UNPKG

autosnippet

Version:

Extract code patterns into a knowledge base for AI coding assistants

113 lines 684 kB
import{r as n,j as e,_ as Ja,$ as jn,a0 as wn,a1 as Nn,a2 as kn,a3 as Ya,a4 as Cn,a5 as Sn,a6 as An,a7 as Qa,a8 as Za,a9 as Xa,aa as Dn,ab as Rn,ac as er,ad as tr,ae as sr,af as In,ag as ar,ah as rr,ai as nr,aj as lr,ak as or,al as ir,am as cr,an as Tn,ao as En,ap as dr,aq as Pn,ar as ur,as as Mn,at as mr,au as pr,av as Ln,aw as Je,ax as it,ay as _n,az as Fn,aA as xr,aB as gr,aC as zn,aD as Bn}from"./vendor-BZEJEVBn.js";import{Z as Be,S as pa,P as Ds,F as Gn,L as $n,a as On,b as Hn,G as Kn,B as qn,H as Ys,c as pt,d as Un,e as Mt,E as Ut,f as Wn,g as hr,T as Vn,W as xa,C as Jn,A as js,h as Ve,i as Wt,j as Ue,k as Yn,l as Ge,m as gs,n as Qn,D as Gs,o as Jt,p as Ct,q as br,I as hs,r as Qs,s as fr,t as ds,R as Yt,M as ut,u as vr,v as Zn,w as Xn,x as el,U as yr,y as tl,z as Le,J as mt,X as ze,K as Ne,N as ot,O as $s,Q as Ke,V as Zs,Y as jr,_ as sl,$ as xt,a0 as Vt,a1 as al,a2 as gt,a3 as Qe,a4 as Ye,a5 as Lt,a6 as rl,a7 as nl,a8 as ll,a9 as Xs,aa as ol,ab as wr,ac as St,ad as il,ae as ea,af as cl,ag as dl,ah as ul,ai as It,aj as qe,ak as At,al as ws,am as ta,an as ml,ao as Nr,ap as Tt,aq as Kt,ar as pl,as as ga,at as ha,au as ba,av as Rs,aw as kr,ax as at,ay as us,az as xl,aA as bt,aB as fa,aC as Et,aD as Cr,aE as Os,aF as st,aG as sa,aH as Hs,aI as Ks,aJ as Sr,aK as Ar,aL as Dr,aM as gl,aN as hl,aO as qt,aP as qs,aQ as Rr,aR as bl,aS as aa,aT as Ir,aU as fl,aV as vl,aW as yl,aX as jl,aY as va,aZ as wl,a_ as Nl}from"./icons-BMNb0V6L.js";import{a as ra}from"./axios-42ANG6Sg.js";import{A as kl,m as Cl}from"./framer-motion-CZfOSYpP.js";import"./yaml-qRaU8Ldn.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const l of o)if(l.type==="childList")for(const i of l.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function a(o){const l={};return o.integrity&&(l.integrity=o.integrity),o.referrerPolicy&&(l.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?l.credentials="include":o.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(o){if(o.ep)return;o.ep=!0;const l=a(o);fetch(o.href,l)}})();const Us={common:{save:"保存",saving:"保存中...",saved:"已保存",cancel:"取消",confirm:"确认",delete:"删除",edit:"编辑",close:"关闭",copy:"复制",copied:"已复制",loading:"加载中...",retry:"重试",refresh:"刷新页面",back:"返回",search:"搜索",noData:"暂无数据",operationFailed:"操作失败",saveFailed:"保存失败",deleteFailed:"删除失败",loadFailed:"加载失败",areYouSure:"Are you sure?",yes:"是",no:"否",all:"全部",none:"无",preview:"预览",apply:"应用",applying:"应用中...",stop:"停止",export:"导出",import:"导入",more:"更多",collapse:"折叠",expand:"展开"},sidebar:{recipes:"Recipes",moduleExplorer:"Modules",candidates:"候选 ({count})",batchManage:"批量管理",depGraph:"依赖关系",knowledgeGraph:"知识图谱",guard:"代码审计",panorama:"全景分析",skills:"Skills",repoWiki:"Wiki",signals:"信号中心",aiAssistant:"AI 助手",help:"使用说明",collapseNav:"折叠导航",expandNav:"展开导航",roleDeveloper:"开发者",roleAgent:"Agent",roleChatAgent:"内置 Agent",modeLogin:"登录",modeProbe:"探针",logout:"登出",tokenLabel:"7日 Token",tokenCalls:"次调用",tokenCallsFull:"{count} 次 AI 调用"},header:{searchPlaceholder:"搜索知识库...",semanticSearch:"语义搜索",semanticSearchTitle:"语义搜索 (AI 向量检索)",semanticSearchFailed:"语义搜索失败。请确保已运行 asd embed 构建索引。",aiSwitchFailed:"切换 AI 失败,请检查项目根目录是否可写。",aiNotConfigured:"AI 未配置 — 点击设置 LLM",configureLlm:"配置 LLM",clickSwitchAi:"点击切换 AI 提供商",switchAi:"切换 AI",mockModeHint:"Mock 模式 — 基于代码结构生成,非 AI 深度分析",mockSwitchToConfirm:"切换到 Mock 模式后,Bootstrap 将生成基于代码结构的伪造数据(非 AI 深度分析)。确定切换?",mockSwitchFromConfirm:`是否清理 Mock 模式产生的伪造数据?
选择「确定」会删除所有 Mock 生成的候选条目。`,editEnvConfig:"修改 .env 配置",closeAiChat:"关闭 AI 对话",openAiChat:"打开 AI 对话",aiChat:"AI 对话",newRecipe:"新建 Recipe",langSwitch:"中 / EN"},commandPalette:{searchPlaceholder:"搜索知识、命令、页面...",noResults:"没有找到结果",recent:"最近",pages:"页面",commands:"命令"},login:{title:"AutoSnippet",subtitle:"连接开发者、AI 与项目知识库",heading:"登录 Dashboard",username:"用户名",password:"密码",usernamePlaceholder:"输入用户名",passwordPlaceholder:"输入密码",usernameRequired:"请输入用户名",passwordRequired:"请输入密码",loginFailed:"登录失败,请重试",loggingIn:"登录中...",loginBtn:"登录",envHint:"登录功能由 VITE_AUTH_ENABLED 环境变量控制"},pagination:{showing:"显示 {start}-{end},共 {total} 条",perPage:"每页",unit:"条",firstPage:"第一页",prevPage:"上一页",nextPage:"下一页",lastPage:"最后一页"},recipes:{title:"Recipe 知识库",sortNewest:"最新",sortAlpha:"A-Z",sortQuality:"质量",sortUsage:"热门",sortCategory:"分类",filterAll:"全部类型",filterKnowledge:"仅 Knowledge",searchPlaceholder:"搜索 Recipes...",totalCount:"共 {count} 条",noResults:"没有匹配的 Recipe",batchActions:"批量操作",selectAll:"全选",deselectAll:"取消全选",batchDelete:"删除选中",batchDeleteConfirm:"确定删除选中的 {count} 条 Recipe?",batchDeleteDone:"已删除 {count} 条",qualityAuthorityScore:"权威分",qualityExcellent:"优秀",qualityGreat:"Great",qualitySolid:"Solid",qualityGood:"Good",qualityBasic:"基础",knowledgeType:"类型",typeKnowledge:"Knowledge",sourceLabel:"来源",sourceBootstrap:"bootstrap",sourceManual:"manual",sourceAiScan:"ai-scan",sourceExtract:"extract",sourceClipboard:"clipboard",editRecipe:"编辑",deleteRecipe:"删除",pushToCandidate:"推入候选",recipeDetail:"Recipe 详情",editBtn:"Edit",description:"描述",markdown:"Markdown",code:"代码",designRationale:"设计原理",steps:"实施步骤",codeChanges:"代码变更",validation:"验证方法",tags:"标签",constraints:"约束条件",guardRules:"Guard 规则",boundaryConstraints:"边界约束",preconditions:"前置条件",sideEffects:"副作用",relations:"关系图 (Relations)",headers:"Headers",noContent:"No content",semanticResults:"语义搜索结果",semanticSimilarity:"相似度",insertToFile:"插入到文件",viewInRecipes:"在 Recipes 中查看",reasoning:"推理依据",sourceColon:"来源:",confidenceColon:"置信度:",alternativesLabel:"备选:",qualityGrade:"质量评级",qualityCompleteness:"完整性",qualityAdaptation:"适配度",qualityDocumentation:"文档度",usageCount:"使用 {count}",emptyValue:"(空)",verificationMethod:"方法:",verificationExpected:"预期:",knowledgeTypes:{codePattern:"代码模式",architecture:"架构设计",bestPractice:"最佳实践",codeStandard:"代码规范",callChain:"调用链路",rule:"规则"}},candidates:{title:"AI 扫描发现的知识模式,审核后升级为 Recipe",tabs:{pending:"待审",approved:"已批准",rejected:"已拒绝"},sortNewest:"最新优先",sortOldest:"最早优先",sortScore:"按质量分",sortConfidence:"按置信度",sortDefault:"默认排序",searchPlaceholder:"搜索候选...",totalCount:"共 {count} 条待审",noResults:"没有待审候选",noPending:"已全部审核",confidenceHigh:"高",confidenceMedium:"中",confidenceLow:"低",sourceBootstrap:"冷启动",sourceManual:"manual",sourceAiScan:"ai-scan",sourceExtract:"extract",sourceClipboard:"clipboard",sourceSignal:"signal",approve:"直接发布",reject:"拒绝",approveAndSave:"审核编辑",batchApprove:"批量批准 ({count})",batchReject:"批量拒绝 ({count})",batchDeleteConfirm:"确定移除选中的 {count} 条候选?",batchDeleteDone:"已删除 {count} 条",approveSuccess:"已批准为 Recipe",rejectSuccess:"已拒绝",aiRefine:"AI 润色",aiEnrich:"AI 补齐",viewDetail:"查看详情",selectAll:"全选",deselectAll:"取消全选",silent:"静默",expandedDetail:"展开详情",collapse:"收起",qualityDimensions:"质量维度",authorityScore:"权威分",trigger:"Trigger",category:"Category",language:"Language",path:"Path",description:"描述",code:"代码",markdown:"Markdown",rationale:"设计原理",tags:"标签",headers:"Headers",confidence:"置信度",source:"来源",createdAt:"创建时间",updatedAt:"更新时间",groupByTarget:"按 Target 分组",clearGroup:"确定移除「{name}」下的全部候选?",clearGroupDone:"已移除 {name} 下的全部候选",coldStartTitle:"项目扫描:结构收集 + 多维度 Candidate 创建",enrichTitle:"① 结构补齐:填充缺失的 rationale / knowledgeType / complexity / scope / steps / constraints(只填空不覆盖,建议先于润色执行)",refineTitle:"② 内容润色:改善 summary 描述、补充架构洞察、推断 relations 关联、调整 confidence 评分(逐条 AI 精炼,建议在结构补齐之后执行)",withCode:"(含代码 {count})",emptyHint:"点击下方按钮启动项目扫描,或使用 CLI 命令手动创建",emptyHintIde:"或在 IDE Agent Mode 中说「帮我扫描项目」",rescanBtn:"增量扫描",rescanTitle:"增量扫描:保留已有 Recipe,重新分析项目,补齐缺失知识",rescanHint:"增量扫描会保留现有 Recipe,仅补齐新发现的维度内容",cleanRebuildBtn:"清理重建",cleanRebuildTitle:"清理重建:清除所有候选与缓存,重新执行完整项目扫描",fullScanBtn:"全量扫描 ·",clipboardCreate:"从剪贴板创建",scanningHint:"各维度知识正在后台提取并接受 AI 审查,完成后候选内容将自动展示",scannedAt:"扫描于 {time}",similarOnly:"只看相似",resetFilters:"重置",approveCurrentPage:"当前页进入审核",removeCurrentPage:"移除当前页",deleteAll:"全部删除",overallScore:"综合 {score}",similarPrefix:"相似",linesCount:"{count} 行",enrichTitleSingle:"① 结构补齐:填充缺失的语义字段(rationale / knowledgeType / complexity 等)",refineTitleSingle:"② 内容润色:改善描述、补充洞察、推断关联(支持自定义提示词)",projectProfile:"项目特写",recipeCompare:"Recipe 对比",refineEnhanced:"润色增强信息",agentNotes:"Agent 笔记:",similarRecipe:"相似 Recipe",similarWith:"与 {name} 相似 {score}%",enrichShort:"补齐",refineShort:"润色",enrichTitleBottom:"① 结构补齐",refineTitleBottom:"② 内容润色",timeJustNow:"刚刚",timeMinutesAgo:"{n} 分钟前",timeHoursAgo:"{n} 小时前",timeDaysAgo:"{n} 天前",confidenceHighLabel:"高",confidenceMediumLabel:"中",confidenceMediumLowLabel:"中低",confidenceLowLabel:"低",sourceAiScanLabel:"AI 全量扫描",sourceMcpLabel:"MCP 提交",sourceManualLabel:"手动创建",sourceFileWatcherLabel:"文件监听",sourceClipboardLabel:"剪贴板",sourceSignalLabel:"信号",sourceSubmitCheckLabel:"AI 审查提交",sourceFallbackLabel:"规则降级"},knowledge:{title:"批量管理",lifecycle:"生命周期",lifecycleCandidate:"Candidate",lifecycleRecipe:"Recipe",lifecycleArchived:"Archived",searchPlaceholder:"搜索知识条目...",totalCount:"共 {count} 条",noResults:"无匹配条目",batchActions:"批量操作",batchPromote:"批量晋升",batchDemote:"批量降级",batchArchive:"批量归档",batchDelete:"批量删除",batchDeleteConfirm:"确定删除选中的 {count} 条知识?",batchDeleteDone:"已删除 {count} 条",selectAll:"全选",deselectAll:"取消全选",detail:"知识详情",detailContent:"内容",detailQuality:"质量",detailMeta:"元数据",qualityCompleteness:"完整度",qualityClarity:"清晰度",qualityRelevance:"关联性",qualityAccuracy:"精确度",qualityUsability:"可用性",authorityScore:"权威分",source:"来源",category:"分类",language:"语言",createdAt:"创建时间",updatedAt:"更新时间",path:"路径",trigger:"触发词",lifecyclePending:"待审核",lifecycleStaging:"预备中",lifecycleActive:"已发布",lifecycleEvolving:"演进中",lifecycleDecaying:"衰退中",lifecycleDeprecated:"已废弃",lifecycleFlow:"生命周期状态流",actionPublish:"发布",actionStage:"预备",actionDeprecate:"废弃",actionReactivate:"重新激活",actionEvolve:"演进",actionDecay:"衰退",actionRestore:"恢复发布",actionUnstage:"回退待审",sourceBootstrap:"AI 全量扫描",sourceMcp:"MCP 提交",sourceManual:"手动创建",sourceFileWatcher:"文件监听",sourceClipboard:"剪贴板",sourceCli:"CLI",sourceAgent:"AI Agent",sourceSubmitCheck:"AI 审查提交",allCategories:"所有分类",selectedCount:"已选 {count} 条",batchPublish:"批量发布",quickBatchPublish:"快速批量发布",batchPublishResult:"发布 {success} 条,失败 {fail} 条",batchPublishFailed:"批量发布失败",batchPublishComplete:"批量发布完成",batchDeleteResult:"删除 {success} 条,失败 {fail} 条",batchDeleteFailed:"批量删除失败",batchDeprecate:"批量废弃",batchDeprecateResult:"废弃 {success} 条,失败 {fail} 条",batchDeprecateFailed:"批量废弃失败",noDeprecatable:"选中条目中没有可废弃的(仅已发布/演进中状态可废弃)",noAutoApprovable:"当前没有可自动通过的待审核条目",noPublishable:"无可发布项",autoPublishResult:"已发布 {count} 条可自动通过的条目",autoApprovable:"可自动通过",clearFilters:"清除筛选条件",loadFailed:"加载知识条目失败",operationSuccess:"操作成功",deleteConfirmMsg:"确定删除「{title}」?此操作不可恢复。",deleteSuccess:"已删除「{title}」",deleteFailed:"删除失败",deprecateReasonPrompt:"请输入废弃原因:",rejectionReason:"驳回原因",summary:"摘要",relatedKnowledge:"关联知识",reasoning:"推理依据",confidence:"置信度",alternatives:"备选",qualityGrade:"质量评级",qualityAdaptation:"适配度",qualityDocumentation:"文档度",qualityCompletionLabel:"完整性",markdownDoc:"Markdown 文档",importHeaders:"导入头文件",codePattern:"代码 / 标准用法",designRationale:"设计原理",implementSteps:"实施步骤",constraintsLabel:"约束条件",aiInsight:"AI 洞察",lifecycleHistoryLabel:"生命周期历史",scope:"范围",scopeUniversal:"通用",scopeProject:"项目级",scopeModule:"模块级",complexity:"复杂度",complexityAdvanced:"高级",complexityIntermediate:"中级",complexityBeginner:"初级",sourceFile:"源文件",prev:"上一条",next:"下一条",narrow:"收窄",widen:"展宽",guardHits:"Guard",adoptions:"采纳",searchHits:"搜索",statViews:"浏览",statApplications:"应用",published:"发布"},knowledgeGraph:{title:"知识图谱",nodeTypes:"节点类型",nodeRecipe:"Recipe",nodeModule:"Module",nodeFile:"File",nodeSymbol:"Symbol",relationInherits:"继承",relationImplements:"实现",relationCalls:"调用",relationDependsOn:"依赖",relationDataFlow:"数据流",relationConflicts:"冲突",relationExtends:"扩展",relationAssociates:"关联",relationContains:"包含",relationImports:"导入",relationOverrides:"覆盖",relationComposedOf:"组合",relationReferencedBy:"被引用",relationTestedBy:"被测试",relationDocumentedIn:"被记录",tools:"工具",zoomIn:"放大",zoomOut:"缩小",resetView:"重置视图",fitView:"适应画布",toggleLabels:"显示/隐藏标签",nodeDetail:"节点详情",relatedNodes:"关联节点",noSelection:"点击节点查看详情",legend:"图例",searchPlaceholder:"搜索节点...",noResults:"没有匹配的节点",totalNodes:"共 {count} 个节点",totalEdges:"共 {count} 条边",loadFailed:"加载知识图谱失败",empty:"知识图谱为空",emptyDesc:"当前没有 Recipe 之间的关系数据。点击下方按钮让 AI 自动分析已有 Recipe 之间的潜在关系(requires / extends / enforces / calls 等)。",discoverRelations:"AI 发现关系",discovering:"AI 分析中…",refresh:"刷新",retry:"重试",statsLabel:"{nodes} 节点 · {edges} 关系",cancelSelection:"取消选中",outEdges:"出边(依赖)",inEdges:"入边(被依赖)",none:"无",relationRequires:"需要",relationEnforces:"约束",relationPrerequisite:"前置",relationReferences:"引用",relationAlternative:"替代",relationDeprecatedBy:"废弃",relationSolves:"解决",discoverAnalyzing:"AI 分析中…(已运行 {elapsed}s)",discoverPollTimeout:"轮询超时,任务可能仍在后台运行。请稍后刷新页面查看结果。",discoverNoResults:"分析完成,共检查 {pairs} 对 Recipe,未发现关系。待 Recipe 数量增加后可再次尝试。",discoverBatchErrors:"分析完成,但 {errors} 个批次 AI 调用失败,未发现关系。请检查 AI Provider 配置。",discoverSuccess:"发现 {count} 条关系(共分析 {pairs} 对{failMsg})",discoverBatchFailed:",{count} 个批次失败",discoverAiNotConfigured:"AI 服务未配置: {error}",discoverTimeout:"任务超时: {error}",discoverFailed:"发现失败: {error}",discoverRunning:"AI 分析仍在进行中…",discoverStarted:"AI 分析已启动,正在后台运行…",discoverInsufficientRecipes:"Recipe 数量不足,无法分析",discoverPreviousTimeout:"上次任务超时,请重试",discoverAiUnavailable:"AI 服务不可用: {error}",discoverStartFailed:"启动失败: {error}",unknownError:"未知错误",discoverTooltip:"AI 自动发现 Recipe 关系"},guard:{title:"Guard 审计",summary:"概览",totalViolations:"共 {count} 项违规",noViolations:"没有违规项",searchPlaceholder:"搜索规则或文件...",severityError:"错误",severityWarning:"警告",severityInfo:"信息",ruleId:"规则 ID",file:"文件",line:"行",message:"消息",severity:"严重性",statusOpen:"待处理",statusResolved:"已解决",statusIgnored:"已忽略",resolve:"标记为已解决",ignore:"忽略",reopen:"重新打开",aiGenPlaceholder:"例: 禁止在 View 中直接调用网络请求",addRule:"添加规则",refreshAudit:"刷新审计",refreshing:"审计刷新中...",refreshSuccess:"审计已刷新",reportIssue:"提交误报",clearHistory:"清空历史",clearConfirm:"确定清空所有 Guard 违反记录?",addRuleValidation:"请填写规则 ID、说明、正则和至少一种语言",patternLabel:"正则(对每行匹配,JSON 中反斜杠需双写)",languagesLabel:"语言",dimensionLabel:"审查规模",noteLabel:"备注",allLanguages:"所有语言",noMatchingRules:"无匹配规则,请调整筛选条件",violationRecords:"违反记录(共 {runs} 次运行,{count} 处违反)",dimFile:"同文件",dimTarget:"同 target",dimProject:"同项目",rationale:"技术原因",fixSuggestion:"修复建议",sourceRecipe:"来源 Recipe",categorySafety:"安全",categoryCorrectness:"正确性",categoryPerformance:"性能",categoryStyle:"风格",category:"分类",currentProject:"当前项目",dimNoLimit:"不限制",notePlaceholder:"仅作简单模式提示",copyFixSuggestion:"复制修复建议",codeLevelConfigTip:"Code-Level 和 Cross-File 检查(如过度 unwrap、循环 import 等)可通过配置禁用或调整阈值。",codeLevelConfigPath:"配置路径:config/default.json → guard.disabledRules / guard.codeLevelThresholds",metricCompliance:"合规度",metricCoverage:"覆盖率",metricConfidence:"置信度",metricQualityGate:"质量门禁",hintCompliance:"基于违规数量的扣分评估",hintCoverage:"已执行检查 / 计划总检查",hintConfidence:"结果中无不确定项的比例",tabViolations:"违规",tabUncertain:"不确定",tabRules:"规则",tabBoundaries:"边界",tabAudit:"审计日志",noAuditLogs:"暂无审计日志",loadMore:"加载更多",tableHeaders:{rule:"规则",file:"文件",line:"行号",message:"描述",severity:"级别",status:"状态",actions:"操作"}},panorama:{title:"项目全景",overview:"概览",health:"健康度",gaps:"知识空白",modules:"模块",layers:"层级",files:"文件",recipes:"知识条目",coverage:"覆盖率",cycles:"循环依赖",healthScore:"健康评分",avgCoupling:"平均耦合度",highPriorityGaps:"高优先级",noGaps:"未发现知识空白",noData:"暂无全景数据",loading:"加载全景数据...",stale:"数据可能已过期"},skills:{title:"Skills 管理",searchPlaceholder:"搜索 Skills...",totalCount:"共 {count} 条",noResults:"没有匹配的 Skill",addSkill:"新增 Skill",editSkill:"编辑 Skill",deleteSkill:"删除 Skill",deleteConfirm:"确定删除此 Skill?",deleteSuccess:"已删除",saveSuccess:"已保存",skillName:"名称",skillNamePlaceholder:"输入 Skill 名称",skillDescription:"描述",skillDescPlaceholder:"输入 Skill 描述",skillTrigger:"触发器",skillTriggerPlaceholder:"输入触发条件",skillAction:"动作",skillActionPlaceholder:"输入动作内容",skillEnabled:"已启用",skillDisabled:"已禁用",toggleEnable:"启用/禁用",aiRecommend:"AI 推荐",aiRecommendDesc:"基于项目分析,AI 推荐以下 Skills",aiRecommending:"AI 分析中...",aiRecommendSuccess:"已推荐 {count} 条",aiRecommendFailed:"推荐失败",acceptRecommend:"采纳",rejectRecommend:"忽略",bulkAccept:"全部采纳",signalBadge:"信号",category:"类别",priority:"优先级",priorityHigh:"高",priorityMedium:"中",priorityLow:"低",subtitle:"Agent 技能文档 — 指导 AI 如何正确使用 AutoSnippet 工具",fetchFailed:"获取 Skills 列表失败",loadError:"不存在或读取出错",loadSkillFailed:"加载 Skill 失败",updateSuccess:"更新成功",updateFailed:"更新 Skill 失败",deleteFailed:"删除 Skill 失败",createSuccess:"创建成功",createFailed:"创建 Skill 失败",createAddedToKB:"已创建并加入知识库",filterProject:"项目级",filterBuiltin:"内置",noRecommendations:"当前暂无推荐。继续使用后会积累更多信号。",aiRecommendTooltip:"基于使用模式分析推荐 Skill",creating:"创建中",useCase:"适用",chars:"字符",related:"相关",confirmDelete:"确认删除",deleteSkillConfirmMsg:'删除 Skill "{name}"?此操作不可撤销。',selectToView:"选择左侧 Skill 查看详情",checkGenerated:"请检查并确认生成的内容",aiGenerated:"AI 已生成 Skill",aiGenFailed:"AI 生成失败",fillRequired:"请填写名称、描述和内容",savedToKB:"已保存到知识库",aiGenMode:"AI 生成",manualMode:"手动填写",describeSkill:"描述你想创建的 Skill",aiGeneratingContent:"AI 正在生成...",generateSkill:"生成 Skill",skillContent:"Skill 文档内容",createdBy:{manual:"手动创建","user-ai":"AI 协助创建","system-ai":"自动创建","external-ai":"外部 AI 创建"}},depGraph:{title:"依赖关系图",searchPlaceholder:"搜索模块...",noResults:"没有匹配的模块",totalModules:"共 {count} 个模块",totalDeps:"共 {count} 条依赖",layout:"布局",layoutTree:"树形",layoutForce:"力导向",layoutCircular:"环形",zoomIn:"放大",zoomOut:"缩小",resetView:"重置视图",fitView:"适应画布",nodeDetail:"模块详情",dependencies:"依赖",dependents:"被依赖",legend:"图例",noSelection:"点击节点查看详情",depTypes:{direct:"直接依赖",transitive:"传递依赖",devOnly:"开发依赖"},refresh:"刷新",retry:"重试",noDataTitle:"当前项目内未扫描到模块依赖关系。",noDataDesc:"请确保项目包含模块定义文件(go.mod / package.json / Package.swift / build.gradle 等),然后点击 Refresh 重新扫描。",filterAll:"全部",filterInternal:"内部包",filterExternal:"外部依赖",packages:"包",packageList:"包列表",depRelations:"依赖关系(小图)",depRelationsDesc:"主图不显示连线,点击节点可在浮窗查看该包依赖;此处列出全部 From → To。",labelExternal:"外部",labelInternal:"内部",labelIndirect:"间接",projectRoot:"项目根",close:"关闭",none:"无",visualization:"模块依赖结构可视化",targetHint:"Target 级节点格式:"},bootstrap:{title:"项目扫描进度",pipelineSteps:{collecting:"收集项目结构",scanning:"扫描源代码",analyzing:"AI 分析",enriching:"知识增强",indexing:"建立索引"},taskStatus:{pending:"等待中",running:"执行中",completed:"已完成",failed:"失败",skipped:"已跳过"},stats:{totalFiles:"文件总数",totalTargets:"Target 数",totalRecipes:"Recipe 数",totalTime:"总耗时",aiCalls:"AI 调用数"},notifications:{started:"项目扫描已开始",completed:"项目扫描完成",failed:"项目扫描失败",partialComplete:"部分完成"},retryFailed:"重试失败任务",viewDetails:"查看详情",dimLabels:{architecture:"架构与设计",codingStandards:"代码规范",designPatterns:"设计模式",errorResilience:"错误韧性",concurrencyAsync:"并发与异步",dataEventFlow:"数据与事件流",networkingApi:"网络通信",uiInteraction:"界面交互",testingQuality:"测试质量",securityAuth:"安全认证",performanceOptimization:"性能优化",observabilityLogging:"可观测性",agentGuidelines:"Agent 注意事项",swiftObjcIdiom:"Swift/ObjC 惯用法",tsJsModule:"TS/JS 模块",pythonStructure:"Python 结构",jvmAnnotation:"JVM 注解",goModule:"Go 模块",rustOwnership:"Rust 所有权",csharpDotnet:"C#/.NET",reactPatterns:"React 模式",vuePatterns:"Vue 模式",springPatterns:"Spring 模式",swiftuiPatterns:"SwiftUI 模式",djangoFastapi:"Django/FastAPI",bootstrap:"Bootstrap"},pipelineLabels:{architecture:"架构模式","coding-standards":"代码规范","design-patterns":"设计模式","error-resilience":"错误韧性","concurrency-async":"并发与异步","data-event-flow":"数据与事件流","networking-api":"网络通信","ui-interaction":"界面交互","testing-quality":"测试质量","security-auth":"安全认证","performance-optimization":"性能优化","observability-logging":"可观测性","agent-guidelines":"Agent 开发注意事项","swift-objc-idiom":"Swift/ObjC 惯用法","ts-js-module":"TS/JS 模块导出","python-structure":"Python 包结构","jvm-annotation":"JVM 注解体系","go-module":"Go 模块","rust-ownership":"Rust 所有权","csharp-dotnet":"C#/.NET 模式","react-patterns":"React 模式","vue-patterns":"Vue 模式","spring-patterns":"Spring 模式","swiftui-patterns":"SwiftUI 模式","django-fastapi":"Django/FastAPI"},pipelineDescs:{architecture:"分层架构、模块职责、依赖关系、技术栈","coding-standards":"命名约定、注释风格、文件组织","design-patterns":"单例、委托、工厂、观察者等模式","error-resilience":"错误处理、异常恢复、防御性编程","concurrency-async":"线程安全、异步模式、竞态防护","data-event-flow":"事件传播、数据持久化、状态管理","networking-api":"API 契约、请求模式、重试策略","ui-interaction":"UI 组件规范、生命周期、导航","testing-quality":"测试模式、Mock 策略、CI/CD","security-auth":"认证授权、加密、权限控制","performance-optimization":"内存管理、懒加载、缓存策略","observability-logging":"日志规范、事件追踪、监控诊断","agent-guidelines":"强制规范、废弃 API、架构约束","swift-objc-idiom":"宏定义、Category/Extension、Swift-ObjC 互操作","ts-js-module":"barrel export、导出约定、循环依赖","python-structure":"包结构、导入约定、类型标注","jvm-annotation":"DI 注解、ORM 映射、自定义注解","go-module":"go.mod、internal 包、接口设计","rust-ownership":"所有权模式、Trait 设计、unsafe 约束","csharp-dotnet":"DI 注册、LINQ、Entity Framework","react-patterns":"组件结构、状态管理、路由模式","vue-patterns":"Composition API、Pinia、路由守卫","spring-patterns":"Bean 配置、分层架构、事务策略","swiftui-patterns":"View 结构、状态管理、导航","django-fastapi":"App 结构、API 设计、中间件"},statusLabels:{skeleton:"等待中",filling:"填充中",completed:"已完成",failed:"失败"},allCompleted:"全部完成",completedWithErrors:"完成(有错误)",elapsed:"已用",estimatedRemaining:"预计剩余",toolCalls:"工具调用",dimensions:"{done}/{total} 维度",notifySuccess:"{completed} 个维度全部填充成功",notifyPartial:"{completed}/{total} 成功,{failed} 失败",coldStartComplete:"项目扫描完成",close:"关闭",cancel:"取消",reviewPipeline:"AI 审查管线",reviewRounds:{round1Label:"资格审查",round1Desc:"过滤误报 · 识别合并",round2Label:"内容精炼",round2Desc:"AI 改写摘要 · 动态置信度",round3Label:"去重 & 关系",round3Desc:"语义去重 · 关系推断"},round1Done:"保留 {kept} · 合并 {merged} · 丢弃 {dropped}",round2Progress:"{current}/{total} 条",round2Done:"已精炼 {refined}/{total} 条",round3Done:"去重后 {afterDedup} 条 · {relationsFound} 条关系",noMatch:"✓ 无匹配内容",featuresOnly:"✓ {sourceCount} 项特征",featuresAndCandidates:"✓ {sourceCount} 项特征 · {extracted} 条候选",candidatesOnly:"✓ {extracted} 条候选"},wiki:{title:"Repo Wiki",sidebar:"Wiki",fileCount:"{count} 篇",searchPlaceholder:"搜索文件...",generating:"文件生成中,新文档将自动出现…",backToList:"返回文件列表",aiBadge:"AI 增强",copySuccess:"已复制",copyBtn:"复制",loadFailed:"加载失败",incrementalUpdate:"增量更新",fullGeneration:"全量生成",genStarted:"Wiki 生成已启动",genFailed:"生成失败",selectPlaceholder:"从左侧文件树选择,或使用下方快捷入口",phases:{outline:"大纲",content:"内容",review:"审校"},fileTypes:{overview:"概述",module:"模块",api:"API",guide:"指南"},synced:"同步",wikiGenerating:"Wiki 正在生成中",outOfDateHint:"检测到代码变更,Wiki 可能已过期,建议增量更新",emptyTitle:"尚未生成 Repo Wiki",emptyDesc:"Wiki 在冷启动时自动全量生成,后续通过增量更新保持同步",emptyHint:"运行 asd setup 冷启动 · asd wiki --update 增量更新",quickOverview:"项目概述",quickOverviewDesc:"项目信息、技术栈与数据统计",quickArch:"架构总览",quickArchDesc:"模块依赖图、项目结构分析",quickStart:"快速上手",quickStartDesc:"构建、运行与入口分析",quickProtocols:"协议与组件",quickProtocolsDesc:"核心协议、委托和组件关系",selectFile:"选择一个文件开始阅读",lastGenerated:"最后生成",duration:"耗时",incrementalUpdating:"增量更新中...",loadFailedDesc:"无法读取文件内容。"},aiChat:{title:"AI Assistant",emptyTitle:"开始与 AI 对话",emptyDesc:"你可以询问项目相关问题,AI 将帮你分析代码、推荐模式。",inputPlaceholder:"输入你的问题...",inputHint:"Enter 发送 · Shift+Enter 换行",thinking:"AI 思考中...",analyzing:"AI 正在分析...",topicPanel:"话题列表",newTopic:"开启新话题",deleteTopic:"删除话题",deleteTopicConfirm:"确定删除此话题?",quickPrompts:{analyzeArch:"分析项目架构",findDuplicates:"查找重复代码",suggestOptimize:"推荐优化方向"},timeJustNow:"刚刚",timeMinutesAgo:"{n} 分钟前",timeHoursAgo:"{n} 小时前",timeDaysAgo:"{n} 天前",codeBlock:"代码块",diffView:"变更对比",diffBefore:"Before",diffAfter:"After",contextLabel:"AI Context / 项目特写",copyCode:"复制代码",topicRecords:"话题记录",noHistory:"暂无聊天记录",autoSaveHint:"开始对话后自动保存",topicCount:"{count} 个话题 · 本地存储",askAnything:"询问任何关于项目的问题",startChat:"开始 AI 对话",emptyDescLong:"询问关于你项目的任何问题 — 代码分析、架构建议、优化方向等。",aiAssistant:"AI 助手",messageCount:"{n} 条",requestFailed:"请求失败: {error}",cancelled:"(已取消)",expandTopics:"展开话题列表",diffEmpty:"(空)",quickPromptSummarize:"总结项目概况"},help:{title:"使用说明",gettingStarted:"快速开始",commands:"命令参考",faq:"常见问题",tokenUsage:"Token 用量",about:"关于",pageTitle:"AutoSnippet 使用说明",subtitle:"连接开发者、AI 与项目知识库:知识挖掘自我进化 · 规范治理 AI 编码产出 · 多语言支持",techSpecs:"Node.js ≥ 22 · 18 MCP 工具 · 5 Skills · Agent Runtime · AST · VSCode Extension · Vector",viewGithub:"查看 GitHub",fullDocs:"完整文档",tokenUsageLast7Days:"Token 用量(近 7 日)",quickStart:"快速开始",coreConcepts:"核心概念",coreFeatures:"核心功能",editorDirectives:"编辑器指令",cursorIntegration:"IDE 集成",v3Architecture:"V3 架构",cliReference:"命令行速查",step1Title:"安装与初始化",step2Title:"启动 Dashboard",step2Desc:"启动 HTTP API + Dashboard + FileWatcher",step3Title:"IDE 集成",step3Desc:"安装 MCP + Skills + Cursor Rules + VSCode Extension",step4Title:"冷启动知识库",step4Desc1:"多维度 AI 扫描代码库",step4Desc2:"生成 Candidate → Dashboard 审核 → Recipe",threeRoles:"三大角色",roleColumn:"角色",responsibilityColumn:"职责",capabilityColumn:"能力",roleDeveloper:"开发者",roleCursorAgent:"IDE Agent",roleChatAgent:"内置 Agent",developerResp:"审核与决策、维护项目标准",cursorAgentResp:"按规范生成代码、检索知识库、管理任务",chatAgentResp:"冷启动分析、飞书编程、Skills 推荐、扫描审查",coreComponents:"核心组件",bootstrapLabel:"Bootstrap(冷启动)",bootstrapDesc:"14 维度 × 7 阶段双路径知识提取引擎",candidatesLabel:"Candidates(候选)",candidatesDesc:"V3 结构化候选条目,Agent 只提交、人类审核",recipeLabel:"Recipe(配方)",recipeDesc:"统一 V3 知识模型 + 知识图谱关系网络",chatAgentLabel:"Agent 运行时(统一引擎)",chatAgentDesc:"单一 Runtime + Preset 配置驱动,支撑所有 AI 能力",searchPipelineLabel:"4 层检索管线",searchPipelineDesc:"5 层漏斗 + 6 信号精排 + Cross-Encoder AI 重排",guardLabel:"Guard(代码审查)",guardDesc:"知识驱动规则,写码即检测;Agent 静默自修复",knowledgeLoop:"知识库闭环",loopStep1:"发现提取",loopStep1Sub:"Bootstrap / Agent / Cursor",loopStep2:"审核筛选",loopStep2Sub:"自动 + 人工",loopStep3:"持久化",loopStep3Sub:".md + DB + 图谱",loopStep4:"交付使用",loopStep4Sub:"IDE / Agent / Guard",loopStep5:"反馈学习",loopStep5Sub:"规则精度 + 质量评分",knowledgeBuild:"知识库构建",semanticSearchLabel:"语义检索",codeAudit:"代码审查(Audit)",dataSync:"数据同步",usageExamples:"使用示例",exampleSearchKB:"检索知识库",exampleSearchKBDesc:'对 Cursor 说:"查找网络请求错误处理的代码"',exampleBatchScan:"批量扫描",exampleBatchScanDesc:'对 Cursor 说:"扫描 NetworkModule,生成 Recipes 到候选"',exampleSubmitCode:"提交代码",exampleSubmitCodeDesc:'对 Cursor 说:"把这段代码保存为 Recipe"',skills10:"5 个 Skills",mcp16:"18 个 MCP 工具(参数化统合)",bootstrapEngine:"Bootstrap 冷启动引擎",bootstrapEngineDesc:"3 步完成知识库从 0 → 1:",fourLayerPipeline:"4 层检索管线",fourLayerPipelineDesc:"多信号融合的精准检索:",chatAgentSystem:"ChatAgent 对话系统",chatAgentSystemDesc:"多 Agent 协作架构,可持续扩展:",fiveEntryChannels:"六个入口通道",initAndEnv:"初始化与环境",kbManagement:"知识库管理",searchAndAudit:"搜索与审查",maintenanceUpgrade:"维护与升级",footerHint:"需要更详细的说明?查看 {link} 或运行 {cmd} 检查环境",footerGithubReadme:"GitHub README",mcpWriteNote:"写操作工具(submit_knowledge、guard、bootstrap 等)通过 Gateway 权限 / 宪法 / 审计三重保护。",editorDirectivesNote:"需先运行 asd watch 或 asd ui;支持快捷写法 asc / ass / asa",createDirective:"创建 Recipe",searchDirective:"搜索并插入",auditDirective:"代码审查",includeDirective:"自动注入头文件/模块",developerCap:'Dashboard 审核候选、保存 Recipe;<code class="bg-slate-100 px-1 rounded">// as:search</code> 检索知识;运行 <code class="bg-slate-100 px-1 rounded">asd ui</code>',cursorAgentCap:"11 个 Skills 理解规范;22 个 MCP 工具按需检索、提交候选;写操作经 Gateway 审核;TaskGraph DAG 任务编排 + tokenBudget 感知消费",chatAgentCap:'统一 AgentRuntime 驱动;飞书 Lark Preset 编程对话;Skills 智能推荐 + 自动注入;<code class="bg-slate-100 px-1 rounded">asd coldstart</code> 冷启动 + <code class="bg-slate-100 px-1 rounded">asd ais</code> 扫描',bootstrapBullet1:"14 维度知识提取(7 通用 + 7 语言),按语言/框架自动激活",bootstrapBullet2:"双路径:Analyst/Producer AI 管线 或 IDE Agent + MCP",bootstrapBullet3:"副产品自动生成:Repo Wiki + 4 Project Skills + Phase 6 AI 润色",candidatesBullet1:"V3 格式 16+ 必填字段,Reasoning 强验证",candidatesBullet2:"Jaccard 0.85 去重 + 严格权限:Agent 只能提交候选",candidatesBullet3:"来源:AI 扫描 / Cursor / 剪贴板 / Dashboard,完整生命周期管理",recipeBullet1:"融合 kind(rule/pattern/fact)+ 12 knowledgeType + 8 图谱关系",recipeBullet2:'<code class="bg-blue-100 px-1 rounded">kind=rule</code> 自动成为 Guard 规则,知识→规范→检测闭环',recipeBullet3:'.md = 唯一数据源,<code class="bg-blue-100 px-1 rounded">asd sync</code> 增量同步 → DB',chatAgentCompBullet1:"统一 AgentRuntime + 4 策略 + CoALA(感知→记忆→推理→行动)",chatAgentCompBullet2:"三层记忆 + 三级上下文压缩 + 5 Provider 自动 fallback",chatAgentCompBullet3:"AgentRouter 5 级意图级联:手动→渠道→关键词→LLM→默认 chat",searchPipelineBullet1:"倒排索引召回 → Cross-Encoder AI 重排 → E-E-A-T 粗排 → 6 信号精排",searchPipelineBullet2:"自研中英文加权字段分词 + 会话上下文感知重排",searchPipelineBullet3:"search MCP 工具:5 种模式路由,单次 40 候选 AI 评分",guardCompBullet1:"三源规则:内置 + 知识库 kind=rule 自动衍生 + Enhancement Pack 扩展",guardCompBullet2:"Agent 自修复回路:违规 + 内联 Recipe 修复指南 → 静默修复 → 再检测(最多 5 轮)",guardCompBullet3:"VSCode 实时诊断 + Quick Fix;FeedbackLoop 自动跟踪修复、学习规则精度",kbBuildBullet1:'<strong>AI 扫描</strong>:<code class="bg-slate-100 px-1 rounded text-xs">asd ais [Target]</code> 批量提取',kbBuildBullet2:'<strong>Cursor 扫描</strong>:对 Copilot 说 "扫描 Module"',kbBuildBullet3:"<strong>手动创建</strong>:New Recipe → Use Copied Code",kbBuildBullet4:'<strong>编辑器内</strong>:复制代码 → <code class="bg-slate-100 px-1 rounded text-xs">// as:create -c</code>',semSearchBullet1:"<strong>4 层管线</strong>:InvertedIndex → CoarseRanker → MultiSignalRanker → RetrievalFunnel",semSearchBullet2:'<strong>编辑器内</strong>:<code class="bg-slate-100 px-1 rounded text-xs">// as:search keyword</code>',semSearchBullet3:"<strong>Cursor MCP</strong>:search 统合工具(mode 路由 5 种模式)",semSearchBullet4:"<strong>Dashboard</strong>:搜索框支持语义 + 关键词",auditFeatureBullet1:'<strong>文件审查</strong>:<code class="bg-slate-100 px-1 rounded text-xs">// as:audit</code>',auditFeatureBullet2:'<strong>Target 审查</strong>:<code class="bg-slate-100 px-1 rounded text-xs">// as:audit target</code>',auditFeatureBullet3:'<strong>Guard 审查</strong>:MCP <code class="bg-slate-100 px-1 rounded text-xs">guard</code>(code / files 参数)',auditFeatureBullet4:"<strong>Dashboard</strong>:Guard 页面可视化审查",syncBullet1:'<strong>同步</strong>:<code class="bg-slate-100 px-1 rounded text-xs">asd sync</code> .md → DB(增量)',syncBullet2:'<strong>Hash 校验</strong>:<code class="bg-slate-100 px-1 rounded text-xs">_contentHash</code> 检测手动编辑',syncBullet3:"<strong>向量索引</strong>:启动时自动构建语义索引",syncBullet4:'<strong>依赖图</strong>:<code class="bg-slate-100 px-1 rounded text-xs">structure</code>(operation: targets / files)MCP 工具',coreFeaturesDesc:"覆盖知识采集、智能检索、代码合规、任务编排、文档生成、数据同步六大能力",kbBuildDesc:"多通道采集,AI 驱动的知识库全生命周期管理",semSearchDescShort:"4 层管线融合 FieldWeighted + keyword + semantic 三路信号",guardCompliance:"Guard 合规闭环",guardComplianceDesc:"规则审查 → 诊断波浪线 → 灯泡修复,代码合规闭环",featureTaskGraphTitle:"TaskGraph 任务编排",featureTaskGraphDesc:"DAG 任务图 + tokenBudget 感知,结构化管理复杂工程任务",featureTaskGraphBullet1:"<strong>DAG 模型</strong>:decompose / prime / ready / claim / close 等 15 种操作",featureTaskGraphBullet2:"<strong>tokenBudget 感知</strong>:自动裁剪详情级别(CRITICAL &lt; 5K, WARNING &lt; 20K)",featureTaskGraphBullet3:"<strong>MCP + VSCode</strong>:task 工具 + lm.registerTool 原生集成",featureTaskGraphBullet4:"<strong>Prime 预热</strong>:自动注入 Mission Briefing + 关键上下文",wikiDocGen:"Wiki 文档生成",wikiDocGenDesc:"Agent 驱动的项目文档自动生成与维护",wikiDocBullet1:"<strong>wiki(plan)</strong>:扫描项目 → 规划主题 + 数据包",wikiDocBullet2:"<strong>wiki(finalize)</strong>:meta.json 汇总 + 去重 + 文件验证",wikiDocBullet3:"<strong>知识聚合</strong>:基于 Recipe 自动生成开发文档",wikiDocBullet4:"<strong>增量更新</strong>:版本追踪 + 差异合并",syncDescShort:"增量同步、Hash 校验、向量索引、依赖图分析",createDirBullet1:"无选项:打开 Dashboard",createDirBullet2:"<code>-c</code>:从剪贴板静默创建",createDirBullet3:"<code>-f</code>:扫描当前文件",searchDirBullet1:"从知识库检索 Recipe",searchDirBullet2:"选择后插入代码,替换该行",searchDirBullet3:"记录一次人工使用",auditDirBullet1:"无后缀:审查当前文件",auditDirBullet2:"<code>target</code>:审查当前 Target",auditDirBullet3:"<code>project</code>:审查整个项目",includeDirBullet1:"代码中包含此标记",includeDirBullet2:"补全后自动注入 import",skillIntent:"意图路由",skillConcepts:"概念教学",skillCandidates:"候选提交",skillRecipes:"Recipe 检索",skillGuard:"代码合规",skillStructure:"项目结构",skillAnalysis:"深度分析",skillColdstart:"冷启动",skillCreate:"引导创建",skillLifecycle:"生命周期",skillDevdocs:"开发文档",mcpLayerHeader:"层级",mcpToolHeader:"工具",mcpDescHeader:"说明",mcpAgentLayerHeader:"Agent 层(18 个)— 默认对外暴露",mcpAdminLayerHeader:"Admin 层(4 个)— 需设置 ASD_MCP_TIER=admin",mcpHealthDesc:"服务健康检查",mcpCapabilitiesDesc:"服务能力清单(Agent 自发现)",mcpGuardDesc:"code=单文件审查 / files=批量审查",mcpSubmitDesc:"提交候选 / 批量 / 保存文档",mcpEnrichDesc:"AI 润色 / 校验 / 查重",mcpLifecycleDesc:"批量生命周期操作",mcpSearchDesc:"mode 路由 auto / keyword / weighted / semantic / context",mcpKnowledgeDesc:"operation 路由 list / get / insights / confirm_usage",mcpStructureDesc:"operation 路由 targets / files / metadata",mcpGraphDesc:"operation 路由 query / impact / path / stats",mcpCallContextDesc:"调用链上下文:callers / callees / both / impact",mcpSkillDesc:"operation 路由 list / load / create / update / delete / suggest",mcpBootstrapDesc:"无参数,返回 Mission Briefing + 维度任务清单",mcpDimensionCompleteDesc:"维度完成通知 + Checkpoint + Hints 分发",mcpWikiPlanDesc:"文档规划:扫描项目 → 主题 + 数据包",mcpWikiFinalizeDesc:"文档完成:meta.json + 去重 + 文件验证",mcpTaskDesc:"15 种操作:create / ready / claim / close / decompose / prime / stats 等",archBootstrapStep1:"① 项目扫描 → 依赖 / 目录 / 入口分析",archBootstrapStep2:"② AI 批量提取 → Candidate 候选列表",archBootstrapStep3:"③ 审阅 + Promote → Recipe 知识库就绪",archBootstrapNote:"支持 bootstrap → dimension_complete 循环迭代、session 断点续跑",archPipelineL1:"InvertedIndex — 倒排索引快速召回",archPipelineL2:"CoarseRanker — 多维信号粗排",archPipelineL3:"MultiSignalRanker — 多维信号精排",archPipelineL4:"RetrievalFunnel — 漏斗截断 + 上下文装配",archAnalystAgent:"<strong>Analyze 阶段</strong>:分析用户意图 → 检索知识库 → 给出建议 → 信心信号分级",archProducerAgent:"<strong>Produce 阶段</strong>:格式化知识 → 创建候选 → 执行提交 → 结果聚合",archHandoff:"<strong>QualityGate</strong>:PipelineStrategy 三态门控 (pass/retry/degrade)",archMemory:"<strong>轻量记忆</strong>:跨对话偏好/决策/上下文持久化(JSONL,TTL 过期)",archProjectAware:"<strong>项目感知</strong>:自动注入知识库状态(Recipe 分布、候选积压量、Guard 规则数)",archCliDesc:"asd × 18+ 命令",archMcpDesc:"stdio × 16 工具",archHttpDesc:"Express × 18 路由模块",archSkillsDesc:"11 个 Skills",archVscodeDesc:"lm.registerTool × 深度集成",v3ArchDesc:"从冷启动到知识消费,端到端的 AI 工程化架构",archOverviewLabel:"端到端架构流",archOverviewBootstrap:"冷启动",archOverviewKB:"知识库",archOverviewPipeline:"检索管线",archOverviewAgent:"Agent 引擎",archOverviewTask:"TaskGraph",archOverviewOutput:"多通道交付",archOverviewSecurity:"Guard + Gateway(知识驱动验证 + 权限审计)",archOverviewIDE:"IDE 集成(MCP + Skills + Extension 三通道)",ideIntegrationLabel:"IDE 集成",ideIntegrationDesc:"6 种 IDE + 飞书,MCP/Extension/Directives 三通道接入",ideIntegrationBullet1:"MCP Server:16 工具 + Skills 自动发现 + Tier 可见性",ideIntegrationBullet2:"VSCode Extension:11 模块(Guard + CodeLens + #asd Agent + Decision)",ideIntegrationBullet3:'一键 <code class="bg-slate-100 px-1 rounded text-xs">asd setup</code> 生成 Cursor / VS Code / Claude Code 模板',securityLabel:"安全与权限",securityDesc:"Gateway 4 步管线 + 宪法治理 + 3 角色 RBAC",securityBullet1:"Gateway 四步:validate → guard → route → audit,写操作唯一入口",securityBullet2:"3 级信任:外部 Agent 受限 → 内置 Agent 只读+提交 → 开发者全权限",securityBullet3:"SafetyPolicy:命令沙箱 + 文件写入保护 + 全链路审计",constitutionSecurity:"Constitution / Gateway 安全模型",constitutionSecurityDesc:"三重安全保障:权限校验 + 宪法规则 + 审计追踪",archConstitutionBullet1:"<strong>Gateway 权限</strong>:MCP 写操作经 Gateway 层统一拦截",archConstitutionBullet2:"<strong>Constitution 宪法</strong>:YAML 定义的行为准则,约束 AI 操作边界",archConstitutionBullet3:"<strong>审计日志</strong>:全链路操作可追溯,异常自动报警",archConstitutionBullet4:"<strong>Tier 隔离</strong>:Agent / Admin 分层,敏感操作需提升权限",archTaskGraphTitle:"TaskGraph 任务体系",archTaskGraphDesc:"DAG 有向无环图驱动的结构化任务管理:",archTaskGraphBullet1:"<strong>Task DAG</strong>:依赖关系建模 → 拓扑排序 → 并行调度",archTaskGraphBullet2:"<strong>状态机</strong>:pending → ready → claimed → done,自动流转",archTaskGraphBullet3:"<strong>tokenBudget</strong>:剩余 token 感知,智能裁剪任务详情",archTaskGraphBullet4:"<strong>Session 持久化</strong>:断点续跑 + 进度可视化",agentArchTitle:"Agent 架构",agentArchDesc:"统一运行时 + 正交组合配置,驱动所有 AI 能力",agentArchPresetTitle:"4 种 Preset 模式",agentArchPresetDesc:"同一个 AgentRuntime,不同的配置组合:",agentArchPresetChat:"<strong>chat</strong>:对话问答(8 轮 / 120s)— Dashboard 和飞书日常对话",agentArchPresetInsight:"<strong>insight</strong>:深度洞察(24 轮 / 600s)— 冷启动多维度分析 + 知识提取",agentArchPresetLark:"<strong>lark</strong>:飞书对话(12 轮 / 180s)— 飞书渠道知识管理",agentArchPresetRemoteExec:"<strong>remote-exec</strong>:远程执行(6 轮 / 60s)— 终端命令沙箱",agentArchStrategyTitle:"4 种执行策略",agentArchStrategyDesc:"参考 Anthropic Agents 设计模式:",agentArchStrategySingle:"<strong>Single</strong>:单次 ReAct 循环 — 对话、飞书、远程执行",agentArchStrategyPipeline:"<strong>Pipeline</strong>:顺序多阶段 + 质量门控(通过/重试/降级三态)— 扫描分析",agentArchStrategyFanOut:"<strong>FanOut</strong>:并发子任务 + 分层限流 — 冷启动多维度并行",agentArchStrategyAdaptive:"<strong>Adaptive</strong>:运行时自动选择策略 — 动态调度",agentArchCapTitle:"5 种能力集",agentArchCapDesc:"每种能力贡献提示词 + 工具白名单 + 钩子:",agentArchCapConversation:"<strong>Conversation</strong>(9 工具):多轮对话 · 知识检索 · 记忆 · SOUL.md 人格",agentArchCapCodeAnalysis:"<strong>CodeAnalysis</strong>(15 工具):AST 分析 · 类继承 · 调用图 · 代码搜索",agentArchCapKnowledgeProd:"<strong>KnowledgeProduction</strong>(3 工具):带验证的知识提交",agentArchCapScanProd:"<strong>ScanProduction</strong>(2 工具):扫描管线内存收集",agentArchCapSystem:"<strong>SystemInteraction</strong>(8 工具):安全命令 · 文件写入 · 环境探测",agentArchMemoryTitle:"三层记忆体系",agentArchMemoryDesc:"参考 CoALA / MemGPT 设计,Budget-Aware 注入(12.5% 上下文窗口):",agentArchMemoryWorking:"<strong>工作记忆</strong>(ActiveContext):Scratchpad + 观察日志 + 计划追踪",agentArchMemorySession:"<strong>会话记忆</strong>(SessionStore):跨维度报告 + 只读缓存(LRU + TTL)",agentArchMemoryPersistent:"<strong>持久记忆</strong>(PersistentMemory):三维评分 × 记忆合并(SQLite)",agentArchContextTitle:"上下文管理",agentArchContextDesc:"保障长对话不溢出,模型感知 Token 预算:",agentArchContextWindow:"<strong>ContextWindow</strong>:三级压缩 — L1 截断旧工具结果 → L2 摘要历史 → L3 仅保留提示词",agentArchContextTracker:"<strong>ExplorationTracker</strong>:阶段状态机 + 信号检测 + Nudge 引导 + 优雅退出",agentArchToolsTitle:"工具体系",agentArchToolsDesc:"58 个内部工具 + 22 个 MCP 工具,写操作经 Gateway 审计:",agentArchToolsInternal:"<strong>内部工具</strong>(58 个):10 类 — 项目访问 · 查询 · AST · 组合 · Guard · 知识图谱 · 生命周期 · 基础设施 · 系统 · 扫描",agentArchToolsMcp:"<strong>MCP 工具</strong>(22 个):18 Agent 层 + 4 Admin 层,stdio 传输",agentArchRouterTitle:"意图路由",agentArchRouterDesc:"AgentRouter 5 级优先级:手动指定 → 渠道检测 → 关键词正则 → LLM 分类 → 默认 chat",cliSetupDesc:"初始化项目",cliStatusDesc:"环境自检",cliUiDesc:"启动 Dashboard",cliUpgradeDesc:"升级 IDE 集成",cliSyncDesc:".md → DB 增量同步",cliAisDesc:"AI 扫描提取 Candidates",cliAisForceDesc:"强制重新扫描全量",cliWatchDesc:"文件监控 + 指令触发",cliSearchDesc:"搜索知识库",cliSearchSemanticDesc:"语义搜索模式",cliGuardDesc:"Guard 规则检查",cliServerDesc:"单独启动 API 服务",cliUpgradeMcpDesc:"升级 MCP / Skills / Rules",cliInstallFullDesc:"全量安装 IDE 集成",cliSyncForceDesc:"全量重建 DB",cliSyncDryDesc:"预览同步变更",taskGraphLabel:"TaskGraph(任务图)",taskGraphDesc:"为外部 Agent 解构执行步骤,跨会话持久化任务与上下文",taskGraphBullet1:"decompose 拆解 Epic → DAG 子任务,7 种依赖 + 递归就绪检测,完成后自动解锁下游",taskGraphBullet2:"prime 会话恢复:注入进行中任务 + 团队决策 + 知识上下文,不丢进度",taskGraphBullet3:"团队约定持久化 + supersedes 演化链 + 30 天 Stale 自动检测",vscodeExtension:"VSCode Extension",vscodeExtDesc:"基于 lm.registerTool API 的原生 Copilot 深度集成",vscodeExtTaskTool:"TaskGraph 代理工具",vscodeExtTaskToolDesc:"通过 tokenBudget 感知实现 WARNING / CRITICAL 分级保护,CRITICAL 时自动内联 prime 数据",vscodeExtGuardDiag:"保存时 Guard 自动检查",vscodeExtGuardDiagDesc:"onDidSave → Guard API → DiagnosticCollection 波浪线标记 + 灯泡菜单搜索修复",vscodeExtCodeLens:"指令检测 CodeLens",vscodeExtCodeLensDesc:"检测 // as:search / // as:create 等指令,提供可视化操作按钮",vscodeExtCmd1:"autosnippet.search — 搜索知识库(Cmd+Shift+F5)",vscodeExtCmd2:"autosnippet.create — 从选区创建候选",vscodeExtCmd3:"autosnippet.audit — 审计当前文件",vscodeExtCmd4:"autosnippet.auditProject — 审计整个项目",vscodeExtCmd5:"autosnippet.status — 显示连接状态",cliColdstartAndScan:"冷启动与扫描",cliTaskManagement:"任务管理",cliGuardCi:"Guard CI/CD",cliColdstartDesc:"9 维度冷启动知识库",cliGuardCiDesc:"CI/CD 全项目 Guard 检查",cliGuardStagedDesc:"Git staged 文件检查",cliCursorRulesDesc:"生成 Cursor 多通道交付物料",cliMirrorDesc:"镜像到 .qoder / .trae",cliTaskListDesc:"列出任务图谱",cliTaskReadyDesc:"就绪任务 + 知识上下文",cliTaskPrimeDesc:"恢复会话上下文",cliTaskStatsDesc:"任务统计"},moduleExplorer:{title:"Module Explorer",scanTargets:"扫描 Targets",scanning:"扫描中...",scanComplete:"扫描完成",targetFiles:"{count} 个文件",noTargets:"未发现 Target",recipesInTarget:"关联 Recipes",guardSummary:"Guard 概况",guardViolations:"{count} 项违规",noViolations:"无违规",openFile:"打开文件",refreshTree:"刷新文件树",extractFromFile:"提取代码",fileDetail:"文件详情",projectModules:"项目模块 ({count})",addFolderScan:"添加目录扫描",refreshProject:"刷新项目结构",discovererFolderScan:"目录扫描",removeFolder:"移除此目录",fullProjectResults:"全项目扫描结果",moduleLabel:"模块: {name}",reviewResults:"审核提取结果",resultsCount:"{count} 条",candidateSuffix:" Candidate",fullProjectScanning:"全项目扫描中",moduleScanLabel:"模块扫描: {name}",filesInScan:"本次扫描的文件 ({count})",knowledgeExtract:"知识提取",knowledgeExtractHint:"在左侧选择模块扫描,或点击 + 添加任意目录。提取代码模式并生成 Recipe 知识卡片。",guardAuditSummary:"Guard 审计摘要",auditedFiles:"已审计文件:",totalViolationsLabel:"违反总数:",errorsCount:"{count} 错误",warningsCount:"{count} 警告",recipeNotExist:"「{name}」不存在于当前知识库",recipeNotExistTitle:"Recipe 不存在",loadRecipeFailed:"加载 Recipe 失败",browseFailedTitle:"目录浏览失败",browseFailedDefault:"无法加载目录列表",selectFolderTitle:"选择要扫描的目录",scanningDirs:"正在扫描项目目录...",noDirs:"未发现可扫描的目录",sourceFileCount:"{count} 文件",selectFolderHint:"选择包含源码文件的目录,系统将自动检测语言并执行 AI 扫描",modulesTabLabel:"模块 ({count})",foldersTabLabel:"目录"},search:{title:"智能搜索",searchPlaceholder:"输入搜索关键词...",noResults:"未找到匹配结果",resultCount:"找到 {count} 条结果",relevance:"相关度",source:"来源",category:"分类",language:"语言",matchType:"匹配类型",matchExact:"精确",matchFuzzy:"模糊",matchSemantic:"语义匹配",matchKeyword:"关键词匹配",viewRecipe:"查看 Recipe",insertCode:"插入代码",searchFailed:"搜索失败。请重试。",searching:"搜索中...",searchBtn:"搜索",emptyHint:"输入关键词后点击搜索",contextRelevant:"上下文相关",authorityScore:"权威分",usage:"使用",usageCount:"{count}次",recommendReason:"推荐理由",viewFullContent:"查看完整内容",similarity:"相似度",quality:"质量",noContent:"无内容",useRecipe:"使用此知识",importedFrameworks:"导入的框架:",relatedApis:"相关 APIs:"},scanResult:{title:"扫描结果",trigger:"Trigger",triggerPlaceholder:"@kebab-case-id",description:"描述",descPlaceholder:"中文简述 ≤80 字,引用真实类名",category:"分类",language:"语言",code:"代码模板",markdown:"项目特写",rationale:"设计原理",tags:"标签",tagsPlaceholder:"标签: 按 Enter/逗号添加...",headers:"Imports",headersPlaceholder:"#import <Header.h>",confidence:"置信度",confidenceHigh:"高",confidenceMedium:"中",confidenceLow:"低",source:"来源",authorityScore:"权威分",saveAsRecipe:"保存为 Recipe",saveAsKnowledge:"保存知识",discard:"丢弃",keepCandidate:"保留候选",qualityWarning:"质量提醒",lowQualityHint:"该条目质量较低,建议润色后再保存",editBeforeSave:"编辑后保存",triggerRequired:"请输入 Trigger",savedAsRecipe:"已保存并发布为 Recipe",savedToKb:"已保存到 KB",validation:"验证方法",validationMethod:"方法:",validationExpected:"预期:",steps:"实施步骤",codeChanges:"代码变更",constraints:"约束条件",guardRules:"Guard 规则",boundaryConstraints:"边界约束",preconditions:"前置条件",sideEffects:"副作用",relations:"关系图 (Relations)",knowledgeEntryTitle:"知识条目标题",aiScan:"AI 扫描",lifecyclePending:"待审核",lifecycleStaging:"预备中",lifecycleActive:"已发布",lifecycleEvolving:"演进中",lifecycleDecaying:"衰退中",lifecycleDeprecated:"已废弃",saving:"保存中...",cursorDelivery:"Cursor Delivery",aiReasoning:"AI 推理",confidenceLabel:"置信度 {value}%",sourceLabel:"来源:",noArticle:"(无项目特写内容)",noCode:"(无代码模板)",done:"完成",formatHeaders:"格式化",cleanUnused:"清理未引用",addHeader:"+ 添加",usedInCode:"代码中有引用",unusedInCode:"代码中未找到引用",unknown:"无法判断",unreferenced:"未引用",removeTag:"移除",deleteHeader:"删除",module:"模块",mode:"模式",difficulty:"难度",difficultyBeginner:"初级",difficultyIntermediate:"中级",difficultyAdvanced:"高级",highDuplicateRisk:"高重复风险:",compareBeforeSave:"建议先对比再保存",similarRecipes:"相似 Recipe:",referenced:"引用",collapseHeaders:"收起",editHeaders:"编辑"},createModal:{title:"New Recipe",importFromPath:"Import from Project Path",or:"Or",importFromClipboard:"Import from Clipboard",scanFile:"Scan File",useClipboard:"Use Copied Code",pathPlaceholder:"e.g. Sources/MyModule/Auth.swift",aiThinking:"AI is thinking..."},llmConfig:{title:"LLM 配置",provider:"AI Provider",model:"Model",apiKey:"API Key",proxy:"代理",optional:"(可选)",apiKeyPlaceholderSet:"留空保持当前 Key 不变",apiKeyPlaceholderEmpty:"请输入 API Key",envWarning:"项目尚未配置 .env 文件,保存后将自动创建。",cancel:"取消",saved:"已保存",saveToEnv:"保存到 .env",apiKeyRequired:"请填写 API Key",configured:"已配置:",saveSuccess:"保存成功",saveFailed:"保存失败",providers:{gemini:"Google Gemini",openai:"OpenAI",deepseek:"DeepSeek",claude:"Claude",ollama:"Ollama (本地)"},embedTitle:"Embedding 模型",embedHint:"当 Embedding 和 LLM 使用不同提供商时,单独配置 Embedding Provider。不设则跟随 LLM。",embedModel:"Embedding 模型名称",embedProviders:{followLlm:"跟随 LLM"}},recipeEditor:{title:"Edit Recipe",authorityScore:"权威分",path:"Path",description:"描述",markdown:"Markdown 文档",code:"代码 / 标准用法",rationale:"设计原理",steps:"实施步骤",codeChanges:"代码变更",validation:"验证方法",validationMethod:"方法:",validationExpected:"预期:",tags:"标签",constraints:"约束条件",guardRules:"Guard 规则",boundaryConstraints:"边界约束",preconditions:"前置条件",sideEffects:"副作用",relations:"关系图 (Relations)",preview:"Preview",edit:"Edit",cancel:"Cancel",saveChanges:"Save Changes",saving:"保存中...",qualityLevels:{basic:"Basic",good:"Good",solid:"Solid",great:"Great",excellent:"Excellent"},descPlaceholder:"Recipe 摘要描述...",rationalePlaceholder:"为何采用此方案...",relationTypes:{inherits:"继承",implements:"实现",calls:"调用",dependsOn:"依赖",dataFlow:"数据流",conflicts:"冲突",extends:"扩展",associates:"关联"},noContent:"No content",authorityFailed:"设置权威分失败:"},searchModal:{title:"as:search — 选择并插入",keyword:"关键词:",keywordAll:"(全部)",insertTo:"插入到:",noResults:"未找到匹配的 Recipe",quality:"质量:",insertBtn:"插入",inserting:"插入中...",insertSuccess:"✅ 已插入到",insertFailed:"❌ 插入失败"},refineProgress:{refining:"润色中",completed:"已完成",reviewing:"审核中",progress:"{current}/{total}",fields:"字段:",timeElapsed:"已用时",eta:"预计剩余",title:"AI 润色",doneTitle:"AI 润色完成",runningTitle:"AI 润色中",doneMsg:"{refined} 条已更新",doneMsgWithFail:"{refined} 条已更新,{failed} 条失败",progressMsg:"{done}/{total} 条候选",closeBtn:"关闭"},spmCompare:{title:"SPM 版本对比",current:"当前版本",latest:"最新版本",diff:"差异",added:"新增",removed:"移除",changed:"变更",unchanged:"未变",updateAvailable:"可更新",upToDate:"已是最新",updateBtn:"更新依赖",closeBtn:"关闭",package:"包名",from:"从",to:"到",noChanges:"无变更",candidateCopied:"候选内容已复制到剪贴板",recipeCopied:"Recipe 内容已复制到剪贴板",copied:"已复制",deleteConfirm:"确定删除该候选?",deleteFailed:"删除失败",compareTitle:"对比:候选 vs Recipe",deleteCandidate:"删除候选",auditCandidate:"审核候选",editRecipe:"编辑 Recipe",switchRecipe:"切换 Recipe:",candidateTitle:"候选:{title}",copyCandidate:"复制候选",noCode:"(无代码)",aiContextProfile:"AI Context / 项目特写",noGuide:"(无使用指南)",copyRecipe:"复制 Recipe"},silentLabels:{watch:"as:create",draft:"草稿",cli:"CLI",pending:"待审核(24h)",recipe:"新建片段"},lifecycle:{pending:"待审核",staging:"预备中",active:"已发布",evolving:"演进中",decaying:"衰退中",deprecated:"已废弃"},kind:{rule:"规则",pattern:"模式",fact:"事实"},app:{errorBoundary:{title:"页面出现异常",refreshBtn:"刷新页面"},projectRefresh:{success:"Target 列表与文件树已更新",successTitle:"项目结构已刷新",failed:"刷新失败"},extract:{success:"提取结果已进入候选池,请在 Candidates 页审核",successTitle:"提取完成",markerSuccess:"精准锁定标记代码,已加入候选池",normalSuccess:"提取结果已加入候选池",noMarker:"未找到 ASD 标记,AI 将分析完整文件",extracting:"提取中",failed:"Extraction failed"},clipboard:{empty:"请先复制代码到剪贴板",emptyTitle:"剪贴板为空",analyzing:"已收到代码,AI 正在识别可复用模式...",analyzingTitle:"剪贴板分析中",resultMulti:"已识别 {count} 条 Recipe,请在候选池审核",resultTitle:"AI 识别完成",aiFailed:"AI 识别失败",permissionError:"浏览器可能未授权剪贴板访问",permissionTitle:"剪贴板读取失败"},load:{failed:"无法加载项目数据",failedTitle:"加载失败",failedHint:"请确认项目路径有效后重试"},scan:{events:{initializing:"正在启动扫描...",filesLoaded:"已加载 {count} 个源文件",readingFiles:"正在读取 {count} 个文件内容...",aiAnalyzing:"正在 AI 分析提取可复用模式...",enriching:"正在增强 {count} 条结果...",completing:"扫描完成,正在加载结果..."},streamInit:"正在建立流式连接...",completed:"扫描完成",targetSuccess:"发现 {count} 条可复用代码模式,请在右侧审核",targetSuccessTitle:"Target 扫描完成",aiNotConfigured:"AI 未配置",noResults:"AI 扫描未返回结果",noCode:"该 Target 中未找到可复用的代码片段",scanComplete:"扫描完成",scanFailedHint:"请确认 Target 包含有效的源代码文件",scanFailed:"扫描失败",timeout:"扫描超时,请尝试减少 Target 文件数量",timeoutTitle:"扫描超时",scanError:"扫描出错"},coldStart:{collecting:"正在收集项目结构...",skeletonCreated:"骨架已创建,正在后台填充...",skeletonDetail:"项目扫描骨架已创建: {targets} 个 Target, {files} 个文件, {deps} 条依赖...正在后台逐维度填充...",guardSuffix:"Guard: {count} 项违规",timeout:"项目扫描超时,请检查项目文件数量"},rescan:{analyzing:"正在增量扫描...",done:"增量扫描完成",success:"增量扫描完成:保留 {preserved} 条 Recipe,健康 {healthy} 条,衰减 {decayed} 条",filling:"正在后台 AI 补齐 {count} 个维度...",timeout:"增量扫描超时,请稍后重试"},fullScan:{collecting:"正在收集所有 Target 文件...",phase5:"正在收集源文件...",phase15:"正在 AI 分析代码模式...",phase25:"AI 提取中(大项目可能需要数分钟)...",phase35:"AI 提取中...",phase45:"AI 深度分析中...",phase55:"持续处理中...",phase65:"正在运行 Guard 审计...",phase75:"正在汇总结果...",phase85:"即将完成...",partialComplete:"扫描部分完成(超时)",completed:"全项目扫描完成",resultDetail:"全项目扫描完成: {count} 条候选",guardSuffix:"Guard: {count} 处违反",timeoutSuffix:"(部分结果,AI 超时)",noContent:"全项目扫描完成,未发现可提取内容",timeout:"扫描超时,请尝试减少项目文件数量或分 Target 扫描",timeoutTitle:"扫描超时",scanError:"扫描出错"},recipe:{triggerRequired:"请输入 Trigger",savedAsRecipe:"已保存并发布为 Recipe",savedToKb:"已保存到 KB",saveFailed:"保存失败",saveRecipeFailed:"保存 Recipe 失败",deleteFailed:"删除失败"},candidate:{clearConfirm:"确定移除「{name}」下的全部候选?",clearDone:"已移除 {name} 下的全部候选",pushSuccess:"已加入 Candidate 待审核队列",pushFailed:"创建 Candidate 失败"}},globalChat:{refineFields:{summary:"描述",code:"代码 / 标准用法",markdown:"Markdown 文档",rationale:"设计原理",tags:"标签",confidence:"置信度",aiInsights:"AI 洞察",agentNotes:"Agent 笔记",relations:"关联关系"},diff:{noChanges:"未检测到变更",excludedRestore:"已排除 · 恢复",exclude:"排除",before:"Before",after:"After",empty:"(空)"},system:{refinePrefix:`🎯 润色模式 — **{title}**

当前描述: {description}

**输入润色指令,AI 将根据你的指令定向修改候选内容**,下方有常用指令可直接点击使用。`,noDescription:"(无)",changesApplied:"✅ 变更已应用到候选!",exitedRefine:"已退出润色模式,回到通用对话。",refining:"🔄 AI 润色中...",processing:"处理中...",thinking:"🔄 AI 思考中...",cancelled:"(已取消)"},refineTitle:"AI 润色",chatTitle:"AI Chat",refineSubtitle:"润色中...",chatSubtitle:"询问任何关于项目的问题",exitRefine:"退出润色",newTopic:"开启新话题",closeChat:"关闭 AI Chat",emptyTitle:"AI Chat",emptyDesc:"询问项目相关问题,或使用 AI 功能分析代码、润色候选等。",quickPrompts:{analyzeArch:"分析项目架构",findDuplicates:"查找重复代码",suggestOptimize:"推荐优化方向"},refinePrompts:{addExamples:"增加具体使用案例,不要修改其他内容",optimizeComments:"优化代码注释和说明",addCaveats:"补充常见错误用法和注意事项",improveSummary:"提升描述质量,更简洁专业",addPerformance:"补充性能注意事项"},loading:{analyzing:"AI 正在分析...",thinking:"AI 思考中..."},stopBtn:"停止",assistantRefine:"AI 润色助手",assistantChat:"AI 助手",confirmApply:"确认应用",confirmApplyN:"确认应用 ({i}/{total})",applyingBtn:"应用中...",continueAdjust:"继续调整",nextItem:"下一条",inputHintRefine:"Enter 发送 · Shift+Enter 换行 · 先预览再应用",inputHintChat:"Enter 发送 · Shift+Enter 换行",refinePlaceholder:'输入定向润色指令,如"增加使用案例"、"优化描述"...',chatPlaceholder:"输入你的问题...",applySuccess:"候选内容已更新为润色后版本",applySuccessTitle:"润色已应用",applyFailed:"应用失败",refinePreviewFailed:"润色预览失败: {error}",requestFailed:"请求失败: {error}",previewGenerated:"已生成润色预览,共 {count} 个字段变更(可单独关闭变更):",noChangeHint:"未检测到变更,请尝试更具体的指令。",refineTopicPrefix:"润色: {title}",untitled:"未命名"},chatStream:{stepProgress:"🔄 第 {step}/{maxSteps} 轮推理",toolFailed:"失败",toolResultChars:"{size}字符",andNFiles:" 等 {n} 个文件",tools:{get_project_overview:"获取项目概况",list_project_structure:"浏览目录结构",read_project_file:"读取文件内容",search_project_code:"搜索代码",get_file_summary:"获取文件摘要",semantic_search_code:"语义搜索代码",get_class_hierarchy:"分析类继承关系",get_class_info:"获取类详情",get_protocol_info:"获取协议信息",get_method_overrides:"分析方法重写",get_category_map:"获取分类扩展",search_knowledge:"搜索知识库",search_recipes:"搜索代码片段",search_candidates:"搜索候选条目",get_recipe_detail:"获取片段详情",get_related_recipes:"查找关联片段",get_project_stats:"获取项目统计",knowledge_overview:"知识库概览",analyze_code:"分析代码",enrich_candidate:"丰富候选内容",refine_bootstrap_candidates:"润色候选批次",add_graph_edge:"添加知识图谱边",quality_score:"质量评分",submit_knowledge:"提交知识条目",submit_with_check:"提交并查重",save_document:"保存文档",approve_candidate:"审批候选",reject_candidate:"驳回候选",publish_recipe:"发布片段",deprecate_recipe:"废弃片段",update_recipe:"更新片段",record_usage:"记录使用",guard_check_code:"代码规范检查",query_violations:"查询违规记录",list_guard_rules:"列出守卫规则",get_recommendations:"获取推荐",get_feedback_stats:"获取反馈统计",graph_impact_analysis:"影响分析",rebuild_index:"重建索引",query_audit_log:"查询审计日志",bootstrap_knowledge:"引导知识采集",load_skill:"加载技能",create_skill:"创建技能",suggest_skills:"推荐技能",plan_task:"规划任务",review_my_output:"自检输出质量",get_tool_details:"查看工具说明",get_previous_analysis:"回顾历史分析",note_finding:"记录发现",get_previous_evidence:"查阅已有证据"}},chatPanel:{defaultLoading:"AI 正在处理...",defaultEmptyTitle:"输入指令开始对话",defaultEmptyDesc:"描述你希望执行的操作,AI 将为你处理。",defaultAssistant:"AI 助手",defaultPlaceholder:"输入指令...",defaultInputHint:"Enter 发送 · Shift+Enter 换行",docContent:"文档内容"},constants:{bootstrapDims:{architecture:"架构与设计",bestPractice:"规范与实践",eventAndDataFlow:"事件与数据流",objcDeepScan:"深度扫描",agentGuidelines:"Agent 注意事项",bootstrap:"Bootstrap",codeStandard:"代码规范",codePattern:"设计模式",projectProfile:"项目特征",categoryScan:"Category 分类方法"}},tokenUsageChart:{loadFailed:"加载失败",loading:"加载 Token 用量…",totalToken:"总 Token",totalSub:"7 日合计",input:"输入",output:"输出",calls:"调用",avgPerCall:"均 {avg}/次",emptyState:"暂无 Token 使用记录,使用 ChatAgent 或 MCP 后数据将自动记录",dailyUsage:"每日用量",weekday0:"日",weekday1:"一",weekday2:"二",weekday3:"三",weekday4:"四",weekday5:"五",weekday6:"六",dailyDetail:"输入 {input} · 输出 {output}",dailyCalls:"{count} 次调用",legendInput:"输入",legendOutput:"输出",sourceDistribution:"来源分布"},knowledgeGraphRelations:{dependsOn:"依赖",requires:"需要",extends:"扩展",implements:"实现",inherits:"继承",enforces:"约束",associates:"关联",conflicts:"冲突",calls:"调用",prerequisite:"前置",dataFlow:"数据流",references:"引用",alternative:"替代",deprecatedBy:"废弃",solves:"解决",timeout:"超时"},shared:{renderingChart:"渲染图表中…",switchToChinese:"切换到中文"},scanResultCard:{includeMarkOn:"开启:写入 // as:include 标记",includeMarkOff:"关闭:不写入导入标记",formatHeaders:"统一导入格式",cleanUnused:"移除代码中未引用的头文件",similarWithClick:"与 {name} 相似 {score}%,点击对比"},skillsView:{aiPromptPrefix:"请为以下场景创建一个 Skill 文档:",placeholderDesc:"例如:创建一个关于 SwiftUI 动画最佳实践的 Skill...",placeholderName:"SwiftUI 动画最佳实践指南",placeholderContent:`# My Custom Skill

## 使用场景

## 操作步骤`},guardRuleMessages:{"no-main-thread-sync":"禁止在主线程上使用 dispatch_sync(main),易死锁","main-thread-sync-swift":"禁止在主线程上使用 DispatchQueue.main.sync,易死锁","objc-dealloc-async":"dealloc 内禁止使用 dispatch_async/dispatch_after/postNotification 等","objc-block-retain-cycle":"block 内直接使用 self 可能循环引用,建议 weakSelf","objc-assign-object":"assign 用于对象类型会产生悬垂指针,建议改为 weak 或 strong","swift-force-cast":"强制类型转换 as! 在失败时崩溃,建议 as? 或 guard let","swift-force-try":"try! 在异常时崩溃,建议 do-catch 或 try?","objc-timer-retain-cycle":"NSTimer 以 self 为 target 会强引用 self,需在 dealloc 前 invalidate 或使用 block 形式","objc-possible-main-thread-blocking":"sleep/usleep 可能造成主线程阻塞","js-no-eval":"eval() 存在安全风险和性能问题,应避免使用","js-no-var":"使用 let/const 替代 var,避免变量提升问题","js-no-console-log":"生产代码应移除 console.log,使用专用日志库","js-no-debugger":"生产代码中不应包含 debugger 语句","js-no-alert":"生产代码中不应使用 alert(),影响用户体验","ts-no-non-null-assertion":"非空断言 ! 可能掩盖 null/undefined 错误","py-no-bare-except":"裸 except: 会捕获所有异常(含 SystemExit),应指定异常类型","py-no-exec":"exec() 存在安全风险,应避免使用","py-no-mutable-default":"函数默认参数使用可变对象(list/dict/set)会导致共享状态 bug","py-no-star-import":"from module import * 导致命名空间污染,应显式导入","py-no-assert-in-prod":"assert 在 -O 模式下会被移除,不应用于生产逻辑校验","java-no-system-exit":"System.exit() 直接终止 JVM,应抛异常或返回状态码","java-no-raw-type":"使用泛型集合替代原始类型 (如 List<String> 替代 List)","java-no-empty-catch":"空 catch 块会静默吞掉异常,至少应记录日志","java-no-thread-stop":"Thread.stop() 已废弃且不安全,使用 interrupt() 协作式终止","kotlin-no-force-unwrap":"!! 非空断言在值为 null 时抛 NPE,应使用 ?. 或 ?: 安全访问","go-no-panic":"panic 应仅用于不可恢复错误,库代码应返回 error","go-no-err-ignored":"错误值不应用 _ 忽略,应处理或明确标注","go-no-init-abuse":"init() 函数副作用难以追踪,避免在 init 中执行复杂逻辑","go-no-global-var":"全局可变变量导致并发安全问题,考虑使用依赖注入","dart-no-print":"生产代码应使用 logger 替代 print(),便于日志分级和关闭","dart-avoid-dynamic":"避免使用 dynamic 类型,使用具体类型或泛型提升类型安全","dart-no-set-state-after-dispose":"setState 调用前应检查 mounted 状态,避免 disposed 后调用","dart-avoid-bang-operator":"避免使用 ! 空断言操作符,优先使用 ?? 默认值或 ?. 安全调用","dart-prefer-const-constructor":"当所有字段均为 final 时,构造函数应声明为 const 以优化 Widget 重建","dart-no-relative-import":"lib/ 目录内应使用 package: 形式的绝对导入,避免相对路径导入","dart-dispose-controller":"TextEditingController/AnimationController 等须在 dispose() 中释放","dart-no-build-context-across-async":"BuildContext 不应跨越 async gap 使用,可能导致引用已卸载的 Widget"},guardRuleFixSuggestions:{"objc-block-retain-cycle":"声明 __weak typeof(self) weakSelf = self; 后在 block 内使用 weakSelf","swift-force-cast":"使用 as? 配合 guard let / if let 进行安全转换","kotlin-no-force-unwrap":"使用 ?. 安全调用或 ?: 提供默认值","dart-no-set-state-after-dispose":"使用 if (mounted) setState(...) 守卫","dart-avoid-bang-operator":"使用 ?. 安全调用或 ?? 提供默认值","dart-prefer-const-constructor":"移除 new 关键字,并在 Widget 构造调用前加 const","dart-dispose-controller":"在 State.dispose() 中调用 controller.dispose()","dart-no-build-context-across-async":"在 await 前缓存所需数据,或在 await 后检查 mounted"},signals:{title:"信号 & 报告中心",tabSignals:"信号",tabReports:"报告",tabStats:"统计",time1h:"1小时",time6h:"6小时",time24h:"24小时",time7d:"7天",timeAll:"全部",filterPlaceholder:"按类型筛选...",refresh:"刷新",loading:"加载中...",showingSignals:"显示 {shown} / {total} 条信号",showingReports:"显示 {shown} / {total} 条报告",noSignals:"该时间范围内暂无信号",noReports:"该时间范围内暂无报告",noStats:"暂无统计数据",totalSignals:"信号总数",signalTypes:"信号类型",sources:"来源数",byType:"按类型",bySource:"按来源",openMonitor:"打开信号监控",closeMonitor:"关闭信号监控"}},Sl={common:{save:"Save",saving:"Saving...",saved:"Saved",cancel:"Cancel",confirm:"Confirm",delete:"Delete",edit:"Edit",close:"Close",copy:"Copy",copied:"Copied",loading:"Loading...",retry:"Retry",refresh:"Refresh Page",back:"Back",search:"Search",noData:"No data",operationFailed:"Operation failed",saveFailed:"Save failed",deleteFailed:"Delete failed",loadFailed:"Load failed",areYouSure:"Are you sure?",yes:"Yes",no:"No",all:"All",none:"None",preview:"Preview",apply:"Apply",applying:"Applying...",stop:"Stop",export:"Export",import:"Import",more:"More",collapse:"Collapse",expand:"Expand"},sidebar:{recipes:"Recipes",moduleExplorer:"Module Explorer",candidates:"Candidates ({count})",batchManage:"Batch Manage",depGraph:"Dependency Graph",knowledgeGraph:"Knowledge Graph",guard:"Guard",panorama:"Panorama",skills:"Skills",repoWiki:"Repo Wiki",signals:"Signals",aiAssistant:"AI Assistant",help:"Help",collapseNav:"Collapse navigation",expandNav:"Expand navigation",roleDeveloper:"Developer",roleAgent:"Agent",roleChatAgent:"Built-in Agent",modeLogin:"Login",modeProbe:"Probe",logout:"Log out",tokenLabel:"7-Day Tokens",tokenCalls:"calls",tokenCallsFull:"{count} AI calls"},header:{searchPlaceholder:"Search knowledge...",semanticSearch:"Semantic",semanticSearchTitle:"Semantic Search (Brain AI)",semanticSearchFailed:"Semantic search failed. Make sure you have run `asd embed` to build the index.",aiSwitchFailed:"Failed to switch AI provider. Check if the project root is writable.",aiNotConfigured:"AI not configured — click to set up LLM",configureLlm:"Configure LLM",clickSwitchAi:"Click to switch AI provider",switchAi:"Switch AI",mockModeHint:"Mock mode — generated from code structure, not AI deep analysis",mockSwitchToConfirm:"Switching to Mock mode. Bootstrap will generate fake data based on code structure (not AI deep analysis). Continue?",mockSwitchFromConfirm:`Clean up mock-generated data?
Choosing OK will delete all candidates created by Mock mode.`,editEnvConfig:"Edit .env config",closeAiChat:"Close AI Chat",openAiChat:"Open AI Chat",aiChat:"AI Chat",newRecipe:"New Recipe",langSwitch:"EN / 中"},commandPalette:{searchPlaceholder:"Search knowledge, commands, pages...",noResults:"No results found",recent:"Recent",pages:"Pages",commands:"Commands"},login:{title:"AutoSnippet",subtitle:"Connect developers, AI & project knowledge",heading:"Sign in to Dashboard",username:"Username",password:"Password",usernamePlaceholder:"Enter username",passwordPlaceholder:"Enter password",usernameRequired:"Username is required",passwordRequired:"Password is required",loginFailed:"Login failed, please try again",loggingIn:"Signing in...",loginBtn:"Sign in",envHint:"Authentication is controlled by the VITE_AUTH_ENABLED environment variable"},pagination:{showing:"Showing {start}-{end} of {total}",perPage:"Per page",unit:"",firstPage:"First page",prevPage:"Previous page",nextPage:"Next page",lastPage:"Last page"},recipes:{title:"Recipe Knowledge Base",sortNewest:"Newest",sortAlpha:"A-Z",sortQuality:"Quality",sortUsage:"Popular",sortCategory:"Category",filterAll:"All types",filterKnowledge:"Knowledge only",searchPlaceholder:"Search Recipes...",totalCount:"{count} total",noResults:"No matching Recipes",batchActions:"Batch Actions",selectAll:"Select all",deselectAll:"Deselect all",batchDelete:"Delete selected",batchDeleteConfirm:"Delete {count} selected Recipes?",batchDeleteDone:"{count} deleted",qualityAuthorityScore:"Authority",qualityExcellent:"Excellent",qualityGreat:"Great",qualitySolid:"Solid",qualityGood:"Good",qualityBasic:"Basic",knowledgeType:"Type",typeKnowledge:"Knowledge",sourceLabel:"Source",sourceBootstrap:"bootstrap",sourceManual:"manual",sourceAiScan:"ai-scan",sourceExtract:"extract",sourceClipboard:"clipboard",editRecipe:"Edit",deleteRecipe:"Delete",pushToCandidate:"Push to Candidate",recipeDetail:"Recipe Detail",editBtn:"Edit",description:"Description",markdown:"Markdown",code:"Code",designRationale:"Design Rationale",steps:"Implementation Steps",codeChanges:"Code Changes",validation:"Validation",tags:"Tags",constraints:"Constraints",guardRules:"Guard Rules",boundaryConstraints:"Boundary Constraints",preconditions:"Preconditions",sideEffects:"Side Effects",relations:"Relations",headers:"Headers",noContent:"No content",semanticResults:"Semantic Search Results",semanticSimilarity:"Similarity",insertToFile:"Insert to file",viewInRecipes:"View in Recipes",reasoning:"Reasoning",sourceColon:"Source:",confidenceColon:"Confidence:",alternativesLabel:"Alternatives:",qualityGrade:"Quality Grade",qualityCompleteness:"Completeness",qualityAdaptation:"Adaptation",qualityDocumentation:"Documentation",usageCount:"Uses {count}",emptyValue:"(empty)",verificationMethod:"Method:",verificationExpected:"Expected:",knowledgeTypes:{codePattern:"Code Pattern",architecture:"Architecture",bestPractice:"Best Practice",codeStandard:"Code Standard",callChain:"Call Chain",rule:"Rule"}},candidates:{title:"Patterns discovered by AI scan, review to promote as Recipes",tabs:{pending:"Pending",approved:"Approved",rejected:"Rejected"},sortNewest:"Newest first",sortOldest:"Oldest first",sortScore:"By score",sortConfidence:"By confidence",sortDefault:"Default order",searchPlaceholder:"Search candidates...",totalCount:"{count} pending",noResults:"No pending candidates",noPending:"All reviewed",confidenceHigh:"High",confidenceMedium:"Medium",confidenceLow:"Low",sourceBootstrap:"bootstrap",sourceManual:"manual",sourceAiScan:"ai-scan",sourceExtract:"extract",sourceClipboard:"clipboard",sourceSignal:"signal",approve:"Publish",reject:"Reject",approveAndSave:"Review & Edit",batchApprove:"Approve ({count})",batchReject:"Reject ({count})",batchDeleteConfirm:"Remove {count} selected candidates?",batchDeleteDone:"{count} deleted",approveSuccess:"Approved as Recipe",rejectSuccess:"Rejected",aiRefine:"AI Refine",aiEnrich:"AI Enrich",viewDetail:"View Detail",selectAll:"Select all",deselectAll:"Deselect all",silent:"Silent",expandedDetail:"Expanded Detail",collapse:"Collapse",qualityDimensions:"Quality Dimensions",authorityScore:"Authority",trigger:"Trigger",category:"Category",language:"Language",path:"Path",description:"Description",code:"Code",markdown:"Markdown",rationale:"Rationale",tags:"Tags",headers:"Headers",confidence:"Confidence",source:"Source",createdAt:"Created",updatedAt:"Updated",groupByTarget:"Group by Target",clearGroup:'Remove all candidates under "{name}"?',clearGroupDone:"Removed all candidates under {name}",coldStartTitle:"Project Scan: structural collection + multi-dimension Candidate creation",enrichTitle:"① Structure Fill: populate missing rationale / knowledgeType / complexity / scope / steps / constraints (fill only, no overwrite; run before Refine)",refineTitle:"② Content Refine: improve summary, add architectural insights, infer relations, adjust confidence (per-item AI refinement; run after Structure Fill)",withCode:"(with code {count})",emptyHint:"Click the button below to start a project scan, or use CLI to create manually",emptyHintIde:'or say "scan project" in IDE Agent Mode',rescanBtn:"Incremental Scan",rescanTitle:"Incremental Scan: preserve existing Recipes, re-analyze project, fill knowledge gaps",rescanHint:"Incremental scan preserves existing Recipes and only fills newly discovered dimensions",cleanRebuildBtn:"Clean & Rebuild",cleanRebuildTitle:"Clean & Rebuild: clear all candidates and caches, re-execute full project scan",fullScanBtn:"Full Scan ·",clipboardCreate:"From Clipboard",scanningHint:"Knowledge dimensions are being extracted and reviewed by AI in the background. Results will appear automatically.",scannedAt:"Scanned at {time}",similarOnly:"Similar only",resetFilters:"Reset",approveCurrentPage:"Approve current page",removeCurrentPage:"Remove current page",deleteAll:"Delete all",overallScore:"Overall {score}",similarPrefix:"Similar",linesCount:"{count} lines",enrichTitleSingle:"① Structure Fill: populate missing semantic fields (rationale / knowledgeType / complexity, etc.)",refineTitleSingle:"② Content Refine: improve descriptions, add insights, infer relations (supports custom prompts)",projectProfile:"Project Profile",recipeCompare:"Recipe Compare",refineEnhanced:"Refine Enhanced Info",agentNotes:"Agent Notes:",similarRecipe:"Similar Recipes",similarWith:"Similar to {name} {score}%",enrichShort:"Fill",refineShort:"Refine",enrichTitleBottom:"① Structure Fill",refineTitleBottom:"② Content Refine",timeJustNow:"Just now",timeMinutesAgo:"{n} min ago",timeHoursAgo:"{n} hr ago",timeDaysAgo:"{n} days ago",confidenceHighLabel:"High",confidenceMediumLabel:"Medium",confidenceMediumLowLabel:"Med-Low",confidenceLowLabel:"Low",sourceAiScanLabel:"AI Full Scan",sourceMcpLabel:"MCP Submit",sourceManualLabel:"Manual",sourceFileWatcherLabel:"File Watcher",sourceClipboardLabel:"Clipboard",sourceSignalLabel:"Signal",sourceSubmitCheckLabel:"AI Review Submit",sourceFallbackLabel:"Rule Fallback"},knowledge:{title:"Batch Management",lifecycle:"Lifecycle",lifecycleCandidate:"Candidate",lifecycleRecipe:"Recipe",lifecycleArchived:"Archived",searchPlaceholder:"Search knowledge entries...",totalCount:"{count} total",noResults:"No matching entries",batchActions:"Batch Actions",batchPromote:"Promote",batchDemote:"Demote",batchArchive:"Archive",batchDelete:"Delete",batchDeleteConfirm:"Delete {count} selected entries?",batchDeleteDone:"{count} deleted",selectAll:"Select all",deselectAll:"Deselect all",detail:"Detail",detailContent:"Content",detailQuality:"Quality",detailMeta:"Metadata",qualityCompleteness:"Completeness",qualityClarity:"Clarity",qualityRelevance:"Relevance",qualityAccuracy:"Accuracy",qualityUsability:"Usability",authorityScore:"Authority",source:"Source",category:"Category",language:"Language",createdAt:"Created",updatedAt:"Updated",path:"Path",trigger:"Trigger",lifecyclePending:"Pending",lifecycleStaging:"Staging",lifecycleActive:"Active",lifecycleEvolving:"Evolving",lifecycleDecaying:"Decaying",lifecycleDeprecated:"Deprecated",lifecycleFlow:"Lifecycle State Flow",actionPublish:"Publish",actionStage:"Stage",actionDeprecate:"Deprecate",actionReactivate:"Reactivate",actionEvolve:"Evolve",actionDecay:"Decay",actionRestore:"Restore",actionUnstage:"Unstage",sourceBootstrap:"AI Full Scan",sourceMcp:"MCP Submit",sourceManual:"Manual Create",sourceFileWatcher:"File Watcher",sourceClipboard:"Clipboard",sourceCli:"CLI",sourceAgent:"AI Agent",sourceSubmitCheck:"AI Review Submit",allCategories:"All categories",selectedCount:"{count} selected",batchPublish:"Batch Publish",quickBatchPublish:"Quick Publish",batchPublishResult:"{success} published, {fail} failed",batchPublishFailed:"Batch publish failed",batchPublishComplete:"Batch publish complete",batchDeleteResult:"{success} deleted, {fail} failed",batchDeleteFailed:"Batch delete failed",batchDeprecate:"Batch Deprecate",batchDeprecateResult:"{success} deprecated, {fail} failed",batchDeprecateFailed:"Batch deprecate failed",noDeprecatable:"No deprecatable entries selected (only active/evolving can be deprecated)",noAutoApprovable:"No auto-approvable pending entries",noPublishable:"Nothing to publish",autoPublishResult:"{count} auto-approvable entries published",autoApprovable:"Auto-approvable",clearFilters:"Clear filters",loadFailed:"Failed to load knowledge entries",operationSuccess:"Operation successful",deleteConfirmMsg:'Delete "{title}"? This cannot be undone.',deleteSuccess:'Deleted "{title}"',deleteFailed:"Delete failed",deprecateReasonPrompt:"Enter deprecation reason:",rejectionReason:"Rejection Reason",summary:"Summary",relatedKnowledge:"Related Knowledge",reasoning:"Reasoning",confidence:"Confidence",alternatives:"Alternatives",qualityGrade:"Quality Grade",qualityAdaptation:"Adaptation",qualityDocumentation:"Documentation",qualityCompletionLabel:"Completeness",markdownDoc:"Markdown Document",importHeaders:"Import Headers",codePattern:"Code / Standard Usage",designRationale:"Design Rationale",implementSteps:"Implementation Steps",constraintsLabel:"Constraints",aiInsight:"AI Insight",lifecycleHistoryLabel:"Lifecycle History",scope:"Scope",scopeUniversal:"Universal",scopeProject:"Project-specific",scopeModule:"Module-level",complexity:"Complexity",complexityAdvanced:"Advanced",complexityIntermediate:"Intermediate",complexityBeginner:"Beginner",sourceFile:"Source File",prev:"Previous",next:"Next",narrow:"Narrow",widen:"Widen",guardHits:"Guard",adoptions:"Adoptions",searchHits:"Searches",statViews:"Views",statApplications:"Applications",published:"Published"},knowledgeGraph:{title:"Knowledge Graph",nodeTypes:"Node Types",nodeRecipe:"Recipe",nodeModule:"Module",nodeFile:"File",nodeSymbol:"Symbol",relationInherits:"Inherits",relationImplements:"Implements",relationCalls:"Calls",relationDependsOn:"Depends on",relationDataFlow:"Data flow",relationConflicts:"Conflicts",relationExtends:"Extends",relationAssociates:"Associates",relationContains:"Contains",relationImports:"Imports",relationOverrides:"Overrides",relationComposedOf:"Composed of",relationReferencedBy:"Referenced by",relationTestedBy:"Tested by",relationDocumentedIn:"Documented in",tools:"Tools",zoomIn:"Zoom in",zoomOut:"Zoom out",resetView:"Reset view",fitView:"Fit to canvas",toggleLabels:"Toggle labels",nodeDetail:"Node Detail",relatedNodes:"Related Nodes",noSelection:"Click a node to see details",legend:"Legend",searchPlaceholder:"Search nodes...",noResults:"No matching nodes",totalNodes:"{count} nodes",totalEdges:"{count} edges",loadFailed:"Failed to load knowledge graph",empty:"Knowledge graph is empty",emptyDesc:"No relation data between Recipes. Click below to let AI analyze potential relations (requires / extends / enforces / calls, etc.).",discoverRelations:"AI Discover Relations",discovering:"AI analyzing…",refresh:"Refresh",retry:"Retry",statsLabel:"{nodes} nodes · {edges} relations",cancelSelection:"Deselect",outEdges:"Outgoing (dependencies)",inEdges:"Incoming (dependents)",none:"None",relationRequires:"Requires",relationEnforces:"Enforces",relationPrerequisite:"Prerequisite",relationReferences:"References",relationAlternative:"Alternative",relationDeprecatedBy:"Deprecated by",relationSolves:"Solves",discoverAnalyzing:"AI analyzing… ({elapsed}s elapsed)",discoverPollTimeout:"Poll timeout. The task may still be running in the background. Please refresh the page later.",discoverNoResults:"Analysis complete, checked {pairs} Recipe pairs, no relations found. Try again after adding more Recipes.",discoverBatchErrors:"Analysis complete, but {errors} AI batch calls failed, no relations found. Check AI Provider config.",discoverSuccess:"Discovered {count} relations ({pairs} pairs analyzed{failMsg})",discoverBatchFailed:", {count} batches failed",discoverAiNotConfigured:"AI not configured: {error}",discoverTimeout:"Task timeout: {error}",discoverFailed:"Discovery failed: {error}",discoverRunning:"AI analysis still running…",discoverStarted:"AI analysis started, running in background…",discoverInsufficientRecipes:"Not enough Recipes to analyze",discoverPreviousTimeout:"Previous task timed out, please retry",discoverAiUnavailable:"AI service unavailable: {error}",discoverStartFailed:"Start failed: {error}",unknownError:"Unknown error",discoverTooltip:"AI automatically discover Recipe relations"},guard:{title:"Guard Audit",summary:"Summary",totalViolations:"{count} violations",noViolations:"No violations",searchPlaceholder:"Search rules or files...",severityError:"Error",severityWarning:"Warning",severityInfo:"Info",ruleId:"Rule ID",file:"File",line:"Line",message:"Message",severity:"Severity",statusOpen:"Open",statusResolved:"Resolved",statusIgnored:"Ignored",resolve:"Mark as resolved",ignore:"Ignore",reopen:"Reopen",aiGenPlaceholder:"e.g. Disallow direct network calls in Views",addRule:"Add Rule",refreshAudit:"Refresh Audit",refreshing:"Refreshing audit...",refreshSuccess:"Audit refreshed",reportIssue:"Report false positive",clearHistory:"Clear History",clearConfirm:"Are you sure to clear all Guard violation records?",addRuleValidation:"Please fill in rule ID, message, regex and at least one language",patternLabel:"Regex (matched per line)",languagesLabel:"Languages",dimensionLabel:"Audit Scope",noteLabel:"Note",allLanguages:"All Languages",noMatchingRules:"No matching rules, adjust filters",violationRecords:"Violations ({runs} runs, {count} violations)",dimFile:"Same file",dimTarget:"Same target",dimProject:"Same project",rationale:"Rationale",fixSuggestion:"Fix suggestion",sourceRecipe:"Source Recipe",categorySafety:"Safety",categoryCorrectness:"Correctness",categoryPerformance:"Performance",categoryStyle:"Style",category:"Category",currentProject:"Current project",dimNoLimit:"No limit",notePlaceholder:"Simple pattern hint only",copyFixSuggestion:"Copy fix suggestion",codeLevelConfigTip:"Code-Level and Cross-File checks (e.g. excessive unwrap, circular import) can be disabled or threshold-adjusted via config.",codeLevelConfigPath:"Config path: config/default.json → guard.disabledRules / guard.codeLevelThresholds",metricCompliance:"Compliance",metricCoverage:"Coverage",metricConfidence:"Confidence",metricQualityGate:"Quality Gate",hintCompliance:"Score deducted by violations",hintCoverage:"Executed checks / total planned",hintConfidence:"Ratio of results without uncertainty",tabViolations:"Violations",tabUncertain:"Uncertain",tabRules:"Rules",tabBoundaries:"Boundaries",tabAudit:"Audit Log",noAuditLogs:"No audit logs",loadMore:"Load more",tableHeaders:{rule:"Rule",file:"File",line:"Line",message:"Description",severity:"Severity",status:"Status",actions:"Actions"}},panorama:{title:"Project Panorama",overview:"Overview",health:"Health",gaps:"Knowledge Gaps",modules:"Modules",layers:"Layers",files:"Files",recipes:"Recipes",coverage:"Coverage",cycles:"Cycles",healthScore:"Health Score",avgCoupling:"Avg Coupling",highPriorityGaps:"High Priority",noGaps:"No knowledge gaps found",noData:"No panorama data available",loading:"Loading panorama...",stale:"Data may be stale"},skills:{title:"Skills Management",searchPlaceholder:"Search Skills...",totalCount:"{count} total",noResults:"No matching Skills",addSkill:"Add Skill",editSkill:"Edit Skill",deleteSkill:"Delete Skill",deleteConfirm:"Delete this Skill?",deleteSuccess:"Deleted",saveSuccess:"Saved",skillName:"Name",skillNamePlaceholder:"Enter Skill name",skillDescription:"Description",skillDescPlaceholder:"Enter Skill description",skillTrigger:"Trigger",skillTriggerPlaceholder:"Enter trigger condition",skillAction:"Action",skillActionPlaceholder:"Enter action content",skillEnabled:"Enabled",skillDisabled:"Disabled",toggleEnable:"Enable/Disable",aiRecommend:"AI Recommend",aiRecommendDesc:"Based on project analysis, AI recommends the following Skills",aiRecommending:"AI analyzing...",aiRecommendSuccess:"{count} recommended",aiRecommendFailed:"Recommendation failed",acceptRecommend:"Accept",rejectRecommend:"Ignore",bulkAccept:"Accept all",signalBadge:"Signal",category:"Category",priority:"Priority",priorityHigh:"High",priorityMedium:"Medium",priorityLow:"Low",subtitle:"Agent skill docs — guide AI on how to use AutoSnippet tools",fetchFailed:"Failed to fetch Skills list",loadError:"does not exist or read error",loadSkillFailed:"Failed to load Skill",updateSuccess:"updated",updateFailed:"Failed to update Skill",deleteFailed:"Failed to delete Skill",createSuccess:"created",createFailed:"Failed to create Skill",createAddedToKB:"Created and added to knowledge base",filterProject:"Project",filterBuiltin:"Built-in",noRecommendations:"No recommendations yet. More signals will accumulate with usage.",aiRecommendTooltip:"Recommend Skills based on usage patterns",creating:"Creating",useCase:"Use case",chars:"chars",related:"Related",confirmDelete:"Confirm Delete",deleteSkillConfirmMsg:'Delete Skill "{name}"? This cannot be undone.',selectToView:"Select a Skill on the left to view details",checkGenerated:"Please review the generated content",aiGenerated:"AI generated Skill",aiGenFailed:"AI generation failed",fillRequired:"Please fill in name, description and content",savedToKB:"Saved to knowledge base",aiGenMode:"AI Generate",manualMode:"Manual",describeSkill:"Describe the Skill you want to create",aiGeneratingContent:"AI generating...",generateSkill:"Generate Skill",skillContent:"Skill document content",createdBy:{manual:"Manual","user-ai":"AI Assisted","system-ai":"Auto","external-ai":"External AI"}},depGraph:{title:"Dependency Graph",searchPlaceholder:"Search modules...",noResults:"No matching modules",totalModules:"{count} modules",totalDeps:"{count} dependencies",layout:"Layout",layoutTree:"Tree",layoutForce:"Force",layoutCircular:"Circular",zoomIn:"Zoom in",zoomOut:"Zoom out",resetView:"Reset view",fitView:"Fit to canvas",nodeDetail:"Module Detail",dependencies:"Dependencies",dependents:"Dependents",legend:"Legend",noSelection:"Click a node to see details",depTypes:{direct:"Direct",transitive:"Transitive",devOnly:"Dev only"},refresh:"Refresh",retry:"Retry",noDataTitle:"No module dependency data found in this project.",noDataDesc:'Ensure your project contains module definition files (go.mod / package.json / Package.swift / build.gradle, etc.), then click "Refresh" to rescan.',filterAll:"All",filterInternal:"Internal",filterExternal:"External",packages:"Packages",packageList:"Package List",depRelations:"Dependencies (Mini)",depRelationsDesc:"The main graph doesn't show edges. Click nodes to see deps in the popup. All From → To listed here.",labelExternal:"External",labelInternal:"Internal",labelIndirect:"Indirect",projectRoot:"Project root",close:"Close",none:"None",visualization:"Module dependency structure visualization",targetHint:"Target node format:"},bootstrap:{title:"Project Scan Progress",pipelineSteps:{collecting:"Collecting project structure",scanning:"Scanning source code",analyzing:"AI analyzing",enriching:"Knowledge enrichment",indexing:"Building index"},taskStatus:{pending:"Pending",running:"Running",completed:"Completed",failed:"Failed",skipped:"Skipped"},stats:{totalFiles:"Total files",totalTargets:"Targets",totalRecipes:"Recipes",totalTime:"Total time",aiCalls:"AI calls"},notifications:{started:"Project scan started",completed:"Project scan completed",failed:"Project scan failed",partialComplete:"Partially completed"},retryFailed:"Retry failed tasks",viewDetails:"View details",dimLabels:{architecture:"Architecture & Design",codingStandards:"Coding Standards",designPatterns:"Design Patterns",errorResilience:"Error Resilience",concurrencyAsync:"Concurrency & Async",dataEventFlow:"Data & Event Flow",networkingApi:"Networking & API",uiInteraction:"UI Interaction",testingQuality:"Testing Quality",securityAuth:"Security & Auth",performanceOptimization:"Performance",observabilityLogging:"Observability",agentGuidelines:"Agent Guidelines",swiftObjcIdiom:"Swift/ObjC Idioms",tsJsModule:"TS/JS Modules",pythonStructure:"Python Structure",jvmAnnotation:"JVM Annotations",goModule:"Go Module",rustOwnership:"Rust Ownership",csharpDotnet:"C#/.NET",reactPatterns:"React Patterns",vuePatterns:"Vue Patterns",springPatterns:"Spring Patterns",swiftuiPatterns:"SwiftUI Patterns",djangoFastapi:"Django/FastAPI",bootstrap:"Bootstrap"},pipelineLabels:{architecture:"Architecture Patterns","coding-standards":"Code Standards","design-patterns":"Design Patterns","error-resilience":"Error Resilience","concurrency-async":"Concurrency & Async","data-event-flow":"Data & Event Flow","networking-api":"Networking & API","ui-interaction":"UI Interaction","testing-quality":"Testing Quality","security-auth":"Security & Auth","performance-optimization":"Performance","observability-logging":"Observability","agent-guidelines":"Agent Development Guidelines","swift-objc-idiom":"Swift/ObjC Idioms","ts-js-module":"TS/JS Module Exports","python-structure":"Python Package Structure","jvm-annotation":"JVM Annotations","go-module":"Go Module","rust-ownership":"Rust Ownership","csharp-dotnet":"C#/.NET Patterns","react-patterns":"React Patterns","vue-patterns":"Vue Patterns","spring-patterns":"Spring Patterns","swiftui-patterns":"SwiftUI Patterns","django-fastapi":"Django/FastAPI"},pipelineDescs:{architecture:"Layered architecture, module boundaries, deps, tech stack","coding-standards":"Naming conventions, comments, file organization","design-patterns":"Singleton, delegate, factory, observer patterns","error-resilience":"Error handling, exception recovery, defensive coding","concurrency-async":"Thread safety, async patterns, race condition guards","data-event-flow":"Event propagation, data persistence, state management","networking-api":"API contracts, request patterns, retry strategies","ui-interaction":"UI components, lifecycle, navigation","testing-quality":"Test patterns, mock strategies, CI/CD","security-auth":"Authentication, encryption, access control","performance-optimization":"Memory management, lazy loading, caching","observability-logging":"Logging standards, event tracking, diagnostics","agent-guidelines":"Mandatory rules, deprecated APIs, constraints","swift-objc-idiom":"Macros, Category/Extension, Swift-ObjC interop","ts-js-module":"Barrel exports, export conventions, circular deps","python-structure":"Package structure, import conventions, type hints","jvm-annotation":"DI annotations, ORM mapping, custom annotations","go-module":"go.mod, internal packages, interface design","rust-ownership":"Ownership patterns, trait design, unsafe constraints","csharp-dotnet":"DI registration, LINQ, Entity Framework","react-patterns":"Component structure, state management, routing","vue-patterns":"Composition API, Pinia, route guards","spring-patterns":"Bean config, layered architecture, transactions","swiftui-patterns":"View structure, state management, navigation","django-fastapi":"App structure, API design, middleware"},statusLabels:{skeleton:"Pending",filling:"Filling",completed:"Completed",failed:"Failed"},allCompleted:"All completed",completedWithErrors:"Completed with errors",elapsed:"Elapsed",estimatedRemaining:"Est. remaining",toolCalls:"Tool calls",dimensions:"{done}/{total} dimensions",notifySuccess:"All {completed} dimensions filled successfully",notifyPartial:"{completed}/{total} succeeded, {failed} failed",coldStartComplete:"Project scan complete",close:"Close",cancel:"Cancel",reviewPipeline:"AI Review Pipeline",reviewRounds:{round1Label:"Eligibility Check",round1Desc:"Filter false positives · Identify merges",round2Label:"Content Refinement",round2Desc:"AI rewrite summary · Dynamic confidence",round3Label:"Dedup & Relations",round3Desc:"Semantic dedup · Relation inference"},round1Done:"Kept {kept} · Merged {merged} · Dropped {dropped}",round2Progress:"{current}/{total} items",round2Done:"Refined {refined}/{total} items",round3Done:"{afterDedup} after dedup · {relationsFound} relations",noMatch:"✓ No matching content",featuresOnly:"✓ {sourceCount} features",featuresAndCandidates:"✓ {sourceCount} features · {extracted} candidates",candidatesOnly:"✓ {extracted} candidates"},wiki:{title:"Repo Wiki",sidebar:"Wiki",fileCount:"{count} articles",searchPlaceholder:"Search files...",generating:"Generating files, new docs will appear automatically…",backToList:"Back to file list",aiBadge:"AI Enhanced",copySuccess:"Copied",copyBtn:"Copy",loadFailed:"Failed to load",incrementalUpdate:"Incremental Update",fullGeneration:"Full Generation",genStarted:"Wiki generation started",genFailed:"Generation failed",selectPlaceholder:"Select from the file tree on the left, or use the shortcuts below",phases:{outline:"Outline",content:"Content",review:"Review"},fileTypes:{overview:"Overview",module:"Module",api:"API",guide:"Guide"},synced:"Synced",wikiGenerating:"Wiki is generating",outOfDateHint:"Code changes detected, Wiki may be outdated — incremental update recommended",emptyTitle:"Repo Wiki not generated yet",emptyDesc:"Wiki is auto-generated during cold start, then kept in sync via incremental updates",emptyHint:"Run asd setup for cold start · asd wiki --update for incremental update",quickOverview:"Project Overview",quickOverviewDesc:"Project info, tech stack & statistics",quickArch:"Architecture",quickArchDesc:"Module dependency graph & structure analysis",quickStart:"Getting Started",quickStartDesc:"Build, run & entry point analysis",quickProtocols:"Protocols & Components",quickProtocolsDesc:"Core protocols, delegates and component relations",selectFile:"Select a file to start reading",lastGenerated:"Last generated",duration:"Duration",incrementalUpdating:"Incremental updating...",loadFailedDesc:"Unable to read file content."},aiChat:{title:"AI Assistant",emptyTitle:"Start a conversation with AI",emptyDesc:"Ask questions about your project. AI will help analyze code and recommend patterns.",inputPlaceholder:"Type your question...",inputHint:"Enter to send · Shift+Enter for new line",thinking:"AI is thinking...",analyzing:"AI is analyzing...",topicPanel:"Topics",newTopic:"New Topic",deleteTopic:"Delete Topic",deleteTopicConfirm:"Delete this topic?",quickPrompts:{analyzeArch:"Analyze project architecture",findDuplicates:"Find duplicate code",suggestOptimize:"Suggest optimizations"},timeJustNow:"just now",timeMinutesAgo:"{n} min ago",timeHoursAgo:"{n} hr ago",timeDaysAgo:"{n} days ago",codeBlock:"Code Block",diffView:"Diff View",diffBefore:"Before",diffAfter:"After",contextLabel:"AI Context / Project Profile",copyCode:"Copy Code",topicRecords:"Topics",noHistory:"No chat history",autoSaveHint:"Auto-saved after conversation starts",topicCount:"{count} topics · Local storage",askAnything:"Ask anything about your project",startChat:"Start AI Chat",emptyDescLong:"Ask about your project — code analysis, architecture suggestions, optimization directions, etc.",aiAssistant:"AI Assistant",messageCount:"{n} messages",requestFailed:"Request failed: {error}",cancelled:"(Cancelled)",expandTopics:"Expand topics",diffEmpty:"(empty)",quickPromptSummarize:"Summarize project overview"},help:{title:"Help",gettingStarted:"Getting Started",commands:"Command Reference",faq:"FAQ",tokenUsage:"Token Usage",about:"About",pageTitle:"AutoSnippet Guide",subtitle:"Connect developers, AI & project knowledge: Self-evolving knowledge mining · Governing AI coding output · Multi-language support",techSpecs:"Node.js ≥ 22 · 18 MCP Tools · 5 Skills · Agent Runtime · AST · VSCode Extension · Vector",viewGithub:"View on GitHub",fullDocs:"Full Documentation",tokenUsageLast7Days:"Token Usage (Last 7 Days)",quickStart:"Quick Start",coreConcepts:"Core Concepts",coreFeatures:"Core Features",editorDirectives:"Editor Directives",cursorIntegration:"IDE Integration",v3Architecture:"V3 Architecture",cliReference:"CLI Quick Reference",step1Title:"Install & Initialize",step2Title:"Start Dashboard",step2Desc:"Start HTTP API + Dashboard + FileWatcher",step3Title:"IDE Integration",step3Desc:"Install MCP + Skills + Cursor Rules + VSCode Extension",step4Title:"Cold Start Knowledge Base",step4Desc1:"Multi-dimension AI scan of codebase",step4Desc2:"Generate Candidates → Dashboard review → Recipe",threeRoles:"Three Roles",roleColumn:"Role",responsibilityColumn:"Responsibility",capabilityColumn:"Capabilities",roleDeveloper:"Developer",roleCursorAgent:"IDE Agent",roleChatAgent:"Built-in Agent",developerResp:"Review & decide, maintain project standards",cursorAgentResp:"Generate code per standards, search knowledge base, manage tasks",chatAgentResp:"Cold start analysis, Lark programming, Skills recommendation, scan & audit",coreComponents:"Core Components",bootstrapLabel:"Bootstrap (Cold Start)",bootstrapDesc:"14 dimensions × 7-phase dual-path knowledge extraction engine",candidatesLabel:"Candidates",candidatesDesc:"V3 structured entries — Agent submits, humans review",recipeLabel:"Recipe",recipeDesc:"Unified V3 knowledge model + knowledge graph relations",chatAgentLabel:"Agent Runtime (Unified Engine)",chatAgentDesc:"Single Runtime + Preset-driven configuration, powering all AI capabilities",searchPipelineLabel:"4-Layer Retrieval Pipeline",searchPipelineDesc:"5-layer funnel + 6-signal ranking + Cross-Encoder AI reranking",guardLabel:"Guard (Code Review)",guardDesc:"Knowledge-driven rules, detect on write; Agent silent self-repair",knowledgeLoop:"Knowledge Loop",loopStep1:"Discover & Extract",loopStep1Sub:"Bootstrap / Agent / Cursor",loopStep2:"Review & Filter",loopStep2Sub:"Auto + Human",loopStep3:"Persist",loopStep3Sub:".md + DB + Graph",loopStep4:"Deliver & Use",loopStep4Sub:"IDE / Agent / Guard",loopStep5:"Feedback & Learn",loopStep5Sub:"RuleLearner + Quality",knowledgeBuild:"Knowledge Base Building",semanticSearchLabel:"Semantic Search",codeAudit:"Code Audit",dataSync:"Data Sync",usageExamples:"Usage Examples",exampleSearchKB:"Search Knowledge Base",exampleSearchKBDesc:'Tell Cursor: "Find error handling code for network requests"',exampleBatchScan:"Batch Scan",exampleBatchScanDesc:'Tell Cursor: "Scan NetworkModule, generate Recipes to candidates"',exampleSubmitCode:"Submit Code",exampleSubmitCodeDesc:'Tell Cursor: "Save this code as a Recipe"',skills10:"5 Skills",mcp16:"18 MCP Tools (Parameterized)",bootstrapEngine:"Bootstrap Cold Start Engine",bootstrapEngineDesc:"3 steps from 0 → 1 knowledge base:",fourLayerPipeline:"4-Layer Retrieval Pipeline",fourLayerPipelineDesc:"Multi-signal fusion precision retrieval:",chatAgentSystem:"ChatAgent Dialog System",chatAgentSystemDesc:"Multi-Agent collaboration architecture, continuously extensible:",fiveEntryChannels:"Six Entry Channels",initAndEnv:"Init & Environment",kbManagement:"Knowledge Base Management",searchAndAudit:"Search & Audit",maintenanceUpgrade:"Maintenance & Upgrade",footerHint:"Need more details? Check {link} or run {cmd} to verify your environment",footerGithubReadme:"GitHub README",mcpWriteNote:"Write tools (submit_knowledge, guard, bootstrap, etc.) are protected by Gateway permissions / constitution / audit triple protection.",editorDirectivesNote:"Requires asd watch or asd ui running; supports shortcuts asc / ass / asa",createDirective:"Create Recipe",searchDirective:"Search & Insert",auditDirective:"Code Audit",includeDirective:"Auto-inject headers/modules",developerCap:'Dashboard review candidates, save Recipes; <code class="bg-slate-100 px-1 rounded">// as:search</code> knowledge retrieval; run <code class="bg-slate-100 px-1 rounded">asd ui</code>',cursorAgentCap:"11 Skills understand conventions; 22 MCP tools for on-demand retrieval & candidate submission; writes go through Gateway review; TaskGraph DAG orchestration + tokenBudget-aware consumption",chatAgentCap:'Unified AgentRuntime; Lark Preset programming chat; Skills smart recommendation + auto-injection; <code class="bg-slate-100 px-1 rounded">asd coldstart</code> cold start + <code class="bg-slate-100 px-1 rounded">asd ais</code> scan',bootstrapBullet1:"14 dimensions (7 universal + 7 language), auto-activated by lang/framework",bootstrapBullet2:"Dual-path: Analyst/Producer AI pipeline or IDE Agent + MCP",bootstrapBullet3:"Auto by-products: Repo Wiki + 4 Project Skills + Phase 6 AI refinement",candidatesBullet1:"V3 format 16+ required fields, Reasoning strong validation",candidatesBullet2:"Jaccard 0.85 dedup + strict boundary: Agent can only submit",candidatesBullet3:"Sources: AI scan / Cursor / clipboard / Dashboard, full lifecycle mgmt",recipeBullet1:"Fuses kind (rule/pattern/fact) + 12 knowledgeTypes + 8 graph relations",recipeBullet2:'<code class="bg-blue-100 px-1 rounded">kind=rule</code> auto-becomes Guard rule: knowledge→standard→detection loop',recipeBullet3:'.md = single source of truth, <code class="bg-blue-100 px-1 rounded">asd sync</code> incremental → DB',chatAgentCompBullet1:"Unified AgentRuntime + 4 strategies + CoALA (Perceive→Memory→Reason→Act)",chatAgentCompBullet2:"3-tier memory + 3-level context compression + 5-provider auto-fallback",chatAgentCompBullet3:"AgentRouter 5-level cascade: manual→channel→keyword→LLM→default chat",searchPipelineBullet1:"Inverted index → Cross-Encoder AI rerank → E-E-A-T coarse → 6-signal fine rank",searchPipelineBullet2:"Custom CJK/English field-weighted tokenizer + session context-aware reranking",searchPipelineBullet3:"search MCP tool: 5 mode routes, batch 40-candidate AI scoring",guardCompBullet1:"3 rule sources: built-in + knowledge base kind=rule auto-derived + Enhancement Pack",guardCompBullet2:"Agent self-repair loop: violation + inline Recipe fix guide → silent fix → re-check (up to 5 rounds)",guardCompBullet3:"VSCode real-time diagnostics + Quick Fix; FeedbackLoop auto-tracks fixes & learns rule precision",kbBuildBullet1:'<strong>AI Scan</strong>: <code class="bg-slate-100 px-1 rounded text-xs">asd ais [Target]</code> batch extraction',kbBuildBullet2:'<strong>Cursor Scan</strong>: Tell Copilot "scan Module"',kbBuildBullet3:"<strong>Manual Create</strong>: New Recipe → Use Copied Code",kbBuildBullet4:'<strong>In Editor</strong>: Copy code → <code class="bg-slate-100 px-1 rounded text-xs">// as:create -c</code>',semSearchBullet1:"<strong>4-Layer Pipeline</strong>: InvertedIndex → CoarseRanker → MultiSignalRanker → RetrievalFunnel",semSearchBullet2:'<strong>In Editor</strong>: <code class="bg-slate-100 px-1 rounded text-xs">// as:search keyword</code>',semSearchBullet3:"<strong>Cursor MCP</strong>: search unified tool (mode routes 5 modes)",semSearchBullet4:"<strong>Dashboard</strong>: Search box supports semantic + keyword",auditFeatureBullet1:'<strong>File Audit</strong>: <code class="bg-slate-100 px-1 rounded text-xs">// as:audit</code>',auditFeatureBullet2:'<strong>Target Audit</strong>: <code class="bg-slate-100 px-1 rounded text-xs">// as:audit target</code>',auditFeatureBullet3:'<strong>Guard Audit</strong>: MCP <code class="bg-slate-100 px-1 rounded text-xs">guard</code> (code / files param)',auditFeatureBullet4:"<strong>Dashboard</strong>: Guard page visual audit",syncBullet1:'<strong>Sync</strong>: <code class="bg-slate-100 px-1 rounded text-xs">asd sync</code> .md → DB (incremental)',syncBullet2:'<strong>Hash Check</strong>: <code class="bg-slate-100 px-1 rounded text-xs">_contentHash</code> detect manual edits',syncBullet3:"<strong>Vector Index</strong>: Auto-build semantic index on startup",syncBullet4:'<strong>Dependency Graph</strong>: <code class="bg-slate-100 px-1 rounded text-xs">structure</code> (operation: targets / files) MCP tool',coreFeaturesDesc:"Six key capabilities: knowledge collection, intelligent search, code compliance, task orchestration, document generation, and data sync",kbBuildDesc:"Multi-channel collection, AI-driven full lifecycle knowledge base management",semSearchDescShort:"4-layer pipeline fusing FieldWeighted + keyword + semantic triple signals",guardCompliance:"Guard Compliance Loop",guardComplianceDesc:"Rule audit → diagnostic squiggles → lightbulb fix, closed-loop compliance",featureTaskGraphTitle:"TaskGraph Orchestration",featureTaskGraphDesc:"DAG task graph + tokenBudget awareness, structured complex task management",featureTaskGraphBullet1:"<strong>DAG Model</strong>: decompose / prime / ready / claim / close — 15 operations",featureTaskGraphBullet2:"<strong>tokenBudget Aware</strong>: auto-trim detail levels (CRITICAL &lt; 5K, WARNING &lt; 20K)",featureTaskGraphBullet3:"<strong>MCP + VSCode</strong>: task tool + lm.registerTool native integration",featureTaskGraphBullet4:"<strong>Prime Warmup</strong>: auto-inject Mission Briefing + key context",wikiDocGen:"Wiki Doc Generation",wikiDocGenDesc:"Agent-driven automatic project documentation generation & maintenance",wikiDocBullet1:"<strong>wiki(plan)</strong>: Scan project → plan topics + data packages",wikiDocBullet2:"<strong>wiki(finalize)</strong>: meta.json aggregation + dedup + file validation",wikiDocBullet3:"<strong>Knowledge Aggregation</strong>: Auto-generate dev docs from Recipes",wikiDocBullet4:"<strong>Incremental Update</strong>: Version tracking + diff merging",syncDescShort:"Incremental sync, hash check, vector index, dependency graph analysis",createDirBullet1:"No options: open Dashboard",createDirBullet2:"<code>-c</code>: silently create from clipboard",createDirBullet3:"<code>-f</code>: scan current file",searchDirBullet1:"Retrieve Recipe from knowledge base",searchDirBullet2:"Insert code after selection, replacing the line",searchDirBullet3:"Records one manual usage",auditDirBullet1:"No suffix: audit current file",auditDirBullet2:"<code>target</code>: audit current Target",auditDirBullet3:"<code>project</code>: audit entire project",includeDirBullet1:"Code contains this marker",includeDirBullet2:"Auto-inject import after completion",skillIntent:"Intent Routing",skillConcepts:"Concept Teaching",skillCandidates:"Candidate Submit",skillRecipes:"Recipe Search",skillGuard:"Code Compliance",skillStructure:"Project Structure",skillAnalysis:"Deep Analysis",skillColdstart:"Cold Start",skillCreate:"Guided Creation",skillLifecycle:"Lifecycle",skillDevdocs:"Dev Docs",mcpLayerHeader:"Layer",mcpToolHeader:"Tool",mcpDescHeader:"Description",mcpAgentLayerHeader:"Agent Layer (18) — exposed by default",mcpAdminLayerHeader:"Admin Layer (4) — requires ASD_MCP_TIER=admin",mcpHealthDesc:"Service health check",mcpCapabilitiesDesc:"Service capabilities list (Agent self-discovery)",mcpGuardDesc:"code=single file audit / files=batch audit",mcpSubmitDesc:"Submit candidate / batch / save document",mcpEnrichDesc:"AI enrich / validate / dedup",mcpLifecycleDesc:"Batch lifecycle operations",mcpSearchDesc:"mode routes auto / keyword / weighted / semantic / context",mcpKnowledgeDesc:"operation routes list / get / insights / confirm_usage",mcpStructureDesc:"operation routes targets / files / metadata",mcpGraphDesc:"operation routes query / impact / path / stats",mcpCallContextDesc:"Call chain context: callers / callees / both / impact",mcpSkillDesc:"operation routes list / load / create / update / delete / suggest",mcpBootstrapDesc:"No params — returns Mission Briefing + dimension task list",mcpDimensionCompleteDesc:"Dimension complete notification + Checkpoint + Hints dispatch",mcpWikiPlanDesc:"Document planning: scan project → topics + data packages",mcpWikiFinalizeDesc:"Document finalization: meta.json + dedup + file validation",mcpTaskDesc:"15 operations: create / ready / claim / close / decompose / prime / stats etc.",archBootstrapStep1:"① Project scan → dependency / directory / entry analysis",archBootstrapStep2:"② AI batch extraction → Candidate list",archBootstrapStep3:"③ Review + Promote → Recipe knowledge base ready",archBootstrapNote:"Supports bootstrap → dimension_complete loop iteration & session resume from breakpoint",archPipelineL1:"InvertedIndex — inverted index fast recall",archPipelineL2:"CoarseRanker — multi-signal coarse ranking",archPipelineL3:"MultiSignalRanker — multi-dimensional signal fine ranking",archPipelineL4:"RetrievalFunnel — funnel truncation + context assembly",archAnalystAgent:"<strong>Analyze Stage</strong>: Analyze user intent → retrieve knowledge base → provide suggestions → confidence signal grading",archProducerAgent:"<strong>Produce Stage</strong>: Format knowledge → create candidates → execute submissions → aggregate results",archHandoff:"<strong>QualityGate</strong>: PipelineStrategy tri-state gate (pass/retry/degrade)",archMemory:"<strong>Lightweight Memory</strong>: Cross-conversation preference/decision/context persistence (JSONL, TTL expiry)",archProjectAware:"<strong>Project-Aware</strong>: Auto-inject knowledge base state (Recipe distribution, candidate backlog, Guard rule count)",archCliDesc:"asd × 18+ commands",archMcpDesc:"stdio × 16 tools",archHttpDesc:"Express × 18 route modules",archSkillsDesc:"11 Skills",archVscodeDesc:"lm.registerTool × deep integration",v3ArchDesc:"End-to-end AI engineering architecture from cold start to knowledge consumption",archOverviewLabel:"End-to-End Architecture Flow",archOverviewBootstrap:"Cold Start",archOverviewKB:"Knowledge Base",archOverviewPipeline:"Retrieval Pipeline",archOverviewAgent:"Agent Engine",archOverviewTask:"TaskGraph",archOverviewOutput:"Multi-Channel Delivery",archOverviewSecurity:"Guard + Gateway (Knowledge-Driven Validation + Access Audit)",archOverviewIDE:"IDE Integration (MCP + Skills + Extension Triple-Channel)",ideIntegrationLabel:"IDE Integration",ideIntegrationDesc:"6 IDEs + Lark, MCP/Extension/Directives triple-channel access",ideIntegrationBullet1:"MCP Server: 16 tools + Skills auto-discovery + Tier visibility",ideIntegrationBullet2:"VSCode Extension: 11 modules (Guard + CodeLens + #asd Agent + Decision)",ideIntegrationBullet3:'One-click <code class="bg-slate-100 px-1 rounded text-xs">asd setup</code> generates Cursor / VS Code / Claude Code templates',securityLabel:"Security & Permissions",securityDesc:"Gateway 4-step pipeline + Constitution governance + 3-role RBAC",securityBullet1:"Gateway 4-step: validate → guard → route → audit, single write entry",securityBullet2:"3-tier trust: external Agent (restricted) → built-in Agent (read+submit) → developer (full)",securityBullet3:"SafetyPolicy: command sandbox + file write protection + full audit trail",constitutionSecurity:"Constitution / Gateway Security",constitutionSecurityDesc:"Triple security: permission check + constitution rules + audit trail",archConstitutionBullet1:"<strong>Gateway Permission</strong>: MCP write ops intercepted by Gateway layer",archConstitutionBullet2:"<strong>Constitution</strong>: YAML-defined behavioral rules constraining AI operation boundaries",archConstitutionBullet3:"<strong>Audit Log</strong>: Full-chain operation traceability, auto-alert on anomalies",archConstitutionBullet4:"<strong>Tier Isolation</strong>: Agent / Admin layered, sensitive ops require escalation",archTaskGraphTitle:"TaskGraph System",archTaskGraphDesc:"DAG-driven structured task management:",archTaskGraphBullet1:"<strong>Task DAG</strong>: Dependency modeling → topological sort → parallel scheduling",archTaskGraphBullet2:"<strong>State Machine</strong>: pending → ready → claimed → done, auto-transition",archTaskGraphBullet3:"<strong>tokenBudget</strong>: Remaining token aware, intelligent task detail trimming",archTaskGraphBullet4:"<strong>Session Persistence</strong>: Resume from breakpoint + progress visualization",agentArchTitle:"Agent Architecture",agentArchDesc:"Unified runtime + orthogonal configuration, powering all AI capabilities",agentArchPresetTitle:"4 Preset Modes",agentArchPresetDesc:"One AgentRuntime, different configuration combos:",agentArchPresetChat:"<strong>chat</strong>: Conversation Q&A (8 rounds / 120s) — Dashboard & Lark daily chat",agentArchPresetInsight:"<strong>insight</strong>: Deep Insight (24 rounds / 600s) — cold start multi-dimension analysis + knowledge extraction",agentArchPresetLark:"<strong>lark</strong>: Lark Chat (12 rounds / 180s) — Lark channel knowledge management",agentArchPresetRemoteExec:"<strong>remote-exec</strong>: Remote Exec (6 rounds / 60s) — terminal command sandbox",agentArchStrategyTitle:"4 Execution Strategies",agentArchStrategyDesc:"Based on Anthropic Agents design patterns:",agentArchStrategySingle:"<strong>Single</strong>: One ReAct loop — chat, Lark, remote exec",agentArchStrategyPipeline:"<strong>Pipeline</strong>: Sequential stages + quality gates (pass/retry/degrade) — scan analysis",agentArchStrategyFanOut:"<strong>FanOut</strong>: Concurrent sub-tasks + tier-based throttle — cold start parallel dimensions",agentArchStrategyAdaptive:"<strong>Adaptive</strong>: Auto-select strategy at runtime — dynamic dispatch",agentArchCapTitle:"5 Capability Sets",agentArchCapDesc:"Each contributes prompts + tool whitelist + hooks:",agentArchCapConversation:"<strong>Conversation</strong> (9 tools): Multi-turn dialog · knowledge search · memory · SOUL.md persona",agentArchCapCodeAnalysis:"<strong>CodeAnalysis</strong> (15 tools): AST analysis · class hierarchy · call graph · code search",agentArchCapKnowledgeProd:"<strong>KnowledgeProduction</strong> (3 tools): Knowledge submission with validation",agentArchCapScanProd:"<strong>ScanProduction</strong> (2 tools): In-memory scan pipeline collection",agentArchCapSystem:"<strong>SystemInteraction</strong> (8 tools): Safe commands · file write · environment detection",agentArchMemoryTitle:"3-Tier Memory System",agentArchMemoryDesc:"Inspired by CoALA / MemGPT, Budget-Aware injection (12.5% context window):",agentArchMemoryWorking:"<strong>Working Memory</strong> (ActiveContext): Scratchpad + observation log + plan tracking",agentArchMemorySession:"<strong>Session Memory</strong> (SessionStore): Cross-dimension reports + read-only cache (LRU + TTL)",agentArchMemoryPersistent:"<strong>Persistent Memory</strong> (PersistentMemory): 3-axis scoring × memory consolidation (SQLite)",agentArchContextTitle:"Context Management",agentArchContextDesc:"Prevent long conversations from overflowing, model-aware token budgets:",agentArchContextWindow:"<strong>ContextWindow</strong>: 3-level compression — L1 truncate old tool results → L2 summarize history → L3 keep only prompt",agentArchContextTracker:"<strong>ExplorationTracker</strong>: Phase state machine + signal detection + nudge guidance + graceful exit",agentArchToolsTitle:"Tool System",agentArchToolsDesc:"58 internal tools + 22 MCP tools, writes go through Gateway audit:",agentArchToolsInternal:"<strong>Internal Tools</strong> (58): 10 categories — project access · query · AST · composite · Guard · knowledge graph · lifecycle · infra · system · scan",agentArchToolsMcp:"<strong>MCP Tools</strong> (22): 18 Agent tier + 4 Admin tier, stdio transport",agentArchRouterTitle:"Intent Routing",agentArchRouterDesc:"AgentRouter 5-level priority: manual preset → channel detection → keyword regex → LLM classification → default chat",cliSetupDesc:"Initialize project",cliStatusDesc:"Environment check",cliUiDesc:"Start Dashboard",cliUpgradeDesc:"Upgrade IDE integration",cliSyncDesc:".md → DB incremental sync",cliAisDesc:"AI scan extract Candidates",cliAisForceDesc:"Force full rescan",cliWatchDesc:"File watch + directive trigger",cliSearchDesc:"Search knowledge base",cliSearchSemanticDesc:"Semantic search mode",cliGuardDesc:"Guard rule check",cliServerDesc:"Start API server only",cliUpgradeMcpDesc:"Upgrade MCP / Skills / Rules",cliInstallFullDesc:"Full IDE integration install",cliSyncForceDesc:"Full DB rebuild",cliSyncDryDesc:"Preview sync changes",taskGraphLabel:"TaskGraph",taskGraphDesc:"Decomposes Agent work into persistent, context-aware steps",taskGraphBullet1:"decompose Epic → DAG subtasks, 7 dep types + recursive ready detection, auto-cascade on close",taskGraphBullet2:"prime session recovery: injects in-progress + decisions + knowledge context, no lost progress",taskGraphBullet3:"Team decisions persisted + supersedes evolution chain + 30-day stale auto-detection",vscodeExtension:"VSCode Extension",vscodeExtDesc:"Native Copilot deep integration via lm.registerTool API",vscodeExtTaskTool:"TaskGraph Proxy Tool",vscodeExtTaskToolDesc:"tokenBudget-aware WARNING / CRITICAL tiered protection; auto-inlines prime data at CRITICAL level",vscodeExtGuardDiag:"Guard Check on Save",vscodeExtGuardDiagDesc:"onDidSave → Guard API → DiagnosticCollection squiggles + lightbulb menu search fix",vscodeExtCodeLens:"Directive CodeLens",vscodeExtCodeLensDesc:"Detects // as:search / // as:create directives and provides visual action buttons",vscodeExtCmd1:"autosnippet.search — Search knowledge base (Cmd+Shift+F5)",vscodeExtCmd2:"autosnippet.create — Create candidate from selection",vscodeExtCmd3:"autosnippet.audit — Audit current file",vscodeExtCmd4:"autosnippet.auditProject — Audit entire project",vscodeExtCmd5:"autosnippet.status — Show connection status",cliColdstartAndScan:"Cold Start & Scan",cliTaskManagement:"Task Management",cliGuardCi:"Guard CI/CD",cliColdstartDesc:"9-dimension cold start knowledge base",cliGuardCiDesc:"CI/CD full project Guard check",cliGuardStagedDesc:"Git staged files Guard check",cliCursorRulesDesc:"Generate Cursor multi-channel delivery",cliMirrorDesc:"Mirror to .qoder / .trae",cliTaskListDesc:"List task graph",cliTaskReadyDesc:"Ready tasks + knowledge context",cliTaskPrimeDesc:"Restore session context",cliTaskStatsDesc:"Task statistics"},moduleExplorer:{title:"Module Explorer",scanTargets:"Scan Targets",scanning:"Scanning...",scanComplete:"Scan complete",targetFiles:"{count} files",noTargets:"No Targets found",recipesInTarget:"Related Recipes",guardSummary:"Guard Summary",guardViolations:"{count} violations",noViolations:"No violations",openFile:"Open file",refreshTree:"Refresh file tree",extractFromFile:"Extract code",fileDetail:"File Detail",projectModules:"Project Modules ({count})",addFolderScan:"Add folder scan",refreshProject:"Refresh project structure",discovererFolderScan:"Folder Scan",removeFolder:"Remove this folder",fullProjectResults:"Full project scan results",moduleLabel:"Module: {name}",reviewResults:"Review extraction results",resultsCount:"{count} items",candidateSuffix:" Candidate",fullProjectScanning:"Full project scanning",moduleScanLabel:"Module scan: {name}",filesInScan:"Scanned files ({count})",knowledgeExtract:"Knowledge Extraction",knowledgeExtractHint:"Select a module on the left to scan, or click + to add a folder. Extract code patterns and generate Recipe knowledge cards.",guardAuditSummary:"Guard Audit Summary",auditedFiles:"Audited files:",totalViolationsLabel:"Total violations:",errorsCount:"{count} errors",warningsCount:"{count} warnings",recipeNotExist:'"{name}" does not exist in the current knowledge base',recipeNotExistTitle:"Recipe not found",loadRecipeFailed:"Failed to load Recipe",browseFailedTitle:"Browse folder failed",browseFailedDefault:"Unable to load directory listing",selectFolderTitle:"Select folder to scan",scanningDirs:"Scanning project directories...",noDirs:"No scannable directories found",sourceFileCount:"{count} files",selectFolderHint:"Select a folder with source files. Language will be auto-detected and AI scan will run.",modulesTabLabel:"Modules ({count})",foldersTabLabel:"Folders"},search:{title:"Smart Search",searchPlaceholder:"Enter search keywords...",noResults:"No matching results",resultCount:"{count} results found",relevance:"Relevance",source:"Source",category:"Category",language:"Language",matchType:"Match Type",matchExact:"Exact",matchFuzzy:"Fuzzy",matchSemantic:"Semantic Match",matchKeyword:"Keyword Match",viewRecipe:"View Recipe",insertCode:"Insert Code",searchFailed:"Search failed. Please try again.",searching:"Searching...",searchBtn:"Search",emptyHint:"Enter keywords and click Search",contextRelevant:"Context Relevant",authorityScore:"Authority",usage:"Usage",usageCount:"{count} times",recommendReason:"Recommendation Reason",viewFullContent:"View Full Content",similarity:"Similarity",quality:"Quality",noContent:"No content",useRecipe:"Use This Recipe",importedFrameworks:"Imported Frameworks:",relatedApis:"Related APIs:"},scanResult:{title:"Scan Result",trigger:"Trigger",triggerPlaceholder:"@kebab-case-id",description:"Description",descPlaceholder:"Brief description ≤80 chars, reference real class names",category:"Category",language:"Language",code:"Code Template",markdown:"Project Profile",rationale:"Design Rationale",tags:"Tags",tagsPlaceholder:"Tags: press Enter/comma to add...",headers:"Imports",headersPlaceholder:"#import <Header.h>",confidence:"Confidence",confidenceHigh:"High",confidenceMedium:"Medium",confidenceLow:"Low",source:"Source",authorityScore:"Authority",saveAsRecipe:"Save as Recipe",saveAsKnowledge:"Save Knowledge",discard:"Discard",keepCandidate:"Keep as Candidate",qualityWarning:"Quality Warning",lowQualityHint:"This item has low quality. Consider refining before saving.",editBeforeSave:"Edit before saving",triggerRequired:"Trigger is required",savedAsRecipe:"Saved and published as Recipe",savedToKb:"Saved to Knowledge Base",validation:"Validation",validationMethod:"Method:",validationExpected:"Expected:",steps:"Implementation Steps",codeChanges:"Code Changes",constraints:"Constraints",guardRules:"Guard Rules",boundaryConstraints:"Boundary Constraints",preconditions:"Preconditions",sideEffects:"Side Effects",relations:"Relations",knowledgeEntryTitle:"Knowledge Entry Title",aiScan:"AI Scan",lifecyclePending:"Pending Review",lifecycleStaging:"Staging",lifecycleActive:"Published",lifecycleEvolving:"Evolving",lifecycleDecaying:"Decaying",lifecycleDeprecated:"Deprecated",saving:"Saving...",cursorDelivery:"Cursor Delivery",aiReasoning:"AI Reasoning",confidenceLabel:"Confidence {value}%",sourceLabel:"Sources:",noArticle:"(No project profile content)",noCode:"(No code template)",done:"Done",formatHeaders:"Format",cleanUnused:"Clean Unused",addHeader:"+ Add",usedInCode:"Referenced in code",unusedInCode:"Not found in code",unknown:"Cannot determine",unreferenced:"Unused",removeTag:"Remove",deleteHeader:"Delete",module:"Module",mode:"Mode",difficulty:"Difficulty",difficultyBeginner:"Beginner",difficultyIntermediate:"Intermediate",difficultyAdvanced:"Advanced",highDuplicateRisk:"High Duplicate Risk:",compareBeforeSave:"Compare before saving",similarRecipes:"Similar Recipes:",referenced:"referenced",collapseHeaders:"Collapse",editHeaders:"Edit"},createModal:{title:"New Recipe",importFromPath:"Import from Project Path",or:"Or",importFromClipboard:"Import from Clipboard",scanFile:"Scan File",useClipboard:"Use Copied Code",pathPlaceholder:"e.g. Sources/MyModule/Auth.swift",aiThinking:"AI is thinking..."},llmConfig:{title:"LLM Configuration",provider:"AI Provider",model:"Model",apiKey:"API Key",proxy:"Proxy",optional:"(optional)",apiKeyPlaceholderSet:"Leave blank to keep current key",apiKeyPlaceholderEmpty:"Enter API Key",envWarning:"No .env file found. It will be created automatically on save.",cancel:"Cancel",saved:"Saved",saveToEnv:"Save to .env",apiKeyRequired:"API Key is required",configured:"Configured:",saveSuccess:"Saved successfully",saveFailed:"Save failed",providers:{gemini:"Google Gemini",openai:"OpenAI",deepseek:"DeepSeek",claude:"Claude",ollama:"Ollama (Local)"},embedTitle:"Embedding Model",embedHint:"Configure a separate Embedding provider when it differs from the LLM provider. Leave unset to follow LLM.",embedModel:"Embedding Model Name",embedProviders:{followLlm:"Follow LLM"}},recipeEditor:{title:"Edit Recipe",authorityScore:"Authority",path:"Path",description:"Description",markdown:"Markdown Document",code:"Code / Standard Usage",rationale:"Design Rationale",steps:"Implementation Steps",codeChanges:"Code Changes",validation:"Validation",validationMethod:"Method:",validationExpected:"Expected:",tags:"Tags",constraints:"Constraints",guardRules:"Guard Rules",boundaryConstraints:"Boundary Constraints",preconditions:"Preconditions",sideEffects:"Side Effects",relations:"Relations",preview:"Preview",edit:"Edit",cancel:"Cancel",saveChanges:"Save Changes",saving:"Saving...",qualityLevels:{basic:"Basic",good:"Good",solid:"Solid",great:"Great",excellent:"Excellent"},descPlaceholder:"Recipe summary description...",rationalePlaceholder:"Why this approach...",relationTypes:{inherits:"Inherits",implements:"Implements",calls:"Calls",dependsOn:"Depends on",dataFlow:"Data flow",conflicts:"Conflicts",extends:"Extends",associates:"Associates"},noContent:"No content",authorityFailed:"Failed to set authority score:"},searchModal:{title:"as:search — Select & Insert",keyword:"Keyword:",keywordAll:"(all)",insertTo:"Insert to:",noResults:"No matching Recipe found",quality:"Quality:",insertBtn:"Insert",inserting:"Inserting...",insertSuccess:"✅ Inserted to",insertFailed:"❌ Insert failed"},refineProgress:{refining:"Refining",completed:"Completed",reviewing:"Reviewing",progress:"{current}/{total}",fields:"Fields:",timeElapsed:"Elapsed",eta:"ETA",title:"AI Refine",doneTitle:"AI Refine Complete",runningTitle:"AI Refining",doneMsg:"{refined} items updated",doneMsgWithFail:"{refined} updated, {failed} failed",progressMsg:"{done}/{total} candidates",closeBtn:"Close"},spmCompare:{title:"SPM Version Compare",current:"Current",latest:"Latest",diff:"Diff",added:"Added",removed:"Removed",changed:"Changed",unchanged:"Unchanged",updateAvailable:"Update available",upToDate:"Up to date",updateBtn:"Update Dependencies",closeBtn:"Close",package:"Package",from:"From",to:"To",noChanges:"No changes",candidateCopied:"Candidate content copied to clipboard",recipeCopied:"Recipe content copied to clipboard",copied:"Copied",deleteConfirm:"Are you sure you want to delete this candidate?",deleteFailed:"Delete failed",compareTitle:"Compare: Candidate vs Recipe",deleteCandidate:"Delete Candidate",auditCandidate:"Audit Candidate",editRecipe:"Edit Recipe",switchRecipe:"Switch Recipe:",candidateTitle:"Candidate: {title}",copyCandidate:"Copy Candidate",noCode:"(No code)",aiContextProfile:"AI Context / Project Profile",noGuide:"(No guide)",copyRecipe:"Copy Recipe"},silentLabels:{watch:"as:create",draft:"Draft",cli:"CLI",pending:"Pending (24h)",recipe:"New Recipe"},lifecycle:{pending:"Pending",staging:"Staging",active:"Published",evolving:"Evolving",decaying:"Decaying",deprecated:"Deprecated"},kind:{rule:"Rule",pattern:"Pattern",fact:"Fact"},app:{errorBoundary:{title:"Something went wrong",refreshBtn:"Refresh Page"},projectRefresh:{success:"Target list and file tree updated",successTitle:"Project Structure Refreshed",failed:"Refresh failed"},extract:{success:"Extracted results are in the candidate pool. Review in Candidates.",successTitle:"Extraction Complete",markerSuccess:"Pinpointed marked code, added to candidate pool",normalSuccess:"Extracted results added to candidate pool",noMarker:"No ASD markers found, AI will analyze the full file",extracting:"Extracting",failed:"Extraction failed"},clipboard:{empty:"Please copy code to clipboard first",emptyTitle:"Clipboard Empty",analyzing:"Code received, AI is identifying reusable patterns...",analyzingTitle:"Analyzing Clipboard",resultMulti:"Identified {count} Recipes, review in candidate pool",resultTitle:"AI Identification Complete",aiFailed:"AI Identification Failed",permissionError:"Browser may not have clipboard permission",permissionTitle:"Clipboard Read Failed"},load:{failed:"Unable to load project data",failedTitle:"Load Failed",failedHint:"Confirm the project path is valid and try again"},scan:{events:{initializing:"Starting scan...",filesLoaded:"Loaded {count} source files",readingFiles:"Reading {count} file contents...",aiAnalyzing:"AI analyzing reusable patterns...",enriching:"Enriching {count} results...",completing:"Scan complete, loading results..."},streamInit:"Establishing stream connection...",completed:"Scan complete",targetSuccess:"Found {count} reusable code patterns, review on the right",targetSuccessTitle:"Target Scan Complete",aiNotConfigured:"AI Not Configured",noResults:"AI scan returned no results",noCode:"No reusable code found in this Target",scanComplete:"Scan Complete",scanFailedHint:"Confirm the Target contains valid source files",scanFailed:"Scan Failed",timeout:"Scan timed out. Try reducing the number of Target files.",timeoutTitle:"Scan Timeout",scanError:"Scan Error"},coldStart:{collecting:"Collecting project structure...",skeletonCreated:"Skeleton created, filling in background...",skeletonDetail:"Project scan skeleton created: {targets} Targets, {files} files, {deps} dependencies... Filling dimensions in background...",guardSuffix:"Guard: {count} violations",timeout:"Project scan timed out. Check project file count."},rescan:{analyzing:"Running incremental scan...",done:"Incremental scan complete",success:"Incremental scan done: preserved {preserved} Recipes, {healthy} healthy, {decayed} decayed",filling:"AI filling {count} gap dimensions in background...",timeout:"Incremental scan timed out. Please try again later."},fullScan:{collecting:"Collecting all Target files...",phase5:"Collecting source files...",phase15:"AI analyzing code patterns...",phase25:"AI extracting (large projects may take several minutes)...",phase35:"AI extracting...",phase45:"AI deep analysis...",phase55:"Continuing processing...",phase65:"Running Guard audit...",phase75:"Summarizing results...",phase85:"Almost done...",partialComplete:"Scan partially complete (timeout)",completed:"Full project scan complete",resultDetail:"Full project scan complete: {count} candidates",guardSuffix:"Guard: {count} violations",timeoutSuffix:"(partial results, AI timeout)",noContent:"Full project scan complete, no extractable content found",timeout:"Scan timed out. Try reducing file count or scanning per-Target.",timeoutTitle:"Scan Timeout",scanError:"Scan Error"},recipe:{triggerRequired:"Trigger is required",savedAsRecipe:"Saved and published as Recipe",savedToKb:"Saved to Knowledge Base",saveFailed:"Save failed",saveRecipeFailed:"Failed to save Recipe",deleteFailed:"Delete failed"},candidate:{clearConfirm:'Remove all candidates under "{name}"?',clearDone:"Removed all candidates under {name}",pushSuccess:"Added to Candidate review queue",pushFailed:"Failed to create Candidate"}},globalChat:{refineFields:{summary:"Description",code:"Code / Standard Usage",markdown:"Markdown Document",rationale:"Design Rationale",tags:"Tags",confidence:"Confidence",aiInsights:"AI Insights",agentNotes:"Agent Notes",relations:"Relations"},diff:{noChanges:"No changes detected",excludedRestore:"Excluded · Restore",exclude:"Exclude",before:"Before",after:"After",empty:"(empty)"},system:{refinePrefix:`🎯 Refine Mode — **{title}**

Current summary: {description}

**Enter refine instructions and AI will modify the candidate content accordingly.** Use the quick prompts below.`,noDescription:"(none)",changesApplied:"✅ Changes applied to candidate!",exitedRefine:"Exited refine mode, back to general chat.",refining:"🔄 AI is refining...",processing:"Processing...",thinking:"🔄 AI is thinking...",cancelled:"(Cancelled)"},refineTitle:"AI Refine",chatTitle:"AI Chat",refineSubtitle:"Refining...",chatSubtitle:"Ask anything about your project",exitRefine:"Exit Refine",newTopic:"New Topic",closeChat:"Close AI Chat",emptyTitle:"AI Chat",emptyDesc:"Ask project-related questions, or use AI to analyze code, refine candidates, etc.",quickPrompts:{analyzeArch:"Analyze project architecture",findDuplicates:"Find duplicate code",suggestOptimize:"Suggest optimizations"},refinePrompts:{addExamples:"Add concrete usage examples without changing anything else",optimizeComments:"Optimize code comments and descriptions",addCaveats:"Add common mistakes and caveats",improveSummary:"Improve summary quality, make it concise and professional",addPerformance:"Add performance considerations"},loading:{analyzing:"AI is analyzing...",thinking:"AI is thinking..."},stopBtn:"Stop",assistantRefine:"AI Refine Assistant",assistantChat:"AI Assistant",confirmApply:"Confirm Apply",confirmApplyN:"Confirm Apply ({i}/{total})",applyingBtn:"Applying...",continueAdjust:"Continue Adjusting",nextItem:"Next",inputHintRefine:"Enter to send · Shift+Enter for newline · Preview before applying",inputHintChat:"Enter to send · Shift+Enter for newline",refinePlaceholder:'Enter refine instructions, e.g. "add usage examples", "optimize summary"...',chatPlaceholder:"Enter your question...",applySuccess:"Candidate content updated to refined version",applySuccessTitle:"Refine Applied",applyFailed:"Apply Failed",refinePreviewFailed:"Refine preview failed: {error}",requestFailed:"Request failed: {error}",previewGenerated:"Refine preview generated with {count} field changes (toggle individually):",noChangeHint:"No changes detected. Try a more specific instruction.",refineTopicPrefix:"Refine: {title}",untitled:"Untitled"},chatStream:{stepProgress:"🔄 Step {step}/{maxSteps}",toolFailed:"failed",toolResultChars:"{size} chars",andNFiles:" and {n} files",tools:{get_project_overview:"Get project overview",list_project_structure:"Browse directory",read_project_file:"Read file",search_project_code:"Search code",get_file_summary:"Get file summary",semantic_search_code:"Semantic search",get_class_hierarchy:"Analyze class hierarchy",get_class_info:"Get class info",get_protocol_info:"Get protocol info",get_method_overrides:"Analyze overrides",get_category_map:"Get category map",search_knowledge:"Search knowledge",search_recipes:"Search recipes",search_candidates:"Search candidates",get_recipe_detail:"Get recipe detail",get_related_recipes:"Find related recipes",get_project_stats:"Get project stats",knowledge_overview:"Knowledge overview",analyze_code:"Analyze code",enrich_candidate:"Enrich candidate",refine_bootstrap_candidates:"Refine candidates",add_graph_edge:"Add graph edge",quality_score:"Quality score",submit_knowledge:"Submit knowledge",submit_with_check:"Submit & check",save_document:"Save document",approve_candidate:"Approve candidate",reject_candidate:"Reject candidate",publish_recipe:"Publish recipe",deprecate_recipe:"Deprecate recipe",update_recipe:"Update recipe",record_usage:"Record usage",guard_check_code:"Check code rules",query_violations:"Query violations",list_guard_rules:"List guard rules",get_recommendations:"Get recommendations",get_feedback_stats:"Get feedback stats",graph_impact_analysis:"Impact analysis",rebuild_index:"Rebuild index",query_audit_log:"Query audit log",bootstrap_knowledge:"Bootstrap knowledge",load_skill:"Load skill",create_skill:"Create skill",suggest_skills:"Suggest skills",plan_task:"Plan task",review_my_output:"Review output",get_tool_details:"Get tool details",get_previous_analysis:"Review past analysis",note_finding:"Note finding",get_previous_evidence:"Get prior evidence"}},chatPanel:{defaultLoading:"AI is processing...",defaultEmptyTitle:"Start a conversation",defaultEmptyDesc:"Describe what you want AI to do and it will handle it for you.",defaultAssistant:"AI Assistant",defaultPlaceholder:"Enter instructions...",defaultInputHint:"Enter to send · Shift+Enter for newline",docContent:"Document Content"},constants:{bootstrapDims:{architecture:"Architecture & Design",bestPractice:"Standards & Practices",eventAndDataFlow:"Events & Data Flow",objcDeepScan:"Deep Scan",agentGuidelines:"Agent Guidelines",bootstrap:"Bootstrap",codeStandard:"Code Standards",codePattern:"Design Patterns",projectProfile:"Project Profile",categoryScan:"Category Scan"}},tokenUsageChart:{loadFailed:"Load failed",loading:"Loading token usage…",totalToken:"Total Tokens",totalSub:"7-day total",input:"Input",output:"Output",calls:"Calls",avgPerCall:"avg {avg}/call",emptyState:"No token usage yet. Data will be recorded automatically after using ChatAgent or MCP.",dailyUsage:"Daily Usage",weekday0:"Sun",weekday1:"Mon",weekday2:"Tue",weekday3:"Wed",weekday4:"Thu",weekday5:"Fri",weekday6:"Sat",dailyDetail:"Input {input} · Output {output}",dailyCalls:"{count} calls",legendInput:"Input",legendOutput:"Output",sourceDistribution:"Source Distribution"},knowledgeGraphRelations:{dependsOn:"Depends On",requires:"Requires",extends:"Extends",implements:"Implements",inherits:"Inherits",enforces:"Enforces",associates:"Associates",conflicts:"Conflicts",calls:"Calls",prerequisite:"Prerequisite",dataFlow:"Data Flow",references:"References",alternative:"Alternative",deprecatedBy:"Deprecated By",solves:"Solves",timeout:"Timeout"},shared:{renderingChart:"Rendering chart…",switchToChinese:"Switch to Chinese"},scanResultCard:{includeMarkOn:"On: write // as:include marker in code",includeMarkOff:"Off: do not write import markers",formatHeaders:"Normalize import format",cleanUnused:"Remove unreferenced headers from code",similarWithClick:"Similar to {name} {score}%, click to compare"},skillsView:{aiPromptPrefix:"Please create a Skill document for the following scenario:",placeholderDesc:"e.g., Create a Skill about SwiftUI animation best practices...",placeholderName:"SwiftUI Animation Best Practices Guide",placeholderContent:`# My Custom Skill

## Use Cases

## Steps`},guardRuleMessages:{"no-main-thread-sync":"Do not use dispatch_sync(main) on the main thread — risk of deadlock","main-thread-sync-swift":"Do not use DispatchQueue.main.sync on the main thread — risk of deadlock","objc-dealloc-async":"Do not call dispatch_async / dispatch_after / postNotification inside dealloc","objc-block-retain-cycle":"Using self directly in a block may cause a retain cycle — use weakSelf","objc-assign-object":"assign on object types creates dangling pointers — use weak or strong","swift-force-cast":"Force cast as! crashes on failure — use as? or guard let instead","swift-force-try":"try! crashes on error — use do-catch or try? instead","objc-timer-retain-cycle":"NSTimer strongly retains self as target — invalidate before dealloc or use block API","objc-possible-main-thread-blocking":"sleep/usleep may block the main thread","js-no-eval":"eval() poses security and performance risks — avoid using it","js-no-var":"Use let/const instead of var to avoid hoisting issues","js-no-console-log":"Remove console.log from production code — use a dedicated logger","js-no-debugger":"Production code should not contain debugger statements","js-no-alert":"Do not use alert() in production code — poor user experience","ts-no-non-null-assertion":"Non-null assertion ! may mask null/undefined errors","py-no-bare-except":"Bare except: catches all exceptions (incl. SystemExit) — specify the exception type","py-no-exec":"exec() poses security risks — avoid using it","py-no-mutable-default":"Mutable default arguments (list/dict/set) cause shared-state bugs","py-no-star-import":"from module import * pollutes the namespace — use explicit imports","py-no-assert-in-prod":"assert is removed under -O flag — do not use for production logic validation","java-no-system-exit":"System.exit() terminates the JVM directly — throw an exception or return a status code","java-no-raw-type":"Use generic collections instead of raw types (e.g., List<String> instead of List)","java-no-empty-catch":"Empty catch blocks silently swallow exceptions — at least log the error","java-no-thread-stop":"Thread.stop() is deprecated and unsafe — use interrupt() for cooperative termination","kotlin-no-force-unwrap":"!! throws NPE when value is null — use ?. or ?: for safe access","go-no-panic":"panic should only be used for unrecoverable errors — library code should return error","go-no-err-ignored":"Errors should not be ignored with _ — handle or explicitly annotate them","go-no-init-abuse":"init() side effects are hard to trace — avoid complex logic in init","go-no-global-var":"Global mutable variables cause concurrency issues — consider dependency injection","dart-no-print":"Use a logger instead of print() in production code — enables log levels and toggling","dart-avoid-dynamic":"Avoid the dynamic type — use concrete types or generics for type safety","dart-no-set-state-after-dispose":"Check mounted before calling setState — avoid calling after dispose","dart-avoid-bang-operator":"Avoid the ! null assertion operator — prefer ?? default value or ?. safe call","dart-prefer-const-constructor":"Declare constructor as const when all fields are final to optimize Widget rebuilds","dart-no-relative-import":"Use package: absolute imports inside lib/ — avoid relative path imports","dart-dispose-controller":"TextEditingController/AnimationController etc. must be disposed in dispose()","dart-no-build-context-across-async":"BuildContext should not be used across async gaps — may reference an unmounted Widget"},guardRuleFixSuggestions:{"objc-block-retain-cycle":"Declare __weak typeof(self) weakSelf = self; then use weakSelf inside the block","swift-force-cast":"Use as? with guard let / if let for safe casting","kotlin-no-force-unwrap":"Use ?. for safe calls or ?: for default values","dart-no-set-state-after-dispose":"Use if (mounted) setState(...) as a guard","dart-avoid-bang-operator":"Use ?. for safe calls or ?? for default values","dart-prefer-const-constructor":"Remove the new keyword and add const before Widget constructor calls","dart-dispose-controller":"Call controller.dispose() in State.dispose()","dart-no-build-context-across-async":"Cache needed data before await or check mounted after await"},signals:{title:"Signal & Report Center",tabSignals:"Signals",tabReports:"Reports",tabStats:"Stats",time1h:"1h",time6h:"6h",time24h:"24h",time7d:"7d",timeAll:"All",filterPlaceholder:"Filter types...",refresh:"Refresh",loading:"Loading...",showingSignals:"Showing {shown} of {total} signals",showingReports:"Showing {shown} of {total} reports",noSignals:"No signals in this time range",noReports:"No reports in this time range",noStats:"No stats available",totalSignals:"Total Signals",signalTypes:"Signal Types",sources:"Sources",byType:"By Type",bySource:"By Source",openMonitor:"Open Signal Monitor",closeMonitor:"Close Signal Monitor"}},ya={zh:Us,en:Sl},ms="asd-dashboard-lang";function Al(){try{const t=localStorage.getItem(ms);if(t==="en"||t==="zh")return t}catch{}return"zh"}function ja(t,s){const a=s.split(".");let r=t;for(const o of a){if(r==null||typeof r!="object")return;r=r[o]}return typeof r=="string"?r:void 0}function Dl(t,s){return s?t.replace(/\{(\w+)\}/g,(a,r)=>{const o=s[r];return o!=null?String(o):`{${r}}`}):t}const Tr=n.createContext(null);function Rl({children:t}){const[s,a]=n.useState(Al);n.useEffect(()=>{const i=localStorage.getItem(ms);i==="en"||i==="zh"?fetch("/api/v1/ai/lang",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lang:i})}).catch(()=>{}):fetch("/api/v1/ai/lang").then(p=>p.json()).then(p=>{const d=p?.data?.lang;if(d==="en"||d==="zh"){a(d);try{localStorage.setItem(ms,d)}catch{}}}).catch(()=>{})},[]);const r=n.useCallback(i=>{a(i);try{localStorage.setItem(ms,i)}catch{}fetch("/api/v1/ai/lang",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lang:i})}).catch(()=>{})},[]),o=n.useCallback((i,p)=>{const d=ja(ya[s],i)??ja(ya.zh,i)??i;return Dl(d,p)},[s]),l=n.useMemo(()=>({lang:s,setLang:r,t:o}),[s,r,o]);return e.jsx(Tr.Provider,{value:l,children:t})}function Ae(){const t=n.useContext(Tr);if(!t)throw new Error("useI18n must be used within <I18nProvider>");return t}const Er="asd-dashboard-theme";function Il(){return typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches}function Tl(){try{const t=localStorage.getItem(Er);if(t==="light"||t==="dark"||t==="system")return t}catch{}return"system"}const Pr=n.createContext(null);function El({children:t}){const[s,a]=n.useState(Tl),[r,o]=n.useState(Il);n.useEffect(()=>{const g=window.matchMedia("(prefers-color-scheme: dark)"),x=h=>o(h.matches);return g.addEventListener("change",x),()=>g.removeEventListener("change",x)},[]);const l=s==="dark"?!0:s==="light"?!1:r;n.useEffect(()=>{const g=document.documentElement;l?g.classList.add("dark"):g.classList.remove("dark")},[l]);const i=n.useCallback(g=>{a(g);try{localStorage.setItem(Er,g)}catch{}},[]),p=n.useCallback(()=>{i(l?"light":"dark")},[l,i]),d=n.useMemo(()=>({isDark:l,mode:s,toggle:p,setTheme:i}),[l,s,p,i]);return e.jsx(Pr.Provider,{value:d,children:t})}function Ns(){const t=n.useContext(Pr);if(!t)throw new Error("useTheme must be used within <ThemeProvider>");return t}const Pl="AutoSnippet";function Ml(t){if(typeof window>"u"||!("Notification"in window))return;const s=()=>{try{new Notification(Pl,{body:t,tag:"autosnippet"})}catch{}};if(Notification.permission==="granted"){s();return}Notification.permission!=="denied"&&Notification.requestPermission().then(a=>{a==="granted"&&s()}).catch(()=>{})}const Ll={success:5e3,error:8e3,info:5e3},wa={success:{bg:"linear-gradient(135deg,#ecfdf5 0%,#f0fdf4 100%)",border:"#10b981",bar:"#10b981",darkBg:"linear-gradient(135deg,#0c1a14 0%,#0f1f18 100%)",darkBorder:"#059669"},error:{bg:"linear-gradient(135deg,#fef2f2 0%,#fff1f2 100%)",border:"#ef4444",bar:"#ef4444",darkBg:"linear-gradient(135deg,#1c0f0f 0%,#1f1012 100%)",darkBorder:"#dc2626"},info:{bg:"linear-gradient(135deg,#eff6ff 0%,#f0f9ff 100%)",border:"#3b82f6",bar:"#3b82f6",darkBg:"linear-gradient(135deg,#0f1524 0%,#101828 100%)",darkBorder:"#2563eb"}},_l=()=>e.jsx("svg",{viewBox:"0 0 20 20",fill:"currentColor",className:"w-5 h-5 text-emerald-500 shrink-0",children:e.jsx("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})}),Fl=()=>e.jsx("svg",{viewBox:"0 0 20 20",fill:"currentColor",className:"w-5 h-5 text-red-400 shrink-0",children:e.jsx("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})}),Mr=()=>e.jsx("svg",{viewBox:"0 0 20 20",fill:"currentColor",className:"w-5 h-5 text-blue-400 shrink-0",children:e.jsx("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})}),zl={success:_l,error:Fl,info:Mr},Bl=({visible:t,toastId:s,body:a,type:r,title:o,duration:l})=>{const i=wa[r]||wa.info,p=zl[r]||Mr,d=typeof document<"u"&&document.documentElement.classList.contains("dark");return e.jsxs("div",{onClick:()=>Ja.dismiss(s),style:{background:d?i.darkBg:i.bg,borderLeft:`4px solid ${d?i.darkBorder:i.border}`,borderRadius:10,boxShadow:d?"0 8px 30px rgba(0,0,0,.4),0 2px 8px rgba(0,0,0,.25)":"0 8px 30px rgba(0,0,0,.12),0 2px 8px rgba(0,0,0,.06)",padding:"12px 16px 10px 14px",display:"flex",alignItems:"flex-start",gap:10,minWidth:280,maxWidth:420,position:"relative",overflow:"hidden",cursor:"pointer",opacity:t?1:0,transform:`translateY(${t?0:-8}px)`,transition:"opacity .25s ease, transform .25s ease"},children:[e.jsx("div",{style:{marginTop:1},children:e.jsx(p,{})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[o&&e.jsx("div",{style:{fontWeight:600,fontSize:13,lineHeight:1.3,color:d?"#e2e8f0":"#1e293b",marginBottom:2},children:o}),e.jsx("div",{style:{fontSize:12.5,lineHeight:1.45,color:d?"#94a3b8":"#475569",wordBreak:"break-word"},children:a})]}),e.jsx("div",{style:{position:"absolute",bottom:0,left:0,height:3,width:"100%",background:i.bar,opacity:.45,animation:`toast-progress ${l}ms linear forwards`}})]})};function ne(t,s){const a=s?.type??"success",r=s?.title,o=s?.duration??Ll[a]??5e3;typeof document<"u"&&document.visibilityState==="visible"?Gl(t,a,r,o):Ml(r?`${r}: ${t}`:t)}function Gl(t,s,a,r){Ja.custom(o=>e.jsx(Bl,{visible:o.visible,toastId:o.id,body:t,type:s,title:a,duration:r}),{duration:r})}if(typeof document<"u"){const t="asd-toast-progress-style";if(!document.getElementById(t)){const s=document.createElement("style");s.id=t,s.textContent=`
@keyframes toast-progress {
  from { width: 100%; }
  to   { width: 0%; }
}`,document.head.appendChild(s)}}const et={All:{icon:Ct,color:"text-slate-600",bg:"bg-slate-100",border:"border-slate-200"},View:{icon:Ds,color:"text-pink-600",bg:"bg-pink-50",border:"border-pink-100"},Service:{icon:Jt,color:"text-indigo-600",bg:"bg-indigo-50",border:"border-indigo-100"},Tool:{icon:Be,color:"text-amber-600",bg:"bg-amber-50",border:"border-amber-100"},Model:{icon:Gs,color:"text-emerald-600",bg:"bg-emerald-50",border:"border-emerald-100"},Network:{icon:xa,color:"text-blue-600",bg:"bg-blue-50",border:"border-blue-100"},Storage:{icon:Qn,color:"text-purple-600",bg:"bg-purple-50",border:"border-purple-100"},UI:{icon:gs,color:"text-cyan-600",bg:"bg-cyan-50",border:"border-cyan-100"},Utility:{icon:Ge,color:"text-orange-600",bg:"bg-orange-50",border:"border-orange-100"},architecture:{icon:Yn,color:"text-sky-600",bg:"bg-sky-50",border:"border-sky-100"},"coding-standards":{icon:Ue,color:"text-violet-600",bg:"bg-violet-50",border:"border-violet-100"},"design-patterns":{icon:Wt,color:"text-fuchsia-600",bg:"bg-fuchsia-50",border:"border-fuchsia-100"},"error-resilience":{icon:Ve,color:"text-emerald-600",bg:"bg-emerald-50",border:"border-emerald-100"},"concurrency-async":{icon:js,color:"text-rose-600",bg:"bg-rose-50",border:"border-rose-100"},"data-event-flow":{icon:Jn,color:"text-amber-600",bg:"bg-amber-50",border:"border-amber-100"},"networking-api":{icon:xa,color:"text-blue-600",bg:"bg-blue-50",border:"border-blue-100"},"ui-interaction":{icon:Ds,color:"text-pink-600",bg:"bg-pink-50",border:"border-pink-100"},"testing-quality":{icon:Vn,color:"text-lime-600",bg:"bg-lime-50",border:"border-lime-100"},"security-auth":{icon:hr,color:"text-red-600",bg:"bg-red-50",border:"border-red-100"},"performance-optimization":{icon:Wn,color:"text-orange-600",bg:"bg-orange-50",border:"border-orange-100"},"observability-logging":{icon:Ut,color:"text-teal-600",bg:"bg-teal-50",border:"border-teal-100"},"agent-guidelines":{icon:Mt,color:"text-rose-600",bg:"bg-rose-50",border:"border-rose-100"},"swift-objc-idiom":{icon:Un,color:"text-indigo-600",bg:"bg-indigo-50",border:"border-indigo-100"},"ts-js-module":{icon:pt,color:"text-yellow-600",bg:"bg-yellow-50",border:"border-yellow-100"},"python-structure":{icon:pa,color:"text-green-600",bg:"bg-green-50",border:"border-green-100"},"jvm-annotation":{icon:Ys,color:"text-orange-600",bg:"bg-orange-50",border:"border-orange-100"},"go-module":{icon:qn,color:"text-cyan-600",bg:"bg-cyan-50",border:"border-cyan-100"},"rust-ownership":{icon:Kn,color:"text-amber-600",bg:"bg-amber-50",border:"border-amber-100"},"csharp-dotnet":{icon:Hn,color:"text-purple-600",bg:"bg-purple-50",border:"border-purple-100"},"react-patterns":{icon:On,color:"text-sky-600",bg:"bg-sky-50",border:"border-sky-100"},"vue-patterns":{icon:$n,color:"text-emerald-600",bg:"bg-emerald-50",border:"border-emerald-100"},"spring-patterns":{icon:Gn,color:"text-lime-600",bg:"bg-lime-50",border:"border-lime-100"},"swiftui-patterns":{icon:Ds,color:"text-blue-600",bg:"bg-blue-50",border:"border-blue-100"},"django-fastapi":{icon:pa,color:"text-green-600",bg:"bg-green-50",border:"border-green-100"},bootstrap:{icon:Be,color:"text-violet-600",bg:"bg-violet-50",border:"border-violet-100"}},$l=["All","View","Service","Tool","Model","Network","Storage","UI","Utility"],Ol=["recipes","ai","spm","candidates","knowledge","guard","panorama","skills","wiki","signals","help"],bs=[{id:"swift",label:"Swift"},{id:"objectivec",label:"ObjC",aliases:["objc","objective-c","obj-c"]},{id:"go",label:"Go"},{id:"javascript",label:"JavaScript",aliases:["js"]},{id:"typescript",label:"TypeScript",aliases:["ts"]},{id:"python",label:"Python",aliases:["py"]},{id:"java",label:"Java"},{id:"kotlin",label:"Kotlin",aliases:["kt"]},{id:"rust",label:"Rust",aliases:["rs"]},{id:"dart",label:"Dart"},{id:"c",label:"C"},{id:"cpp",label:"C++",aliases:["c++"]},{id:"csharp",label:"C#",aliases:["cs"]},{id:"ruby",label:"Ruby",aliases:["rb"]}];function na(t){if(!t)return"";const s=t.toLowerCase().trim();for(const a of bs)if(a.id===s||a.aliases?.includes(s))return a.id;return s}function Na(t){switch(na(t)){case"objectivec":return"#import <Module/Header.h>";case"swift":return"import ModuleName";case"go":return'import "package/path"';case"python":return"import module_name";case"java":case"kotlin":return"import com.example.ClassName";case"javascript":case"typescript":return"import { name } from 'module'";case"rust":return"use crate::module::name;";case"dart":return"import 'package:name/name.dart';";case"csharp":return"using Namespace.Name;";case"ruby":return"require 'module_name'";case"c":case"cpp":return"#include <header.h>";default:return"import module"}}const Hl="https://github.com/GxFn/AutoSnippet/issues/new?title=Guard%20误报%2F建议%3A%20&body=请描述误报的规则ID、代码片段或改进建议。",ts=t=>["Example","Demo","Sample","Tests","Spec","Mock","Runner"].some(a=>t.endsWith(a)||t.includes(a)),Kl=t=>t.startsWith("_"),ql=t=>t==="_pending",Ul="您暂无写入权限,无法保存。如需此权限请联系管理员;请勿擅自修改核心代码或安装包,以免影响团队协作与数据安全。";function ps(t){const s=t?.response;if(s?.status!==403)return null;const a=s.data?.code,r=s.data?.error;return a==="RECIPE_WRITE_FORBIDDEN"||typeof r=="string"&&r.includes("没权限")?Ul:null}const Wl="保存过于频繁,请稍后再试。";function ka(t){const s=t?.response;return s?.data?s.status===403?ps(t)??null:s.status===429&&s.data?.code==="RECIPE_SAVE_RATE_LIMIT"?Wl:null:null}function ke(t,s="Unknown error"){if(typeof t=="string")return t;if(t instanceof Error)return t.message;if(ks(t)){const a=t.response?.data;if(a){if(typeof a.error=="string")return a.error;if(typeof a.error=="object"&&a.error?.message)return a.error.message;if(typeof a.message=="string")return a.message}if(t.message)return t.message}if(typeof t=="object"&&t!==null&&"message"in t){const a=t.message;if(typeof a=="string")return a}return s}function ks(t){return typeof t=="object"&&t!==null&&"response"in t&&typeof t.response=="object"}function Vl(t){if(ks(t))return t.response?.status}function fs(t){return t instanceof Error&&t.name==="AbortError"}function Is(t){return typeof t=="object"&&t!==null&&"__CANCEL__"in t}function ss(t){return ks(t)&&t.code==="ECONNABORTED"?!0:ke(t,"").toLowerCase().includes("timeout")}function Jl(t){return ks(t)?t.response?.data?.aiError===!0:!1}const X=ra.create({baseURL:"/api/v1"});function Yl(t){const s=t.quality||{},a=t.stats||t.statistics||{},r=t.content||{},o=t.trigger||"@"+(t.title||"").replace(/[\s_-]+(.)?/g,(i,p)=>p?p.toUpperCase():""),l={authority:a.authority||Math.round((s.overall||0)*5)||0,authorityScore:a.authority||Math.round((s.overall||0)*5)||0,guardUsageCount:a.applications||0,humanUsageCount:a.adoptions||0,aiUsageCount:0,lastUsedAt:t.updatedAt??null};return{id:t.id,name:(t.title||t.name||t.id||"")+".md",content:r,category:t.category||"",language:t.language||"",description:t.description||"",status:t.lifecycle||t.status||"pending",kind:t.kind||void 0,knowledgeType:t.knowledgeType||void 0,relations:t.relations??null,constraints:t.constraints??null,tags:t.tags||[],stats:l,trigger:o,source:t.source||"",sourceFile:t.sourceFile||"",moduleName:t.moduleName||"",usageGuide:r.markdown||t.doClause||"",reasoning:t.reasoning??null,quality:t.quality??null,scope:t.scope||"",complexity:t.complexity||"",difficulty:t.difficulty||t.complexity||"",version:t.version||"",headers:t.headers||[],updatedAt:t.updatedAt||null}}function Ql(t){let s="",a="general",r="",o="",l="",i="",p="",d="",g="",x=[],h=[],u="",m=0,c="1.0.0",j="",S="",D="",I="",P="",Y="",w="",G="",_="",N="",E=t;const L=t.match(/^---\n([\s\S]*?)\n---/);if(L){const $=L[1],U=me=>{const R=$.match(new RegExp(`^${me}:\\s*(.+)$`,"m"));return R?R[1].trim():null};s=U("language")||s,a=U("category")||a,r=U("title")||r,o=U("trigger")||"",l=U("summary_cn")||U("summary")||U("description")||l,i=U("summary_en")||"",p=U("knowledge_type")||U("knowledgeType")||"",d=U("complexity")||"",g=U("scope")||"",u=U("difficulty")||"",c=U("version")||"1.0.0";const q=U("authority");q&&(m=parseInt(q)||0);const A=U("tags");if(A)try{x=JSON.parse(A)}catch{x=A.split(",").map(me=>me.trim()).filter(Boolean)}const y=U("headers");if(y)try{h=JSON.parse(y)}catch{h=[y]}Y=U("kind")||"",w=U("doClause")||"",G=U("dontClause")||"",_=U("whenClause")||"",N=U("topicHint")||"";const W=t.match(/```[\w]*\n([\s\S]*?)```/);W&&(E=W[1].trim());const re=t.replace(/^---\n[\s\S]*?\n---/,"").trim(),he=re.match(/## (?:AI Context \/ )?Usage Guide(?:\s*\(CN\))?\n\n([\s\S]*?)(?=\n## |$)/);he&&(j=he[1].trim());const ue=re.match(/## (?:AI Context \/ )?Usage Guide\s*\(EN\)\n\n([\s\S]*?)(?=\n## |$)/);ue&&(S=ue[1].trim());const V=re.match(/## Architecture Usage\n\n([\s\S]*?)(?=\n## |$)/);V&&(D=V[1].trim());const B=re.match(/## Best Practices\n\n([\s\S]*?)(?=\n## |$)/);B&&(I=B[1].trim());const oe=re.match(/## Standards\n\n([\s\S]*?)(?=\n## |$)/);oe&&(P=oe[1].trim())}return{title:r,language:s,category:a,trigger:o,summary:l,summaryEn:i,knowledgeType:p,complexity:d,scope:g,tags:x,headers:h,difficulty:u,authority:m,version:c,codePattern:E,usageGuide:j,usageGuideEn:S,rationaleText:D,bestPracticesText:I,standardsText:P,kind:Y,doClause:w,dontClause:G,whenClause:_,topicHint:N}}function Zl(t,s,a){const r=Array.isArray(t.category)?t.category[0]:t.category||s||"general";return{title:t.title||"Untitled",content:t.content||{pattern:"",markdown:"",rationale:""},description:t.description||"",trigger:t.trigger||"",language:t.language||"",category:r,kind:t.kind||"pattern",knowledgeType:t.knowledgeType||"code-pattern",complexity:t.complexity||"intermediate",source:a,lifecycle:"pending",tags:t.tags||[],sourceFile:t.sourceFile||"",moduleName:t.moduleName||"",headers:t.headers||[],headerPaths:t.headerPaths||[],reasoning:{whyStandard:t.description||t.title||"Extracted from project",sources:[a],confidence:.6},metadata:{targetName:s||"",title:t.title||"",trigger:t.trigger||"",description:t.description||"",category:r,headers:t.headers||[],headerPaths:t.headerPaths||[],moduleName:t.moduleName||"",isMarked:t.isMarked||!1}}}async function Ft(t){const s=t.replace(/\.md$/i,"");if(/^[a-f0-9-]{8,}$/i.test(s))return s;const a=await X.get("/knowledge?limit=1000"),o=(a.data?.data?.data||a.data?.data||[]).find(l=>{const i=l.title||l.name||"";return i===s||i+".md"===t});if(o?.id)return o.id;throw new Error(`Knowledge entry not found: ${t}`)}async function Xl(t,s){const a=t.body?.getReader();if(!a)throw new Error("ReadableStream not available");const r=new TextDecoder;let o="",l="";for(;;){const{done:i,value:p}=await a.read();if(i)break;const d=r.decode(p,{stream:!0});o+=d;const g=o.split(`
`);o=g.pop()||"";for(const x of g){if(x.startsWith(":")||!x.startsWith("data: "))continue;const h=x.slice(6).trim();if(!(!h||h==="[DONE]"))try{const u=JSON.parse(h);if(s(u),u.type==="text:delta"&&u.delta)l+=u.delta;else if(u.type==="stream:done"&&u.text)l=u.text;else if(u.type==="stream:error")throw new Error(u.message||"Stream error")}catch(u){if(u instanceof SyntaxError)continue;throw u}}}return l}const Z={async fetchData(){const[t,s,a]=await Promise.all([X.get("/knowledge?limit=1000").catch(()=>({data:{success:!0,data:{data:[]}}})),X.get("/ai/config").catch(()=>({data:{success:!0,data:{provider:"",model:""}}})),X.get("/modules/project-info").catch(()=>({data:{success:!0,data:{projectRoot:""}}}))]),r=t.data?.data?.data||t.data?.data?.items||[],l=r.filter(m=>m.lifecycle==="active"||m.lifecycle==="evolving").map(Yl),i=new Set(["pending","staging"]),p=r.filter(m=>i.has(m.lifecycle)),d={};for(const m of p){const c=m.category||m.language||"_pending";d[c]||(d[c]={targetName:c,scanTime:m.createdAt,items:[]}),d[c].items.push(m)}const g=s.data?.data||{provider:"",model:""},x={};for(const m of r)m.id&&m.title&&(x[m.id]=m.title);const h=a.data?.data?.projectRoot||"",u=a.data?.data?.projectName||"";return{rootSpec:{},recipes:l,candidates:d,projectRoot:h,projectName:u,watcherStatus:"active",aiConfig:{provider:g.provider||"",model:g.model||""},idTitleMap:x}},async fetchTargets(){return((await X.get("/modules/targets")).data?.data||{}).targets||[]},async getTargetFiles(t,s){const r=(await X.post("/modules/target-files",{target:t},{signal:s})).data?.data||{};return{files:r.files||[],count:r.total||r.files?.length||0}},async scanTarget(t,s){const r=(await X.post("/modules/scan",{target:t},{signal:s,timeout:6e5})).data?.data||{};return{recipes:r.recipes||r.result||[],scannedFiles:r.scannedFiles||[],message:r.message||"",noAi:!!r.noAi}},async scanTargetStream(t,s,a){let r;const o=await fetch("/api/v1/modules/scan/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({target:t}),signal:a});if(!o.ok)throw new Error(`Scan stream start failed: ${o.status}`);if(r=(await o.json()).sessionId,!r)throw new Error("No sessionId returned");return new Promise((i,p)=>{const d=`/api/v1/modules/scan/events/${r}`,g=new EventSource(d);let x=!1,h={recipes:[],scannedFiles:[],message:"",noAi:!1};function u(){g.close()}if(g.onmessage=m=>{try{const c=JSON.parse(m.data);s(c),c.type==="scan:result"&&(h={recipes:c.recipes||[],scannedFiles:c.scannedFiles||[],message:c.message||"",noAi:!!c.noAi}),c.type==="stream:done"&&(u(),x=!0,i(h)),c.type==="stream:error"&&(u(),x=!0,p(new Error(c.message||"Scan stream error")))}catch{}},g.onerror=()=>{x||(u(),x=!0,h.recipes.length>0?i(h):p(new Error("EventSource connection failed")))},a){const m=()=>{x||(u(),x=!0,p(new DOMException("The operation was aborted.","AbortError")))};if(a.aborted){m();return}a.addEventListener("abort",m,{once:!0})}})},async scanProject(t){const a=(await X.post("/modules/scan-project",{},{signal:t,timeout:6e5})).data?.data||{};return{targets:a.targets||[],recipes:a.recipes||[],guardAudit:a.guardAudit||null,scannedFiles:a.scannedFiles||[],partial:a.partial||!1}},async browseDirectories(t="",s=3){const a=new URLSearchParams;return t&&a.set("path",t),s&&a.set("depth",String(s)),(await X.get(`/modules/browse-dirs?${a.toString()}`)).data?.data?.directories||[]},async scanFolderStream(t,s,a){const r=await fetch("/api/v1/modules/scan-folder/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t}),signal:a});if(!r.ok)throw new Error(`Scan folder start failed: ${r.status}`);const l=(await r.json()).sessionId;if(!l)throw new Error("No sessionId returned");return new Promise((i,p)=>{const d=`/api/v1/modules/scan/events/${l}`,g=new EventSource(d);let x=!1,h={recipes:[],scannedFiles:[],message:"",noAi:!1};function u(){g.close()}if(g.onmessage=m=>{try{const c=JSON.parse(m.data);s(c),c.type==="scan:result"&&(h={recipes:c.recipes||[],scannedFiles:c.scannedFiles||[],message:c.message||"",noAi:!!c.noAi}),c.type==="stream:done"&&(u(),x=!0,i(h)),c.type==="stream:error"&&(u(),x=!0,p(new Error(c.message||"Scan folder stream error")))}catch{}},g.onerror=()=>{x||(u(),x=!0,h.recipes.length>0?i(h):p(new Error("EventSource connection failed")))},a){const m=()=>{x||(u(),x=!0,p(new DOMException("The operation was aborted.","AbortError")))};if(a.aborted){m();return}a.addEventListener("abort",m,{once:!0})}})},async bootstrap(t){const a=(await X.post("/modules/bootstrap",{},{signal:t,timeout:3e5})).data?.data||{};return{report:a.report||{},targets:a.targets||[],filesByTarget:a.filesByTarget||{},dependencyGraph:a.dependencyGraph||null,languageStats:a.languageStats||{},primaryLanguage:a.primaryLanguage||"",guardSummary:a.guardSummary||null,guardViolationFiles:a.guardViolationFiles||[],bootstrapCandidates:a.bootstrapCandidates||{created:0,failed:0},bootstrapSession:a.bootstrapSession||null,asyncFill:a.asyncFill||!1,message:a.message||""}},async getBootstrapStatus(){return(await X.get("/modules/bootstrap/status")).data?.data||{status:"idle"}},async cancelBootstrap(t){return(await X.post("/modules/bootstrap/cancel",{reason:t})).data||{success:!0}},async rescan(t,s){const a=await X.post("/modules/rescan",t||{},{signal:s,timeout:3e5}),r=a.data?.data||{};return{rescan:r.rescan||{},relevanceAudit:r.relevanceAudit||{},gapAnalysis:r.gapAnalysis||{},bootstrapSession:r.bootstrapSession||null,asyncFill:r.asyncFill||!1,status:r.status||"complete",message:a.data?.message||""}},async getDepGraph(t){return(await X.get(`/modules/dep-graph?level=${t}`)).data?.data||{}},async getProjectInfo(){try{return(await X.get("/modules/project-info")).data?.data||{}}catch{return{primaryLanguage:"unknown",discoverers:[],hasSpm:!1}}},async refreshProject(){try{await X.post("/modules/update-map")}catch{await X.post("/commands/spm-map")}},async extractFromPath(t){const a=(await X.post("/extract/path",{relativePath:t})).data?.data||{};return{result:a.result||[],isMarked:a.isMarked||!1}},async extractFromText(t,s){const r=(await X.post("/extract/text",{text:t,...s?{relativePath:s}:{}})).data?.data||{};return Array.isArray(r.result)&&r.result.length>0?r.result[0]:r},async saveRecipe(t,s){const a=Ql(s),r=a.title||t.replace(/\.md$/,""),o={trigger:a.trigger,headers:a.headers,difficulty:a.difficulty,authority:a.authority,version:a.version},l={pattern:a.codePattern||"",rationale:a.rationaleText||"",steps:a.bestPracticesText?[a.bestPracticesText]:[],codeChanges:[],verification:null,markdown:a.usageGuide||""},i={};if(a.standardsText){const d=a.standardsText.split(`
`).map(h=>h.trim()).filter(Boolean),g=d.filter(h=>h.startsWith("- ")).map(h=>h.slice(2).trim());g.length>0&&(i.preconditions=g);const x=d.filter(h=>!h.startsWith("- ")&&!h.startsWith("**"));x.length>0&&(i.boundaries=x)}const p={title:r,language:a.language,category:a.category,description:a.summary,knowledgeType:a.knowledgeType||"code-pattern",complexity:a.complexity||"intermediate",scope:a.scope||null,tags:a.tags||[],content:l,constraints:i,dimensions:o};a.kind&&(p.kind=a.kind),a.doClause&&(p.doClause=a.doClause),a.dontClause&&(p.dontClause=a.dontClause),a.whenClause&&(p.whenClause=a.whenClause),a.topicHint&&(p.topicHint=a.topicHint);try{const d=await Ft(t);await X.patch(`/knowledge/${d}`,p);return}catch{}await X.post("/knowledge",p)},async deleteRecipe(t){const s=await Ft(t);await X.delete(`/knowledge/${s}`)},async getRecipeByName(t){const s=await Ft(t),r=(await X.get(`/knowledge/${s}`)).data?.data;if(!r)throw new Error("Recipe not found");const o=r.content||{};return{name:t,content:o.pattern||o.markdown||""}},async setRecipeAuthority(t,s){const a=await Ft(t);await X.patch(`/knowledge/${a}/quality`,{codeCompleteness:s,projectAdaptation:s,documentationClarity:s})},async updateRecipeRelations(t,s){const a=await Ft(t);await X.patch(`/knowledge/${a}`,{relations:s})},async getCandidate(t){const a=(await X.get(`/knowledge/${t}`)).data?.data;if(!a)throw new Error("Knowledge entry not found");return a},async deleteCandidate(t){await X.delete(`/knowledge/${t}`)},async promoteCandidateToRecipe(t,s){const r=(await X.patch(`/knowledge/${t}/publish`)).data?.data;return{recipe:r,candidate:r}},async enrichCandidates(t){return(await X.post("/candidates/enrich",{candidateIds:t})).data?.data||{enriched:0,total:0,results:[]}},async bootstrapRefine(t,s,a){return(await X.post("/candidates/bootstrap-refine",{candidateIds:t,userPrompt:s,dryRun:a},{timeout:3e5})).data?.data||{refined:0,total:0,errors:[],results:[]}},async refinePreview(t,s){return(await X.post("/candidates/refine-preview",{candidateId:t,userPrompt:s},{timeout:12e4})).data?.data||{}},async refineApply(t,s,a){return(await X.post("/candidates/refine-apply",{candidateId:t,userPrompt:s,preview:a},{timeout:12e4})).data?.data||{}},async getKnowledgeGraph(t=500){return(await X.get(`/search/graph/all?limit=${t}`)).data?.data||{edges:[],nodeLabels:{},nodeTypes:{},nodeCategories:{}}},async getGraphStats(){return(await X.get("/search/graph/stats")).data?.data||{totalEdges:0,byRelation:{},nodeTypes:[]}},async discoverRelations(t=20){const s=await X.post("/recipes/discover-relations",{batchSize:t});if(!s.data?.success)throw new Error(s.data?.error?.message||"启动失败");return s.data?.data||{status:"unknown"}},async getDiscoverRelationsStatus(){return(await X.get("/recipes/discover-relations/status")).data?.data||{status:"idle"}},async deleteAllCandidatesInTarget(t){const a=(await X.get(`/knowledge?category=${encodeURIComponent(t)}&limit=1000`)).data?.data?.data||[];let r=0;for(const o of a)try{await X.delete(`/knowledge/${o.id}`),r++}catch{}return{deleted:r}},async promoteToCandidate(t,s){const a=Zl(t,s,"review-promote");return{ok:!0,candidateId:(await X.post("/knowledge",a)).data?.data?.id||""}},async getAiProviders(){return(await X.get("/ai/providers")).data?.data||[]},async setAiConfig(t,s){return(await X.post("/ai/config",{provider:t,model:s})).data?.data||{provider:t,model:s}},async cleanupMockData(){return(await X.post("/ai/mock/cleanup")).data?.data||{deleted:0}},async chat(t,s,a){const o=(await X.post("/ai/chat",{prompt:t,history:s},{signal:a})).data?.data||{};return{text:o.reply||o.text||"",hasContext:o.hasContext}},async chatStream(t,s,a,r,o){const l=await fetch("/api/v1/ai/chat/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:t,history:s,...o?{lang:o}:{}}),signal:r});if(!l.ok)throw new Error(`Chat start failed: ${l.status}`);if((l.headers.get("content-type")||"").includes("text/event-stream")){let g={text:""};const x=await Xl(l,h=>{a(h),h.type==="stream:done"&&(h.text&&(g.text=h.text),g.toolCalls=h.toolCalls,g.hasContext=h.hasContext)});return!g.text&&x&&(g.text=x),g}const p=await l.json(),d=p.sessionId;if(!d)throw new Error(`No sessionId returned: ${JSON.stringify(p)}`);return new Promise((g,x)=>{const h=`/api/v1/ai/chat/events/${d}`,u=new EventSource(h);let m="",c={text:""},j=!1;function S(){u.close()}if(u.onmessage=D=>{try{const I=JSON.parse(D.data);if(I.type==="stream:start")return;a(I),I.type==="text:delta"&&I.delta&&(m+=I.delta),I.type==="stream:done"&&(c={text:I.text||m,toolCalls:I.toolCalls,hasContext:I.hasContext},S(),j=!0,g(c)),I.type==="stream:error"&&(S(),j=!0,x(new Error(I.message||"Stream error")))}catch{}},u.onerror=()=>{j||(S(),m?(j=!0,g({text:m})):(j=!0,x(new Error("EventSource connection failed"))))},r){const D=()=>{j||(S(),j=!0,x(new DOMException("The operation was aborted.","AbortError")))};r.aborted?D():r.addEventListener("abort",D,{once:!0})}})},async refinePreviewStream(t,s,a,r){const o=await fetch("/api/v1/candidates/refine-preview-stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({candidateId:t,userPrompt:s}),signal:r});if(!o.ok)throw new Error(`Refine stream start failed: ${o.status}`);const i=(await o.json()).sessionId;if(!i)throw new Error("No sessionId returned");return new Promise((p,d)=>{const g=`/api/v1/candidates/refine-preview/events/${i}`,x=new EventSource(g);let h=!1;function u(){x.close()}r&&r.addEventListener("abort",()=>{u(),h||(h=!0,d(new DOMException("Aborted","AbortError")))},{once:!0}),x.onmessage=m=>{try{const c=JSON.parse(m.data);a(c),c.type==="stream:done"&&(u(),h=!0,p({candidateId:c.candidateId||t,before:c.before||{},after:c.after||{},preview:c.preview||null})),c.type==="stream:error"&&(u(),h=!0,d(new Error(c.message||"Refine stream error")))}catch{}},x.onerror=()=>{u(),h||(h=!0,d(new Error("Refine EventSource connection lost")))}})},async summarizeCode(t,s){const a=await X.post("/ai/summarize",{code:t,language:s});return a.data?.data||a.data||{}},async translate(t,s){const a=await X.post("/ai/translate",{summary:t,usageGuide:s}),r=a.data?.data||{summaryEn:"",usageGuideEn:""};return a.data?.warning&&(r.warning=a.data.warning),r},async search(t,s={}){const{mode:a="auto",type:r,limit:o=20,signal:l,context:i}=s,p=u=>{if(!u)return{};if(typeof u=="object")return u;try{return JSON.parse(String(u))}catch{return{markdown:String(u)}}};if(i){const m=(await X.post("/search/context-aware",{keyword:t,limit:o,language:i.language,sessionHistory:i.sessionHistory||[]},{signal:l}).catch(()=>({data:{data:{}}}))).data?.data||{},c=(m.results||[]).map(j=>{const S=p(j.content);return{title:(j.name||"").replace(/\.md$/,""),content:S,score:j.similarity||0,qualityScore:j.qualityScore||0,usageCount:j.usageCount||0,authorityScore:j.authority||0,matchType:j.matchType}});return{items:c,total:m.total||c.length,mode:"weighted",ranked:!0}}const d=new URLSearchParams({q:t,mode:a,limit:String(o)});r&&d.set("type",r);const x=(await X.get(`/search?${d}`,{signal:l})).data?.data||{},h=(x.items||[]).map(u=>({...u,content:p(u.content)}));return{items:h,total:x.totalResults||x.total||h.length,mode:x.mode,ranked:x.ranked}},async getGuardRules(){const s=(await X.get("/rules?limit=100")).data?.data||{},a=s.data||s.items||[],r={};for(const o of a)r[o.id]=o;return{rules:r,projectLanguages:s.projectLanguages||[]}},async getGuardViolations(){const s=(await X.get("/violations")).data?.data||{};return{runs:s.data||s.items||[]}},async clearViolations(){await X.post("/violations/clear",{all:!0})},async saveGuardRule(t){return(await X.post("/rules",t)).data?.data||{}},async insertAtSearchMark(t){return{success:!1}},async listSkills(){return(await X.get("/skills")).data?.data||{skills:[],total:0}},async loadSkill(t,s){const a=s?`?section=${encodeURIComponent(s)}`:"";return(await X.get(`/skills/${encodeURIComponent(t)}${a}`)).data?.data||{}},async createSkill(t){return(await X.post("/skills",t)).data?.data||{}},async updateSkill(t,s){return(await X.put(`/skills/${encodeURIComponent(t)}`,s)).data?.data||{}},async deleteSkill(t){return(await X.delete(`/skills/${encodeURIComponent(t)}`)).data?.data||{}},async suggestSkills(){return(await X.get("/skills/suggest")).data?.data||{suggestions:[],analysisContext:{}}},async getSignalStatus(){return(await X.get("/skills/signal-status")).data?.data||{running:!1,mode:"off",snapshot:null}},async aiGenerateSkill(t){return(await X.post("/ai/chat",{prompt:`你是一个 AutoSnippet Skill 文档生成助手。用户会描述他们想创建的 Skill,你需要生成完整的 SKILL.md 内容。

Skill 文档格式要求:
1. 开头用 Markdown 标题说明 Skill 的目的
2. 包含清晰的使用场景说明
3. 列出具体的操作步骤和指南
4. 如有必要,包含代码示例
5. 使用中文撰写

请严格按以下格式输出(不要用代码块包裹 JSON):

第一行:一个 JSON 对象,包含 name(kebab-case,3-64 字符)和 description(一句话中文描述)
第二行:空行
第三行起:Skill 文档正文内容(Markdown 格式,不含 frontmatter)

示例输出:
{"name": "swiftui-animation-guide", "description": "SwiftUI 动画最佳实践指南"}

# SwiftUI 动画最佳实践

## 使用场景
...

用户需求:${t}`,history:[]})).data?.data||{reply:""}},async getLlmEnvConfig(){return(await X.get("/ai/env-config")).data?.data||{vars:{},hasEnvFile:!1,llmReady:!1}},async getTokenUsage7Days(){return(await X.get("/ai/token-usage")).data?.data||{daily:[],bySource:[],summary:{input_tokens:0,output_tokens:0,total_tokens:0,call_count:0,avg_per_call:0}}},async saveLlmEnvConfig(t){return(await X.post("/ai/env-config",t)).data?.data||{vars:{},hasEnvFile:!1,llmReady:!1}},async knowledgeList(t={}){const s=new URLSearchParams;t.page&&s.set("page",String(t.page)),t.limit&&s.set("limit",String(t.limit)),t.lifecycle&&s.set("lifecycle",t.lifecycle),t.kind&&s.set("kind",t.kind),t.category&&s.set("category",t.category),t.language&&s.set("language",t.language),t.keyword&&s.set("keyword",t.keyword),t.tag&&s.set("tag",t.tag),t.source&&s.set("source",t.source);const a=s.toString();return(await X.get(`/knowledge${a?`?${a}`:""}`)).data?.data||{data:[],pagination:{page:1,pageSize:20,total:0}}},async knowledgeStats(){return(await X.get("/knowledge/stats")).data?.data||{total:0,pending:0,active:0,deprecated:0,rules:0,patterns:0,facts:0}},async knowledgeGet(t){return(await X.get(`/knowledge/${t}`)).data?.data},async knowledgeCreate(t){return(await X.post("/knowledge",t)).data?.data},async knowledgeUpdate(t,s){return(await X.patch(`/knowledge/${t}`,s)).data?.data},async knowledgeDelete(t){await X.delete(`/knowledge/${t}`)},async knowledgeLifecycle(t,s,a){return(await X.patch(`/knowledge/${t}/${s}`,a?{reason:a}:{})).data?.data},async knowledgeBatchPublish(t){return(await X.post("/knowledge/batch-publish",{ids:t})).data?.data||{published:[],failed:[],successCount:0,failureCount:0}},async knowledgeBatchDelete(t){return(await X.post("/knowledge/batch-delete",{ids:t})).data?.data||{deletedCount:0,failureCount:0,failed:[]}},async knowledgeBatchDeprecate(t,s){return(await X.post("/knowledge/batch-deprecate",{ids:t,reason:s})).data?.data||{deprecated:[],failed:[],successCount:0,failureCount:0}},async knowledgeRecordUsage(t,s="adoption",a){await X.post(`/knowledge/${t}/usage`,{type:s,feedback:a})},async knowledgeUpdateQuality(t){return(await X.patch(`/knowledge/${t}/quality`)).data?.data||{quality:{}}},async wikiGenerate(){await X.post("/wiki/generate")},async wikiUpdate(){await X.post("/wiki/update")},async wikiAbort(){await X.post("/wiki/abort")},async wikiStatus(){return(await X.get("/wiki/status")).data?.data||{task:{status:"idle"}}},async wikiFiles(){return(await X.get("/wiki/files")).data?.data||{files:[],exists:!1}},async wikiFileContent(t){return(await X.get(`/wiki/file/${t}`)).data?.data||{path:t,content:"",size:0}},async getLang(){return(await X.get("/ai/lang")).data?.data?.lang||"zh"},async setLang(t){await X.post("/ai/lang",{lang:t})},async getPanoramaOverview(t=!1){return(await X.get("/panorama",t?{params:{refresh:"true"}}:void 0)).data?.data},async getPanoramaHealth(t=!1){return(await X.get("/panorama/health",t?{params:{refresh:"true"}}:void 0)).data?.data},async getPanoramaGaps(t=!1){return(await X.get("/panorama/gaps",t?{params:{refresh:"true"}}:void 0)).data?.data??[]},async getAuditLogs(t){return(await X.get("/audit",{params:t})).data?.data??{logs:[],total:0}},async getGuardReport(t){return(await X.get("/guard/report",{params:t})).data?.data},async getPanoramaCoverage(){return(await X.get("/panorama/coverage")).data?.data},async getKnowledgeLifecycle(){return(await X.get("/knowledge/lifecycle")).data?.data},async getSignalTrace(t){const s={};return t?.type?.length&&(s.type=t.type.join(",")),t?.source&&(s.source=t.source),t?.target&&(s.target=t.target),t?.from&&(s.from=String(t.from)),t?.to&&(s.to=String(t.to)),t?.limit&&(s.limit=String(t.limit)),t?.offset&&(s.offset=String(t.offset)),(await X.get("/signals/trace",{params:s})).data?.data},async getSignalStats(t){const s={};return t?.from&&(s.from=String(t.from)),t?.to&&(s.to=String(t.to)),(await X.get("/signals/stats",{params:s})).data?.data},async getReports(t){const s={};return t?.category?.length&&(s.category=t.category.join(",")),t?.type&&(s.type=t.type),t?.from&&(s.from=String(t.from)),t?.to&&(s.to=String(t.to)),t?.limit&&(s.limit=String(t.limit)),t?.offset&&(s.offset=String(t.offset)),(await X.get("/signals/reports",{params:s})).data?.data}},eo=!1,Ts="auth_token",Es="auth_user";function to(){const[t,s]=n.useState(()=>localStorage.getItem(Ts)),[a,r]=n.useState(()=>{try{const g=localStorage.getItem(Es);return g?JSON.parse(g):null}catch{return null}}),[o,l]=n.useState(!1),i=n.useCallback(async(g,x)=>{l(!0);try{const u=(await ra.post("/api/v1/auth/login",{username:g,password:x})).data;if(u.success){const m=u.data.token,c=u.data.user??{username:g,role:"developer"};return localStorage.setItem(Ts,m),localStorage.setItem(Es,JSON.stringify(c)),s(m),r(c),{success:!0}}return{success:!1,error:u.error?.message||"登录失败"}}catch(h){return{success:!1,error:ke(h,"网络错误")}}finally{l(!1)}},[]),p=n.useCallback(()=>{localStorage.removeItem(Ts),localStorage.removeItem(Es),s(null),r(null)},[]);n.useEffect(()=>{},[]);const d=n.useMemo(()=>!0,[t,a]);return{authEnabled:eo,isAuthenticated:d,isLoading:o,user:a,login:i,logout:p}}const so={developer:["*"],external_agent:["read:recipes","read:guard_rules","create:candidates","submit:knowledge","read:audit_logs:self","knowledge:bootstrap"],chat_agent:["read:recipes","read:candidates","create:candidates","read:guard_rules"]};function ao(t){const[s,a]=n.useState(()=>"developer"),[r,o]=n.useState("anonymous"),[l,i]=n.useState("probe"),[p,d]=n.useState(!0),[g,x]=n.useState(null),h=n.useCallback(async()=>{d(!0);try{const S=localStorage.getItem("auth_token"),D={};S&&(D.Authorization=`Bearer ${S}`);const I=await ra.get("/api/v1/auth/probe",{headers:D});if(I.data.success){const P=I.data.data;a(P.role),o(P.user),i(P.mode),x(P.probeCache??null)}}catch{a("developer")}finally{d(!1)}},[]);n.useEffect(()=>{h()},[t,h]);const u=n.useCallback((S,D)=>{const I=so[s]||[];if(I.includes("*"))return!0;const P=D?`${S}:${D}`:S;if(I.includes(P))return!0;const Y=S.split(":")[0];return!!(I.includes(`${Y}:*`)||Y==="read"&&I.includes("read:*"))},[s]),m=n.useMemo(()=>s==="developer",[s]),c=n.useMemo(()=>s==="developer",[s]),j=n.useMemo(()=>s!=="developer",[s]);return{role:s,user:r,mode:l,isLoading:p,isAdmin:m,canWrite:c,isReadOnly:j,can:u,probeCache:g,refresh:h}}let zt=null;function Cs(){return zt||(zt=jn(window.location.origin,{path:"/socket.io",transports:["websocket"],reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:2e3,reconnectionDelayMax:1e4}),zt.on("connect",()=>{zt.emit("join-notifications")})),zt}const Ps={activeRound:0,round1:{status:"idle"},round2:{status:"idle"},round3:{status:"idle"}};function ro(){const[t,s]=n.useState(null),[a,r]=n.useState(!1),[o,l]=n.useState(Ps),[i,p]=n.useState(0),d=n.useRef(null),g=n.useRef(null);n.useEffect(()=>{const m=Cs(),c=()=>{r(!0),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>S(),500)},j=()=>r(!1),S=async()=>{try{const A=await Z.getBootstrapStatus();A&&A.status==="running"&&A.tasks&&s(y=>!y||y.id===A.id||A.progress>(y?.progress??0)?(d.current=A.id,A):y)}catch{}},D=()=>S(),I=A=>{d.current=A.sessionId,l(Ps),s({id:A.sessionId,status:"running",progress:0,total:A.total,completed:0,failed:0,filling:0,skeleton:A.total,startedAt:A.startedAt||Date.now(),totalToolCalls:0,elapsedMs:0,tasks:A.tasks.map(y=>({id:y.id,status:"skeleton",meta:{type:y.type,dimId:y.dimId,label:y.label,skillWorthy:y.skillWorthy,skillMeta:y.skillMeta}}))})},P=A=>{s(y=>{if(!y)return y;const W=y.tasks.map(re=>re.id===A.taskId?{...re,status:"filling",startedAt:Date.now()}:re);return{...y,progress:A.progress,tasks:W,filling:W.filter(re=>re.status==="filling").length,skeleton:W.filter(re=>re.status==="skeleton").length}})},Y=A=>{s(W=>{if(!W)return W;const re=W.tasks.map(he=>he.id===A.taskId?{...he,status:"completed",completedAt:Date.now(),result:A.result}:he);return{...W,progress:A.progress,completed:A.completed,total:A.total,totalToolCalls:A.totalToolCalls??W.totalToolCalls,elapsedMs:A.elapsedMs??W.elapsedMs,tasks:re,filling:re.filter(he=>he.status==="filling").length,skeleton:re.filter(he=>he.status==="skeleton").length}}),(Number(A.result?.created)||Number(A.result?.extracted)||0)>0&&p(W=>W+1)},w=A=>{s(y=>{if(!y)return y;const W=y.tasks.map(re=>re.id===A.taskId?{...re,status:"failed",completedAt:Date.now(),error:A.error}:re);return{...y,progress:A.progress,failed:W.filter(re=>re.status==="failed").length,tasks:W,filling:W.filter(re=>re.status==="filling").length,skeleton:W.filter(re=>re.status==="skeleton").length}})},G=A=>{s(y=>{if(!y||A.sessionId&&y.id!==A.sessionId)return y;const W=y.tasks.map(re=>re.status==="skeleton"||re.status==="filling"?{...re,status:"completed",completedAt:Date.now()}:re);return{...y,status:W.some(re=>re.status==="failed")?"completed_with_errors":"completed",progress:100,completed:W.filter(re=>re.status==="completed").length,summary:A.summary,tasks:W,filling:0,skeleton:0}})},_=A=>{l(y=>({...y,activeRound:1,round1:{status:"running",total:A.total}}))},N=A=>{l(y=>({...y,activeRound:1,round1:{status:"completed",total:A.total,kept:A.kept,dropped:A.dropped,merged:A.merged}}))},E=A=>{l(y=>({...y,activeRound:2,round2:{status:"running",total:A.total}}))},L=A=>{l(y=>({...y,activeRound:2,round2:{...y.round2,status:"running",current:A.current,total:A.total,progress:A.progress}}))},$=A=>{l(y=>({...y,activeRound:2,round2:{status:"completed",total:A.total,refined:A.refined,progress:100}}))},U=A=>{l(y=>({...y,activeRound:3,round3:{status:"running",total:A.total}}))},q=A=>{l(y=>({...y,activeRound:3,round3:{status:"completed",total:A.total,afterDedup:A.afterDedup,relationsFound:A.relationsFound}}))};return m.on("connect",c),m.on("disconnect",j),m.io.on("reconnect",D),m.on("bootstrap:started",I),m.on("bootstrap:task-started",P),m.on("bootstrap:task-completed",Y),m.on("bootstrap:task-failed",w),m.on("bootstrap:all-completed",G),m.on("review:round1-started",_),m.on("review:round1-completed",N),m.on("review:round2-started",E),m.on("review:round2-progress",L),m.on("review:round2-completed",$),m.on("review:round3-started",U),m.on("review:round3-completed",q),r(m.connected),m.connected&&S(),()=>{g.current&&clearTimeout(g.current),m.off("connect",c),m.off("disconnect",j),m.io.off("reconnect",D),m.off("bootstrap:started",I),m.off("bootstrap:task-started",P),m.off("bootstrap:task-completed",Y),m.off("bootstrap:task-failed",w),m.off("bootstrap:all-completed",G),m.off("review:round1-started",_),m.off("review:round1-completed",N),m.off("review:round2-started",E),m.off("review:round2-progress",L),m.off("review:round2-completed",$),m.off("review:round3-started",U),m.off("review:round3-completed",q)}},[]);const x=n.useCallback(()=>{d.current=null,s(null),l(Ps)},[]),h=n.useCallback(m=>{m&&s(c=>{if(c&&c.id===m.id){const j=(c.filling??0)+(c.completed??0)+(c.failed??0),S=(m.filling??0)+(m.completed??0)+(m.failed??0);if(c.progress>m.progress||j>S)return c}return d.current=m.id,m})},[]),u=t?.status==="completed"||t?.status==="completed_with_errors";return{session:t,isConnected:a,isAllDone:u,reviewState:o,candidateCreatedTick:i,resetSession:x,initFromApiResponse:h}}const H={xs:12,sm:14,md:16,lg:20,xl:24,xxl:32,xxxl:48};function je(...t){return wn(Nn(t))}const Lr=Cn,wt=Sn,Nt=An,ft=n.forwardRef(({className:t,sideOffset:s=6,...a},r)=>e.jsx(kn,{children:e.jsx(Ya,{ref:r,sideOffset:s,className:je("z-50 overflow-hidden rounded-[var(--radius-md)] bg-[var(--bg-emphasis)] px-2.5 py-1.5 text-xs font-medium text-[var(--fg-on-emphasis)] shadow-[var(--shadow-lg)]","animate-in fade-in-0 zoom-in-95","data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95","data-[side=bottom]:slide-in-from-top-1 data-[side=left]:slide-in-from-right-1 data-[side=right]:slide-in-from-left-1 data-[side=top]:slide-in-from-bottom-1",t),...a})}));ft.displayName=Ya.displayName;function Ca({item:t,active:s,onClick:a}){return e.jsxs(wt,{delayDuration:300,children:[e.jsx(Nt,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:a,className:je("relative flex items-center justify-center w-10 h-10 rounded-[var(--radius-md)] transition-all duration-200",s?"bg-[var(--accent)] text-white shadow-[0_0_16px_var(--accent-glow)]":"text-[var(--fg-subtle)] hover:bg-[var(--bg-muted)]/60 hover:text-[var(--fg-default)]"),children:[e.jsx(t.icon,{size:18,className:"shrink-0"}),t.badge!=null&&e.jsxs("span",{className:"absolute -top-0.5 -right-0.5 flex h-2.5 w-2.5 items-center justify-center",children:[e.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-[var(--warning)] opacity-40"}),e.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-[var(--warning)]"})]})]})}),e.jsx(ft,{side:"right",className:"flex items-center gap-1.5",children:e.jsx("span",{children:t.label})})]})}const no=({activeTab:t,navigateToTab:s,candidateCount:a,signalSuggestionCount:r=0,currentUser:o,onLogout:l})=>{const{t:i,lang:p,setLang:d}=Ae(),{isDark:g,toggle:x}=Ns(),h=[{tab:"recipes",icon:br,label:i("sidebar.recipes")},{tab:"candidates",icon:hs,label:i("sidebar.candidates",{count:a})},{tab:"knowledge",icon:Qs,label:i("sidebar.batchManage")},{tab:"panorama",icon:Ge,label:i("sidebar.panorama")},{tab:"spm",icon:fr,label:i("sidebar.moduleExplorer")},{tab:"guard",icon:Ve,label:i("sidebar.guard")},{tab:"skills",icon:ds,label:i("sidebar.skills"),badge:r>0?r:void 0},{tab:"wiki",icon:Ue,label:i("sidebar.repoWiki")},{tab:"signals",icon:Yt,label:"Signals"},{tab:"ai",icon:ut,label:i("sidebar.aiAssistant")},{tab:"help",icon:vr,label:i("sidebar.help")}],u=h.slice(0,h.length-2),m=h.slice(h.length-2);return e.jsx(Lr,{children:e.jsxs("aside",{className:"w-[var(--sidebar-width)] flex flex-col shrink-0 glass-surface select-none z-10",children:[e.jsx("div",{className:"flex items-center justify-center h-[var(--topbar-height)] border-b border-[var(--border-muted)]",children:e.jsx("div",{className:"w-9 h-9 rounded-[var(--radius-md)] flex items-center justify-center text-white shadow-[0_0_20px_var(--accent-glow)]",style:{background:"var(--accent-gradient)"},children:e.jsx("span",{className:"text-[11px] font-black italic tracking-tighter leading-none",children:"AS"})})}),e.jsxs("nav",{className:"flex-1 flex flex-col items-center gap-1 py-3 overflow-y-auto scrollbar-hidden",children:[u.map(c=>e.jsx(Ca,{item:c,active:t===c.tab,onClick:()=>s(c.tab)},c.tab)),e.jsx("div",{className:"w-6 separator-gradient my-2"}),m.map(c=>e.jsx(Ca,{item:c,active:t===c.tab,onClick:()=>s(c.tab)},c.tab))]}),e.jsxs("div",{className:"flex flex-col items-center gap-1 py-3 border-t border-[var(--border-muted)]",children:[e.jsxs(wt,{delayDuration:300,children:[e.jsx(Nt,{asChild:!0,children:e.jsx("button",{onClick:()=>d(p==="zh"?"en":"zh"),className:"flex items-center justify-center w-10 h-10 rounded-[var(--radius-md)] text-[var(--fg-subtle)] hover:bg-[var(--bg-muted)] hover:text-[var(--fg-default)] transition-colors",children:e.jsx(Zn,{size:18})})}),e.jsx(ft,{side:"right",children:i("header.langSwitch")})]}),e.jsxs(wt,{delayDuration:300,children:[e.jsx(Nt,{asChild:!0,children:e.jsx("button",{onClick:x,className:"flex items-center justify-center w-10 h-10 rounded-[var(--radius-md)] text-[var(--fg-subtle)] hover:bg-[var(--bg-muted)] hover:text-[var(--fg-default)] transition-colors",children:g?e.jsx(Xn,{size:18}):e.jsx(el,{size:18})})}),e.jsx(ft,{side:"right",children:i(g?"header.lightMode":"header.darkMode")})]}),o&&e.jsxs(wt,{delayDuration:300,children:[e.jsx(Nt,{asChild:!0,children:e.jsx("button",{onClick:l,className:"flex items-center justify-center w-10 h-10 rounded-[var(--radius-md)] text-[var(--fg-subtle)] hover:bg-[var(--bg-muted)] hover:text-[var(--danger)] transition-colors",children:e.jsx(yr,{size:18})})}),e.jsxs(ft,{side:"right",className:"flex items-center gap-2",children:[e.jsx("span",{children:o}),l&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[var(--fg-subtle)]",children:"·"}),e.jsxs("span",{className:"flex items-center gap-1 text-[var(--danger)]",children:[e.jsx(tl,{size:12}),i("sidebar.logout")]})]})]})]})]})]})})},lo={objectivec:"objectivec",objc:"objectivec","objective-c":"objectivec","obj-c":"objectivec",swift:"swift",go:"go",javascript:"javascript",js:"javascript",typescript:"typescript",ts:"typescript",python:"python",py:"python",java:"java",kotlin:"kotlin",kt:"kotlin",rust:"rust",rs:"rust",dart:"dart",c:"c",cpp:"cpp","c++":"cpp",csharp:"csharp",cs:"csharp",ruby:"ruby",rb:"ruby",markdown:"markdown",md:"markdown",json:"json",yaml:"yaml",xml:"xml",bash:"bash",sh:"bash",shell:"bash",sql:"sql",html:"html",css:"css",text:"text"};function la(t){if(!t)return t;let s=t;!s.includes(`
`)&&s.includes("\\n")&&(s=s.replace(/\\n/g,`
`));const a=s.match(/\\(?=[\[\]{}()*+?^$.|])/g);return a&&a.length>=3&&(s=s.replace(/\\([\[\]{}()*+?^$.|])/g,"$1")),s}const vt=({code:t,language:s="text",className:a="",showLineNumbers:r=!1})=>{const o=lo[s?.toLowerCase()]||s?.toLowerCase()||"text",l=a.includes("!rounded-none"),i=la(t);return e.jsx("div",{className:`rounded-xl overflow-x-auto text-sm min-w-0 ${a}`,children:e.jsx(Qa,{language:o,style:Za,showLineNumbers:r,customStyle:{margin:0,padding:"1rem 1.25rem",fontSize:"0.8125rem",lineHeight:1.5,borderRadius:l?0:"0.75rem",overflowX:"auto"},codeTagProps:{className:"language-highlighted",style:{fontFamily:"ui-monospace, monospace"}},PreTag:"div",children:i})})};let oo=0,Sa="";function io(t){const s=t?"dark":"default";s!==Sa&&(Xa.initialize({startOnLoad:!1,theme:s,securityLevel:"loose",fontFamily:"ui-sans-serif, system-ui, -apple-system, sans-serif",...t?{themeVariables:{darkMode:!0,background:"#1e1e1e",primaryColor:"#2d3748",primaryTextColor:"#e2e8f0",primaryBorderColor:"#4a5568",lineColor:"#94a3b8",secondaryColor:"#283040",tertiaryColor:"#1a2332",noteBkgColor:"#283040",noteTextColor:"#e2e8f0",noteBorderColor:"#4a5568"}}:{}}),Sa=s)}const _r=({code:t})=>{const{t:s}=Ae(),{isDark:a}=Ns(),[r,o]=n.useState(""),[l,i]=n.useState("");return n.useEffect(()=>{let p=!1;const d=`mermaid_${oo++}`;async function g(){io(a);try{const{svg:x}=await Xa.render(d,t.trim());p||(o(x),i(""))}catch(x){p||(i(ke(x,"Mermaid render failed")),o(""));try{document.getElementById("d"+d)?.remove()}catch{}}}return g(),()=>{p=!0}},[t,a]),l?e.jsx("div",{className:"my-4 p-4 bg-slate-800 text-slate-200 rounded-lg overflow-x-auto text-sm font-mono whitespace-pre-wrap",children:t}):r?e.jsx("div",{className:"my-5 flex justify-center overflow-x-auto rounded-lg border p-4 border-[var(--border-default)] bg-[var(--bg-surface)]",dangerouslySetInnerHTML:{__html:r}}):e.jsx("div",{className:"my-4 flex items-center justify-center py-8 text-[var(--fg-muted)] text-sm",children:s("shared.renderingChart")})};function co(t){return!t||typeof t!="string"?t:t.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,"").trim()||t}function uo(t){return!t||typeof t!="string"?t:t.replace(/\\\\n/g,`
`)}function mo(t){if(!t||typeof t!="string")return t;const s=t.split(`
`),a=[];let r=!1;for(let o=0;o<s.length;o++){const l=s[o];if(/^\s*(`{3,}|~{3,})/.test(l)){r=!r,a.push(l);continue}if(r){a.push(l);continue}const i=s[o+1];l!==""&&i!==void 0&&i!==""?a.push(l+"  "):a.push(l)}return a.join(`
`)}const po=/^\s*(graph|flowchart|sequenceDiagram|classDiagram|stateDiagram|erDiagram|gantt|pie|gitGraph|mindmap|timeline|journey|quadrantChart|sankey|xychart|block)\b/i;function xo(t){const s=[],a=t.split(`
`);let r=[],o=!1,l=!1,i=[];for(let p=0;p<a.length;p++){const d=a[p],g=/^\s*(`{3,}|~{3,})(.*)$/.exec(d);if(g&&!l&&!o)if(g[2].trim().toLowerCase()==="mermaid"){r.length>0&&(s.push({type:"markdown",content:r.join(`
`)}),r=[]),o=!0,i=[];continue}else{l=!0,r.push(d);continue}if(o&&g){s.push({type:"mermaid",content:i.join(`
`)}),o=!1,i=[];continue}if(l&&g){l=!1,r.push(d);continue}o?i.push(d):r.push(d)}return o&&i.length>0&&s.push({type:"mermaid",content:i.join(`
`)}),r.length>0&&s.push({type:"markdown",content:r.join(`
`)}),s}const go=t=>({pre({children:s}){return e.jsx("div",{className:"min-w-0",children:s})},code({node:s,className:a,children:r,...o}){const l=/language-(\w+)/.exec(a||""),i=Array.isArray(r)?r.join(""):String(r),p=i.replace(/\n$/,""),d=i.includes(`
`)||!!l;return d&&po.test(p)?e.jsx(_r,{code:p}):d&&l?e.jsx(vt,{code:p,language:l[1],showLineNumbers:t}):d?e.jsx(vt,{code:p,language:"text",showLineNumbers:t}):e.jsx("code",{className:"px-1.5 py-0.5 bg-[var(--bg-subtle)] text-[var(--fg-primary)] rounded text-[0.9em] font-mono border border-[var(--border-default)]",...o,children:r})},p:({children:s})=>e.jsx("p",{className:"mb-4 leading-7 last:mb-0",children:s}),h1:({children:s,...a})=>{const r=typeof s=="string"?s.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g,"-").replace(/(^-|-$)/g,""):void 0;return e.jsx("h1",{id:r,className:"text-[1.75rem] font-bold mb-4 mt-8 first:mt-0 pb-2 border-b border-[var(--border-default)] text-[var(--fg-primary)] leading-tight scroll-mt-20",...a,children:s})},h2:({children:s,...a})=>{const r=typeof s=="string"?s.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g,"-").replace(/(^-|-$)/g,""):void 0;return e.jsx("h2",{id:r,className:"text-xl font-bold mb-3 mt-8 pb-1.5 border-b border-[var(--border-default)] text-[var(--fg-primary)] leading-snug scroll-mt-20",...a,children:s})},h3:({children:s,...a})=>{const r=typeof s=="string"?s.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g,"-").replace(/(^-|-$)/g,""):void 0;return e.jsx("h3",{id:r,className:"text-lg font-semibold mb-2 mt-6 text-[var(--fg-primary)] leading-snug scroll-mt-20",...a,children:s})},h4:({children:s,...a})=>{const r=typeof s=="string"?s.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g,"-").replace(/(^-|-$)/g,""):void 0;return e.jsx("h4",{id:r,className:"text-base font-semibold mb-2 mt-5 text-[var(--fg-primary)] scroll-mt-20",...a,children:s})},strong:({children:s})=>e.jsx("strong",{className:"font-semibold text-[var(--fg-primary)]",children:s}),em:({children:s})=>e.jsx("em",{className:"italic text-[var(--fg-secondary)]",children:s}),del:({children:s})=>e.jsx("del",{className:"line-through text-[var(--fg-muted)]",children:s}),hr:()=>e.jsx("hr",{className:"my-8 border-0 h-px bg-[var(--border-default)]"}),ul:({children:s})=>e.jsx("ul",{className:"list-disc pl-6 mb-4 space-y-1.5 marker:text-[var(--fg-muted)]",children:s}),ol:({children:s})=>e.jsx("ol",{className:"list-decimal pl-6 mb-4 space-y-1.5 marker:text-[var(--fg-secondary)]",children:s}),li:({children:s,...a})=>{const r=a.node,o=r?.children?.[0]?.type==="element"&&r?.children?.[0]?.tagName==="input";return e.jsx("li",{className:`leading-7 ${o?"list-none -ml-6 flex items-start gap-2":""}`,children:s})},blockquote:({children:s})=>e.jsx("blockquote",{className:"border-l-4 border-blue-300 bg-blue-50/40 pl-4 pr-3 py-2 my-4 text-[var(--fg-secondary)] rounded-r-lg [&>p]:mb-2 [&>p:last-child]:mb-0",children:s}),a:({href:s,children:a})=>s?.startsWith("#")?e.jsx("a",{href:s,className:"text-blue-600 hover:text-blue-700 hover:underline underline-offset-2 decoration-blue-300/70 transition-colors",children:a}):e.jsx("a",{href:s,className:"text-blue-600 hover:text-blue-700 hover:underline underline-offset-2 decoration-blue-300/70 transition-colors",target:"_blank",rel:"noopener noreferrer",children:a}),img:({src:s,alt:a})=>e.jsx("img",{src:s,alt:a||"",className:"max-w-full h-auto rounded-lg border border-[var(--border-default)] my-4",loading:"lazy"}),table:({children:s})=>e.jsx("div",{className:"my-5 overflow-x-auto rounded-lg border border-[var(--border-default)]",children:e.jsx("table",{className:"w-full border-collapse text-sm",children:s})}),thead:({children:s})=>e.jsx("thead",{className:"bg-[var(--bg-subtle)] border-b border-[var(--border-default)]",children:s}),tbody:({children:s})=>e.jsx("tbody",{className:"divide-y divide-[var(--border-default)]",children:s}),tr:({children:s})=>e.jsx("tr",{className:"hover:bg-[var(--bg-subtle)] transition-colors",children:s}),th:({children:s})=>e.jsx("th",{className:"px-4 py-2.5 text-left text-xs font-semibold text-[var(--fg-secondary)] uppercase tracking-wider",children:s}),td:({children:s})=>e.jsx("td",{className:"px-4 py-2.5 text-[var(--fg-primary)] align-top",children:s}),input:({checked:s})=>e.jsx("input",{type:"checkbox",checked:s,readOnly:!0,className:"mt-1 w-4 h-4 rounded border-[var(--border-default)] text-blue-600 cursor-default"})}),Qt=({content:t,className:s="",showLineNumbers:a=!1,stripFrontmatter:r=!1})=>{const o=n.useMemo(()=>go(a),[a]),l=n.useMemo(()=>{let i=r?co(t):t;return i=uo(i),i=mo(i),xo(i)},[t,r]);return e.jsx("div",{className:`markdown-body text-[var(--fg-primary)] ${s}`,children:l.map((i,p)=>i.type==="mermaid"?e.jsx(_r,{code:i.content},`mermaid-${p}`):e.jsx(Dn,{remarkPlugins:[Rn],components:o,children:i.content},`md-${p}`))})},Fr="asd-chat-topics",ho=50;function bo(){return Date.now().toString(36)+Math.random().toString(36).substring(2,8)}function fo(t){const s=t.find(r=>r.role==="user");if(!s)return"新话题";const a=s.content.trim().replace(/\n/g," ");return a.length>30?a.slice(0,30)+"…":a}function vo(){try{const t=localStorage.getItem(Fr);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s:[]}catch{return[]}}function yo(t){try{const s=t.slice(0,ho);localStorage.setItem(Fr,JSON.stringify(s))}catch(s){console.warn("[ChatTopics] localStorage save failed:",s)}}function zr(){const[t,s]=n.useState(()=>vo()),[a,r]=n.useState(null),o=n.useRef(t);n.useEffect(()=>{o.current=t},[t]);const l=n.useCallback(u=>{s(m=>{const c=typeof u=="function"?u(m):u;return yo(c),c})},[]),i=n.useCallback(u=>{const m=bo(),c={id:m,title:u||"新话题",messages:[],createdAt:Date.now(),updatedAt:Date.now()};return l(j=>[c,...j]),r(m),m},[l]),p=n.useCallback(u=>{l(m=>m.filter(c=>c.id!==u)),r(m=>m===u?null:m)},[l]),d=n.useCallback((u,m)=>{l(c=>{const j=c.findIndex(P=>P.id===u);if(j<0)return c;const S={...c[j],messages:m,updatedAt:Date.now()},D=fo(m);D!=="新话题"&&(S.title=D);const I=[...c];return I[j]=S,I.splice(j,1),I.unshift(S),I})},[l]),g=n.useCallback(u=>o.current.find(m=>m.id===u),[]),x=n.useCallback(u=>{r(u)},[]),h=t.find(u=>u.id===a)??null;return{topics:t,activeTopicId:a,activeTopic:h,createTopic:i,deleteTopic:p,saveTopic:d,getTopic:g,switchTopic:x,setActiveTopicId:r}}function jo(t,s){const a=`chatStream.tools.${s}`,r=t(a);return r===a?s:r}function wo(t,s,a){if(!a)return"";switch(s){case"read_project_file":{const r=a.filePath||(Array.isArray(a.filePaths)?a.filePaths[0]:"");if(!r)return"";const o=String(r).split("/").pop()||r,l=Array.isArray(a.filePaths)&&a.filePaths.length>1?t("chatStream.andNFiles",{n:a.filePaths.length}):"";return`${o}${l}`}case"list_project_structure":{const r=a.directory||a.path||"";return r?String(r):""}case"search_project_code":{const r=a.patterns||a.pattern||a.query||"";return Array.isArray(r)?r.slice(0,2).join(", ")+(r.length>2?" …":""):String(r).slice(0,40)}case"semantic_search_code":case"search_knowledge":case"search_recipes":case"search_candidates":{const r=a.query||a.keyword||"";return String(r).slice(0,40)}case"get_class_info":case"get_protocol_info":return a.className||a.name||a.protocolName||"";case"get_file_summary":{const r=a.filePath||"";return r&&String(r).split("/").pop()||""}case"summarize_code":case"analyze_code":{const r=a.language||"";return r?`${r}`:""}case"get_class_hierarchy":return a.rootClass||"";default:return""}}function Aa(t,s,a){const r=jo(t,s),o=wo(t,s,a);return o?`${r}: ${o}`:r}function Br(t,s,a){const r=[],o=[];let l="";function i(d){s(g=>g.map(x=>x.id===t?{...x,content:d}:x))}function p(d){switch(d.type){case"step:start":{const g=d.phase==="user"?"":` [${d.phase}]`,x=a("chatStream.stepProgress",{step:d.step,maxSteps:d.maxSteps})+g+"...",h=r.length>0?r.join(`
`)+`

`+x:x;i(h);break}case"tool:start":{r.push(`🔧 ${Aa(a,d.tool,d.args)}...`),o.push({tool:d.tool,args:d.args}),i(r.join(`
`));break}case"tool:end":{const g=r.length-1;if(g>=0){const x=o[g]||{tool:d.tool},h=Aa(a,x.tool,x.args);if(d.status==="error"||d.error)r[g]=`❌ ${h} ${a("chatStream.toolFailed")} (${d.duration}ms)`;else{const u=d.resultSize>1e3?`${(d.resultSize/1024).toFixed(1)}KB`:a("chatStream.toolResultChars",{size:d.resultSize});r[g]=`✅ ${h} → ${u} (${d.duration}ms)`}i(r.join(`
`))}break}case"text:start":{l="";break}case"text:delta":{l+=d.delta||"";const g=r.length>0?r.join(`
`)+`

---

`:"";i(g+l);break}}}return{onEvent:p,getState:()=>({answerText:l,toolLogs:r})}}const Gr=n.createContext({openChat:()=>{},openRefine:()=>{},close:()=>{},toggle:()=>{},newTopic:()=>{},isOpen:!1}),Zt=()=>n.useContext(Gr),Dt=()=>Math.random().toString(36).substring(2,10),No=[{key:"description",labelKey:"globalChat.refineFields.summary"},{key:"pattern",labelKey:"globalChat.refineFields.code"},{key:"markdown",labelKey:"globalChat.refineFields.markdown"},{key:"rationale",labelKey:"globalChat.refineFields.rationale"},{key:"tags",labelKey:"globalChat.refineFields.tags",format:t=>Array.isArray(t)?t.join(", "):String(t||"")},{key:"confidence",labelKey:"globalChat.refineFields.confidence",format:t=>String(t??"—")},{key:"aiInsight",labelKey:"globalChat.refineFields.aiInsights"},{key:"agentNotes",labelKey:"globalChat.refineFields.agentNotes",format:t=>Array.isArray(t)?t.join(`
`):String(t||"")},{key:"relations",labelKey:"globalChat.refineFields.relations",format:t=>JSON.stringify(t||{},null,2)}];function ko(t,s,a){const r=[];for(const o of No){const l=o.format||(d=>String(d??"")),i=l(t[o.key]),p=l(s[o.key]);p&&p!==i&&r.push({field:o.key,label:a(o.labelKey),before:i,after:p})}return r}function Da(t){return{title:t.title||"",description:t.description||"",pattern:t.content?.pattern||"",markdown:t.content?.markdown||"",rationale:t.content?.rationale||"",tags:t.tags||[],confidence:t.reasoning?.confidence??.6,relations:t.relations||{},aiInsight:t.aiInsight||null,agentNotes:t.agentNotes||null}}const Co=({diff:t,excludedFields:s=[],onToggleField:a})=>{const{t:r}=Ae();return t.length===0?e.jsx("p",{className:"text-xs text-[var(--fg-muted)] italic py-2",children:r("globalChat.diff.noChanges")}):e.jsx("div",{className:"space-y-2 mt-2",children:t.map(o=>{const l=s.includes(o.field);return e.jsxs("div",{className:`border rounded-lg overflow-hidden transition-opacity ${l?"border-[var(--border-default)] opacity-45":"border-[var(--border-default)]"}`,children:[e.jsxs("div",{className:"px-2.5 py-1.5 border-b flex items-center gap-1.5 bg-[var(--bg-subtle)] border-[var(--border-default)]",children:[e.jsx(jr,{size:10,className:l?"text-[var(--fg-muted)]":"text-emerald-500"}),e.jsx("span",{className:`text-[10px] font-bold flex-1 ${l?"text-[var(--fg-muted)] line-through":"text-[var(--fg-secondary)]"}`,children:o.label}),a&&(l?e.jsx("button",{onClick:()=>a(o.field),className:"px-2 py-0.5 text-[9px] font-bold rounded-full bg-[var(--bg-subtle)] text-[var(--fg-secondary)] hover:bg-emerald-100 hover:text-emerald-600 transition-colors",title:r("globalChat.diff.excludedRestore"),children:r("globalChat.diff.excludedRestore")}):e.jsxs("button",{onClick:()=>a(o.field),className:"group flex items-center gap-0.5 px-1.5 py-0.5 text-[9px] font-medium rounded-full text-[var(--fg-muted)] hover:bg-red-50 hover:text-red-500 transition-colors",title:r("globalChat.diff.exclude"),children:[e.jsx(ze,{size:10,className:"opacity-60 group-hover:opacity-100"}),r("globalChat.diff.exclude")]}))]}),!l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"p-2 bg-red-50/30 border-b border-[var(--border-default)]",children:[e.jsx("div",{className:"text-[9px] font-bold text-red-400 mb-0.5 uppercase",children:r("globalChat.diff.before")}),e.jsx("pre",{className:"text-[11px] text-[var(--fg-secondary)] whitespace-pre-wrap break-words max-h-40 overflow-auto font-mono leading-relaxed scrollbar-light",children:o.before||e.jsx("span",{className:"italic text-[var(--fg-muted)]",children:r("globalChat.diff.empty")})})]}),e.jsxs("div",{className:"p-2 bg-emerald-50/30",children:[e.jsx("div",{className:"text-[9px] font-bold text-emerald-500 mb-0.5 uppercase",children:r("globalChat.diff.after")}),e.jsx("pre",{className:"text-[11px] text-[var(--fg-primary)] whitespace-pre-wrap break-words max-h-40 overflow-auto font-mono leading-relaxed scrollbar-light",children:o.after})]})]})]},o.field)})})},$r=n.createContext(null),So=({children:t})=>{const{t:s}=Ae(),[a,r]=n.useState(!1),[o,l]=n.useState([]),[i,p]=n.useState(!1),[d,g]=n.useState(!1),[x,h]=n.useState(null),[u,m]=n.useState(new Set),[c,j]=n.useState(""),S=n.useRef([]),D=!!x,I=x?x.candidateIds[x.currentIdx]:null,P=x?x.candidates.find(U=>U.id===I):void 0,Y=x?x.candidateIds.length>1:!1;n.useEffect(()=>{x&&P&&(l(U=>[...U,{id:Dt(),role:"system",content:s("globalChat.system.refinePrefix",{title:P.title,description:P.description||s("globalChat.system.noDescription")}),timestamp:Date.now()}]),j(""))},[x?.currentIdx]);const w=n.useCallback(()=>{h(null),r(!0)},[]),G=n.useCallback(U=>{h({...U,currentIdx:0}),m(new Set),l([]),S.current=[],r(!0)},[]),_=n.useCallback(()=>r(!1),[]),N=n.useCallback(()=>r(U=>!U),[]),E=n.useCallback(()=>{l([]),S.current=[],j(""),h(null),m(new Set)},[]),L={openChat:w,openRefine:G,close:_,toggle:N,newTopic:E,isOpen:a},$={messages:o,setMessages:l,loading:i,setLoading:p,applying:d,setApplying:g,refineCtx:x,setRefineCtx:h,applied:u,setApplied:m,lastPrompt:c,setLastPrompt:j,chatHistoryRef:S,isRefineMode:D,currentRefineId:I,currentRefineCandidate:P,isBatchRefine:Y,close:_};return e.jsx(Gr.Provider,{value:L,children:e.jsx($r.Provider,{value:$,children:t})})},Ao=()=>{const{t,lang:s}=Ae(),a=n.useContext($r),{messages:r,setMessages:o,loading:l,setLoading:i,applying:p,setApplying:d,refineCtx:g,setRefineCtx:x,applied:h,setApplied:u,lastPrompt:m,setLastPrompt:c,chatHistoryRef:j,isRefineMode:S,currentRefineId:D,currentRefineCandidate:I,isBatchRefine:P,close:Y}=a,w=n.useRef(null),G=n.useRef(null),[_,N]=n.useState(""),E=zr(),L=n.useRef(null),$=n.useRef(!1);n.useEffect(()=>{if(S&&I){$.current=!0;const B=E.createTopic(t("globalChat.refineTopicPrefix",{title:I.title||t("globalChat.untitled")}));L.current=B,setTimeout(()=>{$.current=!1},50)}},[g]),n.useEffect(()=>{$.current||L.current&&r.length>0&&E.saveTopic(L.current,r)},[r]);const U=n.useCallback(()=>{if(!L.current){$.current=!0;const B=E.createTopic();L.current=B,setTimeout(()=>{$.current=!1},50)}},[E]);n.useEffect(()=>{w.current?.scrollIntoView({behavior:"smooth"})},[r,l]),n.useEffect(()=>{setTimeout(()=>G.current?.focus(),200)},[]);const q=S&&D&&r.some(B=>{if(B.role!=="assistant"||!B.diff||B.diff.length===0)return!1;const oe=B.excludedFields||[];return B.diff.some(me=>!oe.includes(me.field))})&&!h.has(D),A=n.useCallback((B,oe)=>{o(me=>me.map(R=>{if(R.id!==B)return R;const T=R.excludedFields||[],ee=T.includes(oe)?T.filter(ie=>ie!==oe):[...T,oe];return{...R,excludedFields:ee}}))},[]),y=n.useRef(null),W=n.useCallback(async()=>{const B=_.trim();if(!(!B||l)){if(S||U(),N(""),o(oe=>[...oe,{id:Dt(),role:"user",content:B,timestamp:Date.now()}]),i(!0),S&&D){c(B);const oe=Dt();o(R=>[...R,{id:oe,role:"assistant",content:t("globalChat.system.refining"),timestamp:Date.now()}]);const me=new AbortController;y.current=me;try{const R=await Z.refinePreviewStream(D,B,ie=>{if(ie.type==="data:progress"){const xe=ie.message||ie.stage||t("globalChat.system.processing");o(pe=>pe.map(M=>M.id===oe?{...M,content:`🔄 ${xe}`}:M))}},me.signal),T=R.before||(I?Da(I):{}),ee=ko(T,R.after||{},t);o(ie=>ie.map(xe=>xe.id===oe?{...xe,content:ee.length>0?t("globalChat.previewGenerated",{count:ee.length}):t("globalChat.noChangeHint"),diff:ee.length>0?ee:void 0,preview:ee.length>0?R.preview??void 0:void 0,excludedFields:[]}:xe))}catch(R){fs(R)?o(T=>T.map(ee=>ee.id===oe?{...ee,content:t("globalChat.system.cancelled")}:ee)):o(T=>T.map(ee=>ee.id===oe?{...ee,content:t("globalChat.refinePreviewFailed",{error:ke(R)})}:ee))}finally{y.current=null}}else{j.current.push({role:"user",content:B});const oe=Dt();o(ie=>[...ie,{id:oe,role:"assistant",content:t("globalChat.system.thinking"),timestamp:Date.now()}]);const me=new AbortController;y.current=me;const{onEvent:R,getState:T}=Br(oe,o,t);let ee="";try{const xe=(await Z.chatStream(B,j.current,pe=>{R(pe),ee=T().answerText},me.signal,s)).text||ee;j.current.push({role:"model",content:xe}),o(pe=>pe.map(M=>M.id===oe?{...M,content:xe}:M))}catch(ie){if(fs(ie)){const{answerText:xe,toolLogs:pe}=T(),M=xe||(pe.length>0?pe.join(`
`)+`

`+t("globalChat.system.cancelled"):t("globalChat.system.cancelled"));xe&&j.current.push({role:"model",content:xe}),o(Ce=>Ce.map(F=>F.id===oe?{...F,content:M}:F))}else o(xe=>xe.map(pe=>pe.id===oe?{...pe,content:t("globalChat.requestFailed",{error:ke(ie)})}:pe))}finally{y.current=null}}i(!1)}},[_,l,S,D,I,U]),re=n.useCallback(async()=>{if(!(p||!D||!g)){d(!0);try{const B=[...r].reverse().find(me=>me.role==="assistant"&&me.preview);let oe=B?.preview;if(oe&&B?.excludedFields?.length&&B.diff){oe={...oe};const me=I?Da(I):{};for(const R of B.excludedFields)R in me&&(oe[R]=me[R])}await Z.refineApply(D,m,oe),u(me=>new Set(me).add(D)),g.onCandidateUpdated?.(D),o(me=>[...me,{id:Dt(),role:"system",content:t("globalChat.system.changesApplied"),timestamp:Date.now()}]),ne(t("globalChat.applySuccess"),{title:t("globalChat.applySuccessTitle")})}catch(B){ne(ke(B),{title:t("globalChat.applyFailed"),type:"error"})}finally{d(!1)}}},[p,D,m,g]),he=n.useCallback(()=>{!g||g.currentIdx>=g.candidateIds.length-1||x(B=>B?{...B,currentIdx:B.currentIdx+1}:null)},[g]),ue=n.useCallback(()=>{L.current=null,x(null),o(B=>[...B,{id:Dt(),role:"system",content:t("globalChat.system.exitedRefine"),timestamp:Date.now()}])},[]),V=n.useCallback(B=>{B.key==="Enter"&&!B.shiftKey&&(B.preventDefault(),W())},[W]);return e.jsxs("aside",{className:"w-[420px] h-full bg-[var(--bg-surface)] border-l border-[var(--border-default)] flex flex-col shrink-0",children:[e.jsxs("div",{className:"px-4 h-[var(--topbar-height)] border-b border-[var(--border-default)] flex items-center justify-between shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-gradient-to-br from-blue-50 to-indigo-50 border border-blue-100 flex items-center justify-center",children:S?e.jsx(Le,{className:"text-emerald-500",size:16}):e.jsx(ut,{className:"text-blue-600",size:16})}),e.jsxs("div",{children:[e.jsxs("h3",{className:"text-[13px] font-bold text-[var(--fg-primary)] flex items-center gap-2",children:[t(S?"globalChat.refineTitle":"globalChat.chatTitle"),S&&P&&e.jsxs("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-emerald-50 text-emerald-600 font-medium",children:[(g?.currentIdx??0)+1,"/",g?.candidateIds.length]})]}),e.jsx("p",{className:"text-[10px] text-[var(--fg-muted)] truncate max-w-[250px]",children:S?I?.title||t("globalChat.refineSubtitle"):t("globalChat.chatSubtitle")})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[S&&e.jsx("button",{onClick:ue,className:"px-2 py-1 text-[10px] font-medium text-[var(--fg-secondary)] hover:text-[var(--fg-primary)] hover:bg-[var(--bg-subtle)] rounded-md transition-colors",children:t("globalChat.exitRefine")}),!S&&r.length>0&&e.jsx("button",{onClick:()=>{L.current=null,o([]),j.current=[],c("")},className:"p-1.5 hover:bg-[var(--bg-subtle)] rounded-lg transition-colors",title:t("globalChat.newTopic"),children:e.jsx(mt,{size:16,className:"text-[var(--fg-muted)]"})}),e.jsx("button",{onClick:Y,className:"p-1.5 hover:bg-[var(--bg-subtle)] rounded-lg transition-colors",title:t("globalChat.closeChat"),children:e.jsx(ze,{size:16,className:"text-[var(--fg-muted)]"})})]})]}),S&&I&&e.jsx("div",{className:"border-b border-[var(--border-default)] bg-emerald-50/30 px-4 py-2 shrink-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] font-bold text-emerald-700 truncate flex-1",children:I.title}),I.language&&e.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100",children:I.language})]})}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-3 min-h-0 scrollbar-light",children:[r.length===0&&!S&&e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center py-10",children:[e.jsx("div",{className:"w-12 h-12 rounded-2xl bg-blue-50 border border-blue-100 flex items-center justify-center mb-3",children:e.jsx(ut,{className:"text-blue-500",size:20})}),e.jsx("h4",{className:"text-sm font-bold text-[var(--fg-primary)] mb-1",children:t("globalChat.emptyTitle")}),e.jsx("p",{className:"text-xs text-[var(--fg-muted)] max-w-[280px] leading-relaxed mb-3",children:t("globalChat.emptyDesc")}),e.jsx("div",{className:"flex flex-wrap gap-1.5 justify-center",children:[t("globalChat.quickPrompts.analyzeArch"),t("globalChat.quickPrompts.findDuplicates"),t("globalChat.quickPrompts.suggestOptimize")].map(B=>e.jsx("button",{onClick:()=>{N(B),G.current?.focus()},className:"text-[10px] px-2.5 py-1 rounded-md bg-[var(--bg-subtle)] text-[var(--fg-secondary)] hover:bg-blue-50 hover:text-blue-700 transition-colors",children:B},B))})]}),S&&r.length<=1&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-2",children:[t("globalChat.refinePrompts.addExamples"),t("globalChat.refinePrompts.optimizeComments"),t("globalChat.refinePrompts.addCaveats"),t("globalChat.refinePrompts.improveSummary"),t("globalChat.refinePrompts.addPerformance")].map(B=>e.jsx("button",{onClick:()=>{N(B),G.current?.focus()},className:"text-[10px] px-2.5 py-1 rounded-md bg-emerald-50 text-emerald-700 border border-emerald-200 hover:bg-emerald-100 transition-colors",children:B},B))}),r.map(B=>e.jsx("div",{className:`flex ${B.role==="user"?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[95%] ${B.role==="user"?"bg-blue-600 text-white rounded-2xl rounded-tr-md px-3.5 py-2":B.role==="system"?"bg-[var(--bg-subtle)] border border-[var(--border-default)] text-[var(--fg-secondary)] rounded-2xl px-3.5 py-2 w-full":"bg-[var(--bg-surface)] border border-[var(--border-default)] rounded-2xl rounded-tl-md px-3.5 py-2.5 shadow-sm w-full"}`,children:[B.role==="assistant"&&e.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[e.jsx(Mt,{size:12,className:S?"text-emerald-500":"text-blue-500"}),e.jsx("span",{className:`text-[10px] font-bold ${S?"text-emerald-600":"text-blue-600"}`,children:t(S?"globalChat.assistantRefine":"globalChat.assistantChat")})]}),B.role==="assistant"&&!B.diff?e.jsx(Qt,{content:B.content,className:"text-xs text-[var(--fg-primary)]"}):e.jsx("p",{className:`text-xs leading-relaxed whitespace-pre-wrap ${B.role==="user"?"":B.role==="system"?"text-[var(--fg-secondary)]":"text-[var(--fg-primary)]"}`,children:B.content}),B.diff&&B.diff.length>0&&e.jsx(Co,{diff:B.diff,excludedFields:B.excludedFields,onToggleField:S&&!h.has(D)?oe=>A(B.id,oe):void 0})]})},B.id)),l&&e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"bg-[var(--bg-surface)] border border-[var(--border-default)] rounded-2xl rounded-tl-md px-3.5 py-2.5 shadow-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{size:12,className:`animate-spin ${S?"text-emerald-500":"text-blue-500"}`}),e.jsx("span",{className:"text-xs text-[var(--fg-secondary)]",children:t(S?"globalChat.loading.analyzing":"globalChat.loading.thinking")}),y.current&&e.jsx("button",{onClick:()=>y.current?.abort(),className:"ml-1 px-1.5 py-0.5 text-[10px] font-bold text-red-500 border border-red-200 rounded hover:bg-red-50 transition-colors",children:t("globalChat.stopBtn")})]})})}),e.jsx("div",{ref:w})]}),S&&q&&!l&&(()=>{const B=[...r].reverse().find(T=>T.role==="assistant"&&T.diff&&T.diff.length>0),oe=B?.diff?.length||0,me=B?.excludedFields?.length||0,R=oe-me;return e.jsxs("div",{className:"px-4 py-2 border-t border-[var(--border-default)] bg-emerald-50/50 flex items-center gap-2 shrink-0",children:[e.jsxs("button",{onClick:re,disabled:p,className:"flex items-center gap-1 px-3 py-1.5 text-[11px] font-bold text-white bg-gradient-to-r from-emerald-500 to-teal-600 hover:from-emerald-600 hover:to-teal-700 rounded-lg shadow-sm disabled:opacity-50",children:[p?e.jsx(Ne,{size:11,className:"animate-spin"}):e.jsx(ot,{size:11}),p?t("globalChat.applyingBtn"):me>0?t("globalChat.confirmApplyN",{i:R,total:oe}):t("globalChat.confirmApply")]}),e.jsxs("button",{className:"flex items-center gap-1 px-2.5 py-1.5 text-[11px] font-bold text-[var(--fg-secondary)] hover:text-[var(--fg-primary)] rounded-lg hover:bg-[var(--bg-subtle)] transition-colors",children:[e.jsx($s,{size:11})," ",t("globalChat.continueAdjust")]}),P&&h.has(D)&&g.currentIdx<g.candidateIds.length-1&&e.jsxs("button",{onClick:he,className:"flex items-center gap-1 px-2.5 py-1.5 text-[11px] font-bold text-blue-600 hover:text-blue-700 rounded-lg hover:bg-blue-50 transition-colors ml-auto",children:[t("globalChat.nextItem")," ",e.jsx(Ke,{size:11})]})]})})(),S&&!q&&!l&&P&&h.has(D)&&g.currentIdx<g.candidateIds.length-1&&e.jsx("div",{className:"px-4 py-2 border-t border-[var(--border-default)] flex items-center justify-center shrink-0",children:e.jsxs("button",{onClick:he,className:"flex items-center gap-1 px-3 py-1.5 text-[11px] font-bold text-blue-600 hover:text-blue-700 rounded-lg bg-blue-50 hover:bg-blue-100 transition-colors",children:[t("globalChat.nextItem")," (",(g?.currentIdx??0)+2,"/",g?.candidateIds.length,") ",e.jsx(Ke,{size:12})]})}),e.jsxs("div",{className:"px-4 py-2.5 border-t border-[var(--border-default)] bg-[var(--bg-surface)] shrink-0",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx("textarea",{ref:G,value:_,onChange:B=>N(B.target.value),onKeyDown:V,placeholder:t(S?"globalChat.refinePlaceholder":"globalChat.chatPlaceholder"),rows:2,className:`flex-1 px-3 py-2 text-sm border border-[var(--border-default)] rounded-xl focus:outline-none focus:ring-2 ${S?"focus:ring-emerald-200 focus:border-emerald-400":"focus:ring-blue-200 focus:border-blue-400"} resize-none placeholder:text-[var(--fg-muted)]`,disabled:l||p}),e.jsx("button",{onClick:W,disabled:!_.trim()||l||p,className:`self-stretch w-9 flex items-center justify-center rounded-xl bg-gradient-to-r ${S?"from-emerald-500 to-teal-600 hover:from-emerald-600 hover:to-teal-700":"from-blue-500 to-indigo-600 hover:from-blue-600 hover:to-indigo-700"} text-white disabled:opacity-40 disabled:cursor-not-allowed transition-all shadow-sm shrink-0`,children:e.jsx(Zs,{size:14})})]}),e.jsx("p",{className:"text-[9px] text-[var(--fg-muted)] mt-1",children:t(S?"globalChat.inputHintRefine":"globalChat.inputHintChat")})]})]})},Do=er("inline-flex items-center justify-center gap-2 whitespace-nowrap font-medium transition-all cursor-pointer select-none disabled:pointer-events-none disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)]/40 focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--bg-root)] active:scale-[0.97]",{variants:{variant:{primary:"bg-[var(--bg-emphasis)] text-[var(--fg-on-emphasis)] hover:opacity-90 shadow-[var(--shadow-sm)]",secondary:"bg-[var(--bg-surface)] text-[var(--fg-default)] border border-[var(--border-default)] hover:bg-[var(--bg-subtle)] hover:border-[var(--border-emphasis)] shadow-[var(--shadow-sm)]",ghost:"bg-transparent text-[var(--fg-muted)] hover:bg-[var(--bg-subtle)] hover:text-[var(--fg-default)]",danger:"bg-[var(--danger)] text-white hover:opacity-90 shadow-[0_0_12px_rgba(239,68,68,0.2)]",accent:"text-white hover:opacity-90 shadow-[0_0_16px_var(--accent-glow)]"},size:{sm:"h-7 px-2.5 text-xs rounded-[var(--radius-md)]",md:"h-9 px-4 text-sm rounded-[var(--radius-md)]",lg:"h-11 px-5 text-base rounded-[var(--radius-lg)]",icon:"h-8 w-8 rounded-[var(--radius-md)]","icon-sm":"h-7 w-7 rounded-[var(--radius-sm)]"}},defaultVariants:{variant:"primary",size:"md"}}),We=n.forwardRef(({className:t,variant:s,size:a,loading:r,disabled:o,children:l,style:i,...p},d)=>{const g=s==="accent"?{background:"var(--accent-gradient)",...i}:i;return e.jsxs("button",{ref:d,className:je(Do({variant:s,size:a,className:t})),disabled:o||r,style:g,...p,children:[r&&e.jsxs("svg",{className:"h-4 w-4 animate-spin",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),l]})});We.displayName="Button";const Or=Tn,Hr=En,Ro=n.forwardRef(({className:t,inset:s,children:a,...r},o)=>e.jsxs(tr,{ref:o,className:je("flex cursor-default select-none items-center rounded-[var(--radius-sm)] px-2 py-1.5 text-sm outline-none","focus:bg-[var(--bg-subtle)] data-[state=open]:bg-[var(--bg-subtle)]",s&&"pl-8",t),...r,children:[a,e.jsx(Ke,{className:"ml-auto h-4 w-4"})]}));Ro.displayName=tr.displayName;const Io=n.forwardRef(({className:t,...s},a)=>e.jsx(sr,{ref:a,className:je("z-50 min-w-[8rem] overflow-hidden rounded-[var(--radius-md)] border border-[var(--border-default)] bg-[var(--bg-surface)] p-1 text-[var(--fg-default)] shadow-[var(--shadow-lg)]","data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95","data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95","data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...s}));Io.displayName=sr.displayName;const oa=n.forwardRef(({className:t,sideOffset:s=4,...a},r)=>e.jsx(In,{children:e.jsx(ar,{ref:r,sideOffset:s,className:je("z-50 min-w-[8rem] overflow-hidden rounded-[var(--radius-lg)] border border-[var(--border-default)] bg-[var(--bg-surface)] p-1 text-[var(--fg-default)] shadow-[var(--shadow-xl)]","dark:bg-[var(--bg-surface)]/95 dark:backdrop-blur-xl dark:border-[var(--glass-border)] dark:shadow-[0_16px_64px_rgba(0,0,0,0.5),0_0_1px_rgba(255,255,255,0.06)]","data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95","data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95","data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2","data-[side=bottom]:origin-top data-[side=top]:origin-bottom data-[side=left]:origin-right data-[side=right]:origin-left","data-[align=end]:data-[side=bottom]:origin-top-right data-[align=end]:data-[side=top]:origin-bottom-right","data-[align=start]:data-[side=bottom]:origin-top-left data-[align=start]:data-[side=top]:origin-bottom-left",t),...a})}));oa.displayName=ar.displayName;const kt=n.forwardRef(({className:t,inset:s,...a},r)=>e.jsx(rr,{ref:r,className:je("relative flex cursor-default select-none items-center gap-2 rounded-[var(--radius-sm)] px-2 py-1.5 text-sm outline-none transition-colors","focus:bg-[var(--bg-subtle)] focus:text-[var(--fg-default)]","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s&&"pl-8",t),...a}));kt.displayName=rr.displayName;const To=n.forwardRef(({className:t,children:s,checked:a,...r},o)=>e.jsxs(nr,{ref:o,className:je("relative flex cursor-default select-none items-center rounded-[var(--radius-sm)] py-1.5 pl-8 pr-2 text-sm outline-none transition-colors","focus:bg-[var(--bg-subtle)] focus:text-[var(--fg-default)]","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:a,...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(lr,{children:e.jsx(ot,{className:"h-4 w-4"})})}),s]}));To.displayName=nr.displayName;const Eo=n.forwardRef(({className:t,children:s,...a},r)=>e.jsxs(or,{ref:r,className:je("relative flex cursor-default select-none items-center rounded-[var(--radius-sm)] py-1.5 pl-8 pr-2 text-sm outline-none transition-colors","focus:bg-[var(--bg-subtle)] focus:text-[var(--fg-default)]","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...a,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(lr,{children:e.jsx(sl,{className:"h-2 w-2 fill-current"})})}),s]}));Eo.displayName=or.displayName;const Kr=n.forwardRef(({className:t,inset:s,...a},r)=>e.jsx(ir,{ref:r,className:je("px-2 py-1.5 text-xs font-medium text-[var(--fg-subtle)]",s&&"pl-8",t),...a}));Kr.displayName=ir.displayName;const vs=n.forwardRef(({className:t,...s},a)=>e.jsx(cr,{ref:a,className:je("-mx-1 my-1 h-px bg-[var(--border-muted)]",t),...s}));vs.displayName=cr.displayName;function Po(t){return t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"k":String(t)}function Mo(t,s){if(t.length<=s)return t;const a=Math.floor((s-1)/2);return t.slice(0,a)+"…"+t.slice(t.length-a)}const Lo={recipes:"sidebar.recipes",spm:"sidebar.moduleExplorer",candidates:"sidebar.candidates",knowledge:"sidebar.batchManage",guard:"sidebar.guard",panorama:"sidebar.panorama",skills:"sidebar.skills",wiki:"sidebar.repoWiki",signals:"sidebar.signals",ai:"sidebar.aiAssistant",help:"sidebar.help"},_o=({setShowCreateModal:t,aiConfig:s,llmReady:a=!0,onOpenLlmConfig:r,onBeforeAiSwitch:o,onAiConfigChange:l,activeTab:i,onOpenCommandPalette:p,projectName:d,candidateCount:g=0,showSignalMonitor:x=!1,onToggleSignalMonitor:h})=>{const{toggle:u,isOpen:m}=Zt(),{t:c}=Ae(),[j,S]=n.useState([]),[D,I]=n.useState(!1),[P,Y]=n.useState(null),w=n.useCallback(()=>{Z.getTokenUsage7Days().then(L=>Y(L.summary)).catch(()=>{})},[]);n.useEffect(()=>{w();const L=Cs(),$=()=>w();return L.on("candidate-created",$),L.on("bootstrap:all-completed",$),L.on("token-usage-updated",$),()=>{L.off("candidate-created",$),L.off("bootstrap:all-completed",$),L.off("token-usage-updated",$)}},[w]);const G=async L=>{const $=s?.provider==="mock"&&L.id!=="mock";if(!(s?.provider!=="mock"&&L.id==="mock"&&!window.confirm(c("header.mockSwitchToConfirm")))){if($&&window.confirm(c("header.mockSwitchFromConfirm")))try{const A=await Z.cleanupMockData();console.log(`Mock cleanup: ${A.deleted} entries deleted`)}catch(A){console.error("Mock cleanup failed",A)}I(!0);try{o?.(),await Z.setAiConfig(L.id,L.defaultModel),l&&l()}catch(q){console.error("AI config update failed",q)}finally{I(!1)}}},_=n.useCallback(()=>{j.length===0&&Z.getAiProviders().then(S).catch(()=>{})},[j.length]);n.useEffect(()=>{_()},[_]);const N=s?j.find(L=>L.id===s.provider)?.hasKey:void 0,E=i?c(Lo[i],{count:g}):"";return e.jsx(Lr,{children:e.jsxs("header",{className:"h-[var(--topbar-height)] flex items-center justify-between px-5 border-b border-[var(--border-muted)] glass shrink-0 gap-3 select-none z-10",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"text-sm text-[var(--fg-subtle)] font-medium truncate max-w-[160px]",title:d||"AutoSnippet",children:d||"AutoSnippet"}),E&&e.jsxs(e.Fragment,{children:[e.jsx(Ke,{size:14,className:"text-[var(--fg-subtle)]/50 shrink-0"}),e.jsx("span",{className:"text-sm text-[var(--fg-default)] font-semibold truncate",children:E})]})]}),e.jsxs("button",{onClick:p,className:je("flex items-center gap-2 h-8 px-3 rounded-[var(--radius-full)] border border-[var(--border-default)] bg-[var(--bg-subtle)]/60","text-sm text-[var(--fg-subtle)] hover:border-[var(--accent)]/40 hover:text-[var(--fg-muted)] hover:shadow-[0_0_12px_var(--accent-glow)] transition-all","w-64 justify-between backdrop-blur-sm"),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xt,{size:14}),e.jsx("span",{children:c("header.searchPlaceholder")})]}),e.jsx("kbd",{className:"hidden sm:inline-flex items-center gap-0.5 rounded-[var(--radius-sm)] border border-[var(--border-default)] bg-[var(--bg-root)]/60 px-1.5 py-0.5 text-[10px] font-mono text-[var(--fg-subtle)]",children:"⌘K"})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[!a&&e.jsxs(We,{variant:"ghost",size:"sm",onClick:r,className:"text-[var(--warning)] animate-pulse",children:[e.jsx(Vt,{size:14}),e.jsx("span",{className:"text-xs",children:c("header.configureLlm")})]}),a&&s&&e.jsxs(Or,{onOpenChange:L=>L&&_(),children:[e.jsx(Hr,{asChild:!0,children:e.jsxs(We,{variant:"ghost",size:"sm",className:"gap-1.5 focus-visible:ring-0 focus-visible:ring-offset-0",children:[e.jsxs("span",{className:"relative shrink-0",children:[s.provider==="mock"?e.jsx(al,{size:14,className:"text-amber-500"}):e.jsx(Jt,{size:14}),e.jsx("span",{className:je("absolute -top-0.5 -right-0.5 w-[6px] h-[6px] rounded-full ring-1 ring-[var(--bg-root)]",s.provider==="mock"?"bg-amber-500":N===!1?"bg-red-400":"bg-emerald-500")})]}),e.jsx("span",{className:"text-xs",title:`${s.provider}/${s.model}`,children:Mo(s.model,28)}),s.provider==="mock"&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-amber-500/15 text-amber-500 font-medium shrink-0",children:"Mock"}),P&&P.total_tokens>0&&e.jsxs("span",{className:"flex items-center gap-0.5 ml-0.5 text-[10px] text-[var(--fg-subtle)] tabular-nums shrink-0",children:[e.jsx(Be,{size:9,className:"text-amber-500/70"}),Po(P.total_tokens)]}),e.jsx(gt,{size:12,className:"shrink-0"})]})}),e.jsxs(oa,{align:"end",className:"w-56",children:[e.jsx(Kr,{children:c("header.switchAi")}),s.provider==="mock"&&e.jsxs("div",{className:"px-2 py-1.5 text-[11px] text-amber-500/80 bg-amber-500/5 rounded mx-1 mb-1",children:["🧪 ",c("header.mockModeHint")]}),e.jsx(vs,{}),j.length===0?e.jsx(kt,{disabled:!0,children:c("common.loading")}):j.map(L=>e.jsxs(kt,{onClick:()=>G(L),disabled:D,className:je(s.provider===L.id&&"bg-[var(--accent-subtle)] text-[var(--accent)] font-medium",L.hasKey===!1&&"opacity-50"),children:[e.jsxs("span",{className:"flex items-center gap-2 flex-1",children:[e.jsx("span",{className:je("inline-block w-1.5 h-1.5 rounded-full shrink-0",L.hasKey!==!1?"bg-emerald-500":"bg-[var(--fg-subtle)]")}),L.label]}),s.provider===L.id&&e.jsx("span",{className:"text-xs",children:"✓"})]},L.id)),e.jsx(vs,{}),e.jsxs(kt,{onClick:r,children:[e.jsx(Vt,{size:14}),e.jsx("span",{children:c("header.editEnvConfig")})]})]})]}),e.jsxs(wt,{children:[e.jsx(Nt,{asChild:!0,children:e.jsx(We,{variant:"ghost",size:"icon-sm",onClick:()=>t(!0),children:e.jsx(mt,{size:16})})}),e.jsx(ft,{children:c("header.newRecipe")})]}),h&&e.jsxs(wt,{children:[e.jsx(Nt,{asChild:!0,children:e.jsx(We,{variant:x?"accent":"ghost",size:"icon-sm",onClick:h,children:e.jsx(Yt,{size:16})})}),e.jsx(ft,{children:c(x?"signals.closeMonitor":"signals.openMonitor")})]}),e.jsxs(wt,{children:[e.jsx(Nt,{asChild:!0,children:e.jsx(We,{variant:m?"accent":"ghost",size:"icon-sm",onClick:u,children:e.jsx(ut,{size:16})})}),e.jsx(ft,{children:c(m?"header.closeAiChat":"header.openAiChat")})]}),"        "]})]})})},Fo=Ln,zo=Pn,qr=n.forwardRef(({className:t,...s},a)=>e.jsx(dr,{ref:a,className:je("fixed inset-0 z-50 bg-black/40 backdrop-blur-md","data-[state=open]:animate-in data-[state=open]:fade-in-0","data-[state=closed]:animate-out data-[state=closed]:fade-out-0",t),...s}));qr.displayName=dr.displayName;const Ur=n.forwardRef(({className:t,children:s,size:a="md",hideClose:r=!1,...o},l)=>e.jsxs(zo,{children:[e.jsx(qr,{}),e.jsxs(ur,{ref:l,className:je("fixed left-1/2 top-1/2 z-50 -translate-x-1/2 -translate-y-1/2","w-full rounded-[var(--radius-xl)] border border-[var(--border-default)] bg-[var(--bg-surface)] shadow-[var(--shadow-xl)]","dark:bg-[var(--bg-surface)]/95 dark:backdrop-blur-xl dark:border-[var(--glass-border)]","dark:shadow-[0_24px_80px_rgba(0,0,0,0.6),0_0_1px_rgba(255,255,255,0.08)]","data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%]","data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%]","duration-200",{"max-w-md":a==="sm","max-w-lg":a==="md","max-w-3xl":a==="lg","max-w-5xl":a==="xl","max-w-[calc(100vw-4rem)] max-h-[calc(100vh-4rem)]":a==="full"},t),...o,children:[s,!r&&e.jsxs(Mn,{className:"absolute right-4 top-4 rounded-[var(--radius-sm)] p-1 text-[var(--fg-subtle)] opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-[var(--accent)] focus:ring-offset-2",children:[e.jsx(ze,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Ur.displayName=ur.displayName;const Bo=n.forwardRef(({className:t,...s},a)=>e.jsx(mr,{ref:a,className:je("text-lg font-semibold text-[var(--fg-default)]",t),...s}));Bo.displayName=mr.displayName;const Go=n.forwardRef(({className:t,...s},a)=>e.jsx(pr,{ref:a,className:je("text-sm text-[var(--fg-muted)]",t),...s}));Go.displayName=pr.displayName;const Wr=n.forwardRef(({className:t,...s},a)=>e.jsx(Je,{ref:a,className:je("flex h-full w-full flex-col overflow-hidden rounded-[var(--radius-xl)] text-[var(--fg-default)]",t),...s}));Wr.displayName=Je.displayName;const Vr=n.forwardRef(({className:t,...s},a)=>e.jsxs("div",{className:"flex items-center border-b border-[var(--border-muted)] px-3",children:[e.jsx(xt,{className:"mr-2 h-4 w-4 shrink-0 text-[var(--fg-subtle)]"}),e.jsx(Je.Input,{ref:a,className:je("flex h-12 w-full bg-transparent py-3 text-sm text-[var(--fg-default)] outline-none placeholder:text-[var(--fg-subtle)]","disabled:cursor-not-allowed disabled:opacity-50",t),...s})]}));Vr.displayName=Je.Input.displayName;const Jr=n.forwardRef(({className:t,...s},a)=>e.jsx(Je.List,{ref:a,className:je("max-h-[300px] overflow-y-auto overflow-x-hidden p-1",t),...s}));Jr.displayName=Je.List.displayName;const Yr=n.forwardRef((t,s)=>e.jsx(Je.Empty,{ref:s,className:"py-6 text-center text-sm text-[var(--fg-subtle)]",...t}));Yr.displayName=Je.Empty.displayName;const xs=n.forwardRef(({className:t,...s},a)=>e.jsx(Je.Group,{ref:a,className:je("overflow-hidden p-1 text-[var(--fg-default)]","[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-[var(--fg-subtle)]",t),...s}));xs.displayName=Je.Group.displayName;const Ws=n.forwardRef(({className:t,...s},a)=>e.jsx(Je.Separator,{ref:a,className:je("-mx-1 h-px bg-[var(--border-muted)]",t),...s}));Ws.displayName=Je.Separator.displayName;const Rt=n.forwardRef(({className:t,...s},a)=>e.jsx(Je.Item,{ref:a,className:je("relative flex cursor-default gap-2 select-none items-center rounded-[var(--radius-md)] px-2.5 py-2 text-sm outline-none transition-colors","data-[selected=true]:bg-[var(--accent-subtle)] data-[selected=true]:text-[var(--accent)]","data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50",t),...s}));Rt.displayName=Je.Item.displayName;function Ra({className:t,...s}){return e.jsx("span",{className:je("ml-auto text-xs tracking-widest text-[var(--fg-subtle)]",t),...s})}const $o={recipes:rl,spm:Lt,candidates:Ye,knowledge:Qs,guard:Ve,panorama:Ge,skills:Ue,wiki:Qe,signals:Yt,ai:ut,help:vr},Ms={recipes:"sidebar.recipes",spm:"sidebar.moduleExplorer",candidates:"sidebar.candidates",knowledge:"sidebar.batchManage",guard:"sidebar.guard",panorama:"sidebar.panorama",skills:"sidebar.skills",wiki:"sidebar.repoWiki",signals:"sidebar.signals",ai:"sidebar.aiAssistant",help:"sidebar.help"},Oo=({open:t,onOpenChange:s,navigateToTab:a,setShowCreateModal:r,onSemanticSearch:o,searchQuery:l,setSearchQuery:i,onOpenLlmConfig:p,candidateCount:d=0})=>{const{t:g}=Ae(),[x,h]=n.useState([]);n.useEffect(()=>{t&&x.length===0&&Z.fetchData().then(c=>{const j=c?.recipes||[];h(j.slice(0,5).map(S=>({name:S.name||S.title,title:S.title||S.name})))}).catch(()=>{})},[t]),n.useEffect(()=>{const c=j=>{(j.metaKey||j.ctrlKey)&&j.key==="k"&&(j.preventDefault(),s(!t))};return document.addEventListener("keydown",c),()=>document.removeEventListener("keydown",c)},[t,s]);const u=n.useCallback(c=>{c(),s(!1)},[s]),m=Object.keys(Ms);return e.jsx(Fo,{open:t,onOpenChange:s,children:e.jsx(Ur,{size:"md",hideClose:!0,className:"!p-0 !top-[15vh] !translate-y-0 overflow-hidden",style:{backgroundColor:"var(--bg-root)"},children:e.jsxs(Wr,{className:"[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-[var(--fg-subtle)] [&_[cmdk-item]]:px-3 [&_[cmdk-item]]:py-2.5",children:[e.jsx(Vr,{placeholder:g("commandPalette.searchPlaceholder")||"搜索知识、命令、页面...",value:l,onValueChange:i}),e.jsxs(Jr,{className:"max-h-[360px]",children:[e.jsx(Yr,{children:g("commandPalette.noResults")||"没有找到结果"}),x.length>0&&e.jsx(xs,{heading:g("commandPalette.recent")||"最近",children:x.map(c=>e.jsxs(Rt,{value:c.title,onSelect:()=>u(()=>{a("recipes"),i(c.title)}),children:[e.jsx(Qe,{className:"mr-2 h-4 w-4 text-[var(--fg-subtle)]"}),e.jsx("span",{children:c.title})]},c.name))}),e.jsx(Ws,{}),e.jsx(xs,{heading:g("commandPalette.pages")||"页面",children:m.map(c=>{const j=$o[c],S=c==="candidates"?{count:d}:void 0;return e.jsxs(Rt,{value:g(Ms[c],S),onSelect:()=>u(()=>a(c)),children:[e.jsx(j,{className:"mr-2 h-4 w-4 text-[var(--fg-subtle)]"}),e.jsx("span",{children:g(Ms[c],S)})]},c)})}),e.jsx(Ws,{}),e.jsxs(xs,{heading:g("commandPalette.commands")||"命令",children:[e.jsxs(Rt,{value:"new recipe",onSelect:()=>u(()=>r(!0)),children:[e.jsx(mt,{className:"mr-2 h-4 w-4 text-[var(--fg-subtle)]"}),e.jsx("span",{children:g("header.newRecipe")}),e.jsx(Ra,{children:"⌘N"})]}),o&&e.jsxs(Rt,{value:"semantic search",onSelect:()=>u(()=>o(l)),children:[e.jsx(nl,{className:"mr-2 h-4 w-4 text-[var(--fg-subtle)]"}),e.jsx("span",{children:g("header.semanticSearch")}),e.jsx(Ra,{children:"⌘⇧F"})]}),p&&e.jsxs(Rt,{value:"llm config",onSelect:()=>u(()=>p()),children:[e.jsx(Vt,{className:"mr-2 h-4 w-4 text-[var(--fg-subtle)]"}),e.jsx("span",{children:g("header.configureLlm")})]})]})]})]})})})},Qr="asd-drawer-wide";function Ho(){try{return localStorage.getItem(Qr)==="1"}catch{return!1}}function ia(){const[t,s]=n.useState(Ho),a=n.useCallback(()=>{s(r=>{const o=!r;try{localStorage.setItem(Qr,o?"1":"0")}catch{}return o})},[]);return{isWide:t,toggle:a}}const Ko={xs:"h-6 text-[10px] px-1.5 gap-1 rounded",sm:"h-7 text-[11px] px-2 gap-1.5 rounded-md",md:"h-9 text-sm px-3 gap-2 rounded-lg"},qo={xs:"text-[10px] px-1.5 py-1",sm:"text-[11px] px-2 py-1.5",md:"text-sm px-3 py-2"},tt=({value:t,onChange:s,options:a,className:r,contentClassName:o,placeholder:l="—",disabled:i=!1,size:p="sm",minWidth:d,direction:g="auto",id:x,name:h})=>{const[u,m]=n.useState(!1),[c,j]=n.useState(-1),[S,D]=n.useState(!1),I=n.useRef(null),P=n.useRef(null),Y=a.find(E=>E.value===t),w=n.useCallback(()=>{if(g==="up")return!0;if(g==="down"||!I.current)return!1;const E=I.current.getBoundingClientRect(),L=window.innerHeight-E.bottom,$=Math.min(a.length*28+8,248);return L<$&&E.top>$},[g,a.length]),G=n.useCallback(()=>{D(w()),m(!0),j(a.findIndex(E=>E.value===t))},[w,a,t]);n.useEffect(()=>{if(!u)return;const E=L=>{I.current?.contains(L.target)||P.current?.contains(L.target)||m(!1)};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[u]);const _=n.useCallback(E=>{if(i)return;const L=a.filter($=>!$.disabled);E.key==="Enter"||E.key===" "?(E.preventDefault(),u?c>=0&&c<L.length&&(s(L[c].value),m(!1)):G()):E.key==="Escape"?m(!1):E.key==="ArrowDown"?(E.preventDefault(),u?j($=>Math.min($+1,L.length-1)):G()):E.key==="ArrowUp"&&(E.preventDefault(),j($=>Math.max($-1,0)))},[i,u,c,a,t,s,G]);n.useEffect(()=>{if(!u||c<0||!P.current)return;P.current.querySelectorAll("[data-select-item]")[c]?.scrollIntoView({block:"nearest"})},[c,u]);const N=E=>{s(E),m(!1),I.current?.focus()};return e.jsxs("div",{className:"relative inline-block",style:d?{minWidth:d}:void 0,children:[h&&e.jsx("input",{type:"hidden",name:h,value:t}),e.jsxs("button",{ref:I,id:x,type:"button",role:"combobox","aria-expanded":u,"aria-haspopup":"listbox",disabled:i,onClick:()=>{i||(u?m(!1):G())},onKeyDown:_,className:je("inline-flex items-center justify-between border border-[var(--border-default)] bg-[var(--bg-surface)] text-[var(--fg-default)] font-medium transition-colors","hover:border-[var(--border-emphasis)] hover:bg-[var(--bg-subtle)]","disabled:opacity-50 disabled:pointer-events-none",Ko[p],r),children:[e.jsx("span",{className:"truncate",children:Y?e.jsxs(e.Fragment,{children:[Y.icon&&e.jsx("span",{className:"mr-1",children:Y.icon}),Y.label]}):l}),e.jsx(gt,{size:p==="xs"?10:p==="sm"?12:14,className:je("shrink-0 text-[var(--fg-muted)] transition-transform",u&&"rotate-180")})]}),u&&e.jsx("div",{ref:P,role:"listbox",className:je("absolute z-50 min-w-full max-h-60 overflow-y-auto","rounded-[var(--radius-md)] border border-[var(--border-default)] bg-[var(--bg-surface)] shadow-[var(--shadow-lg)] p-0.5",S?"bottom-full mb-1 animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-1":"top-full mt-1 animate-in fade-in-0 zoom-in-95 slide-in-from-top-1",o),children:a.map((E,L)=>{const $=E.value===t,U=L===c;return e.jsxs("div",{"data-select-item":!0,role:"option","aria-selected":$,onClick:()=>!E.disabled&&N(E.value),onMouseEnter:()=>!E.disabled&&j(L),className:je("flex items-center justify-between cursor-pointer rounded-[var(--radius-sm)] transition-colors",qo[p],E.disabled&&"opacity-40 pointer-events-none",U&&"bg-[var(--bg-subtle)]",$&&"text-[var(--accent)] font-semibold"),children:[e.jsxs("span",{className:"flex items-center gap-1.5 truncate",children:[E.icon&&e.jsx("span",{children:E.icon}),E.label]}),$&&e.jsx(ot,{size:p==="xs"?10:12,className:"shrink-0 text-[var(--accent)]"})]},E.value)})})]})},ca=({currentPage:t,totalPages:s,totalItems:a,pageSize:r,onPageChange:o,onPageSizeChange:l,pageSizeOptions:i=[12,24,48,96]})=>{if(s<=1&&a<=i[0])return null;const{t:p}=Ae(),d=(t-1)*r+1,g=Math.min(t*r,a),x=()=>{const h=[];if(s<=7)for(let m=1;m<=s;m++)h.push(m);else if(t<=3){for(let m=1;m<=5;m++)h.push(m);h.push("..."),h.push(s)}else if(t>=s-2){h.push(1),h.push("...");for(let m=s-5+1;m<=s;m++)h.push(m)}else{h.push(1),h.push("...");for(let m=t-1;m<=t+1;m++)h.push(m);h.push("..."),h.push(s)}return h};return e.jsxs("div",{className:"flex items-center justify-between mt-6 px-2",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("span",{className:"text-sm text-[var(--fg-secondary)]",children:p("pagination.showing",{start:d,end:g,total:a})}),l&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-[var(--fg-secondary)]",children:p("pagination.perPage")}),e.jsx(tt,{value:String(r),onChange:h=>l(Number(h)),options:i.map(h=>({value:String(h),label:String(h)})),size:"sm"}),e.jsx("span",{className:"text-sm text-[var(--fg-secondary)]",children:p("pagination.unit")})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>o(1),disabled:t===1,className:"p-1.5 rounded-md hover:bg-[var(--bg-subtle)] disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:p("pagination.firstPage"),children:e.jsx(ll,{size:H.md,className:"text-[var(--fg-secondary)]"})}),e.jsx("button",{onClick:()=>o(t-1),disabled:t===1,className:"p-1.5 rounded-md hover:bg-[var(--bg-subtle)] disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:p("pagination.prevPage"),children:e.jsx(Xs,{size:H.md,className:"text-[var(--fg-secondary)]"})}),e.jsx("div",{className:"flex items-center gap-1 mx-2",children:x().map((h,u)=>typeof h=="number"?e.jsx("button",{onClick:()=>o(h),className:`min-w-[32px] h-8 px-2 rounded-md text-sm font-medium transition-colors ${t===h?"bg-blue-600 text-white":"hover:bg-[var(--bg-subtle)] text-[var(--fg-secondary)]"}`,children:h},u):e.jsx("span",{className:"px-1 text-[var(--fg-muted)]",children:h},u))}),e.jsx("button",{onClick:()=>o(t+1),disabled:t===s,className:"p-1.5 rounded-md hover:bg-[var(--bg-subtle)] disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:p("pagination.nextPage"),children:e.jsx(Ke,{size:H.md,className:"text-[var(--fg-secondary)]"})}),e.jsx("button",{onClick:()=>o(s),disabled:t===s,className:"p-1.5 rounded-md hover:bg-[var(--bg-subtle)] disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:p("pagination.lastPage"),children:e.jsx(ol,{size:H.md,className:"text-[var(--fg-secondary)]"})})]})]})},Uo=it.memo(({code:t,lang:s,editorStyles:a})=>e.jsx(Qa,{language:s,style:Za,showLineNumbers:!1,customStyle:{margin:0,padding:a.padding,fontSize:a.fontSize,lineHeight:a.lineHeight,borderRadius:"0",whiteSpace:"pre",verticalAlign:"top",display:"inline-block",minWidth:"100%",minHeight:"100%",backgroundColor:"#282c34"},codeTagProps:{style:{fontFamily:a.fontFamily,whiteSpace:"pre",verticalAlign:"top",fontSize:a.fontSize,lineHeight:a.lineHeight}},PreTag:"div",children:(()=>{const r=t;return r[r.length-1]===`
`?r+" ":r})()})),as=19.5,Wo=it.memo(({totalLines:t,scrollTop:s,viewportHeight:a,fontSize:r,lineHeight:o,fontFamily:l})=>{const p=Math.max(0,Math.floor(s/as)-10),d=Math.ceil(a/as)+20,g=Math.min(t,p+d),x=p*as,h=Math.max(0,(t-g)*as),u=[];for(let m=p;m<g;m++)u.push(e.jsx("div",{children:m+1},m));return e.jsx("div",{style:{paddingTop:x,paddingBottom:h,fontSize:r,lineHeight:o,fontFamily:l},children:u})}),ys=({value:t,onChange:s,onCursorChange:a,language:r="javascript",height:o="400px",className:l="",placeholder:i="",rows:p,showLineNumbers:d=!0})=>{const g=n.useRef(null),x=n.useRef(null),h=n.useRef(null),u=n.useRef(null),[m,c]=n.useState(t),j=n.useRef(void 0);n.useEffect(()=>{const E=t.length>5e3?200:t.length>1e3?80:0;if(E===0){c(t);return}return j.current=setTimeout(()=>c(t),E),()=>clearTimeout(j.current)},[t]);const[S,D]=n.useState({top:0,height:400}),P={objectivec:"objectivec","objective-c":"objectivec","obj-c":"objectivec",objc:"objectivec",swift:"swift",javascript:"javascript",js:"javascript",typescript:"typescript",ts:"typescript",python:"python",py:"python",bash:"bash",shell:"bash",markdown:"markdown",md:"markdown",json:"json",text:"text"}[r?.toLowerCase()]||r?.toLowerCase()||"text",Y=n.useMemo(()=>({padding:"1rem 1.25rem",fontSize:"0.8125rem",lineHeight:1.5,fontFamily:"ui-monospace, monospace",minHeight:"200px"}),[]),w=n.useCallback(E=>{const L=E.currentTarget;h.current&&(h.current.scrollTop=L.scrollTop,h.current.scrollLeft=L.scrollLeft),u.current&&(u.current.scrollTop=L.scrollTop),D({top:L.scrollTop,height:L.clientHeight})},[]),G=n.useCallback(E=>{s(E.target.value),a&&a(E.target.selectionStart||0)},[s,a]),_=n.useCallback(E=>{a&&a(E.currentTarget.selectionStart||0)},[a]),N=n.useMemo(()=>(t||"").split(`
`).length,[t]);return n.useEffect(()=>{x.current&&D(E=>({...E,height:x.current.clientHeight}))},[]),e.jsxs("div",{ref:g,className:`relative overflow-hidden ${l}`,style:{height:p?"auto":o,minHeight:Y.minHeight,display:"flex",borderRadius:"0",backgroundColor:"#282c34"},children:[d&&e.jsx("div",{ref:u,className:"flex-shrink-0 overflow-hidden pointer-events-none select-none",style:{width:"3.5em",backgroundColor:"#282c34",color:"#5c6370",textAlign:"right",paddingTop:"1rem",paddingRight:"0.75em",paddingBottom:"1rem",borderRadius:"0",borderRight:"1px solid #333842"},children:e.jsx(Wo,{totalLines:N,scrollTop:S.top,viewportHeight:S.height,fontSize:Y.fontSize,lineHeight:Y.lineHeight,fontFamily:Y.fontFamily})}),e.jsxs("div",{className:"relative flex-1",style:{borderRadius:"0",backgroundColor:"#282c34"},children:[e.jsx("div",{ref:h,className:"absolute inset-0 pointer-events-none highlight-scroll-hidden",style:{zIndex:0,overflow:"scroll"},children:e.jsx(Uo,{code:m||i,lang:P,editorStyles:Y})}),e.jsx("textarea",{ref:x,value:t,onChange:G,onSelect:_,onKeyUp:_,onClick:_,onScroll:w,rows:p,placeholder:i,className:"absolute inset-0 w-full h-full resize-none outline-none editor-with-dark-scrollbar",style:{padding:Y.padding,lineHeight:Y.lineHeight,fontSize:Y.fontSize,fontFamily:Y.fontFamily,caretColor:"#61afef",backgroundColor:"transparent",color:"transparent",WebkitTextFillColor:"transparent",zIndex:10,border:"none",margin:0,overflow:"auto",overflowX:"hidden",WebkitAppearance:"none",appearance:"none",boxSizing:"border-box",whiteSpace:"pre"}})]})]})},da=({badges:t,metadata:s,tags:a,maxTags:r,id:o,sourceFile:l,sourceFileLabel:i="源文件"})=>{const p=r&&a?a.slice(0,r):a;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)] space-y-3",children:[t.length>0&&e.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:t.map((d,g)=>{const x=d.icon;return e.jsxs("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border inline-flex items-center gap-1 ${d.className}`,children:[x&&e.jsx(x,{size:10}),d.label]},g)})}),(s.length>0||o||l)&&e.jsxs("div",{className:"flex flex-wrap gap-x-5 gap-y-2 text-xs",children:[s.map((d,g)=>{const x=d.icon;return e.jsxs("div",{className:`flex items-center gap-1.5${d.fullWidth?" basis-full mt-0.5":""}`,children:[e.jsx(x,{size:11,className:`${d.iconClass} shrink-0`}),e.jsx("span",{className:"text-[var(--fg-muted)]",children:d.label}),d.isCode?e.jsx("code",{className:"font-mono text-[11px] text-[var(--fg-secondary)] break-all",children:d.value}):e.jsx("span",{className:`font-medium text-[var(--fg-secondary)]${d.mono?" font-mono text-[11px]":""}`,children:d.value})]},g)}),o&&e.jsxs("div",{className:"flex items-center gap-1.5 basis-full mt-0.5",children:[e.jsx(Ys,{size:11,className:"text-[var(--fg-muted)] shrink-0"}),e.jsx("span",{className:"text-[var(--fg-muted)]",children:"ID"}),e.jsx("code",{className:"font-mono text-[11px] text-[var(--fg-secondary)] break-all",children:o})]}),l&&e.jsxs("div",{className:"flex items-center gap-1.5 basis-full",children:[e.jsx(Lt,{size:11,className:"text-[var(--fg-muted)] shrink-0"}),e.jsx("span",{className:"text-[var(--fg-muted)]",children:i}),e.jsx("code",{className:"font-mono text-[11px] text-[var(--fg-secondary)] break-all",title:l,children:l})]})]})]}),p&&p.length>0&&e.jsxs("div",{className:"px-6 py-3 border-b border-[var(--border-default)] flex flex-wrap items-center gap-1.5",children:[e.jsx(wr,{size:11,className:"text-[var(--fg-muted)] mr-0.5"}),p.map((d,g)=>e.jsx("span",{className:"text-[9px] px-2 py-0.5 rounded bg-[var(--accent-subtle)] text-[var(--accent)] border border-[var(--border-default)] font-medium",children:typeof d=="string"?d:String(d)},g))]})]})},Vo=({label:t,text:s})=>s?e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-1.5 block",children:t}),e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] leading-relaxed",children:s})]}):null,Jo=({reasoning:t,labels:s,filterSubmitted:a=!1})=>{if(!t)return null;const r=t,o=r.whyStandard&&(!a||!/^Submitted via /i.test(r.whyStandard));return o||r.sources&&r.sources.length>0||r.confidence!=null&&r.confidence>0?e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(St,{size:11,className:"text-amber-400"})," ",s.section]}),e.jsxs("div",{className:"bg-amber-50/30 border border-amber-100 rounded-xl p-4 space-y-2.5",children:[o&&e.jsx("p",{className:"text-sm text-[var(--fg-primary)] leading-relaxed",children:r.whyStandard}),r.sources&&r.sources.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] font-bold",children:s.source}),r.sources.map((i,p)=>e.jsx("code",{className:"text-[10px] px-2 py-0.5 bg-[var(--bg-surface)] border border-amber-200 rounded text-amber-700 font-mono",children:i},p))]}),r.confidence!=null&&r.confidence>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] font-bold",children:s.confidence}),e.jsx("div",{className:"flex-1 max-w-[160px] h-1.5 bg-[var(--border-default)] rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-amber-400 rounded-full",style:{width:`${Math.round((r.confidence??0)*100)}%`}})}),e.jsxs("span",{className:"text-[10px] font-bold text-amber-600",children:[Math.round((r.confidence??0)*100),"%"]})]}),r.alternatives&&r.alternatives.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 pt-1",children:[e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] font-bold",children:s.alternatives}),r.alternatives.map((i,p)=>e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded text-[var(--fg-secondary)]",children:i},p))]})]})]}):null},Yo=({quality:t,labels:s})=>{if(!t?.grade||t.grade==="F")return null;const a=r=>r.toFixed(2);return e.jsxs("div",{className:"px-6 py-3 border-b border-[var(--border-default)]",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:s.section}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("span",{className:`text-2xl font-black ${t.grade==="A"?"text-emerald-600":t.grade==="B"?"text-blue-600":t.grade==="C"?"text-amber-600":t.grade==="D"?"text-orange-600":"text-[var(--fg-muted)]"}`,children:t.grade}),e.jsxs("div",{className:"flex-1 grid grid-cols-3 gap-2 text-xs",children:[t.completeness!=null&&t.completeness>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-sm font-bold text-[var(--fg-primary)]",children:a(t.completeness)}),e.jsx("div",{className:"text-[var(--fg-muted)]",children:s.completeness})]}),t.adaptation!=null&&t.adaptation>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-sm font-bold text-[var(--fg-primary)]",children:a(t.adaptation)}),e.jsx("div",{className:"text-[var(--fg-muted)]",children:s.adaptation})]}),t.documentation!=null&&t.documentation>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-sm font-bold text-[var(--fg-primary)]",children:a(t.documentation)}),e.jsx("div",{className:"text-[var(--fg-muted)]",children:s.documentation})]})]})]})]})},Qo=({label:t,content:s})=>s?e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(Qe,{size:11,className:"text-blue-400"})," ",t]}),e.jsx("div",{className:"bg-blue-50/30 border border-blue-100 rounded-xl p-4",children:e.jsx("div",{className:"markdown-body text-sm text-[var(--fg-primary)] leading-relaxed",children:e.jsx(Qt,{content:s})})})]}):null,Zo=({label:t,code:s,language:a})=>{if(!s)return null;const r=a==="objc"||a==="objective-c"?"objectivec":a||"text";return e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(pt,{size:11,className:"text-emerald-500"})," ",t]}),e.jsx(vt,{code:s,language:r,showLineNumbers:!0})]})},Xo=({label:t,headers:s})=>!s||s.length===0?null:e.jsxs("div",{className:"px-6 py-3 border-b border-[var(--border-default)]",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:t}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map((a,r)=>e.jsx("code",{className:"px-2.5 py-1 bg-violet-50 text-violet-700 border border-violet-100 rounded-md text-[10px] font-mono font-medium",children:a},r))})]}),ei=({label:t,text:s})=>s?e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:t}),e.jsx("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-xl p-4",children:e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] leading-relaxed",children:s})})]}):null,ti=({label:t,steps:s})=>!s||s.length===0?null:e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:t}),e.jsx("div",{className:"space-y-2",children:s.map((a,r)=>{if(typeof a=="string")return e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-lg p-3 border border-[var(--border-default)] flex items-start gap-2.5",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0 mt-0.5",children:r+1}),e.jsx("p",{className:"text-xs text-[var(--fg-primary)] leading-relaxed",children:a})]},r);const o=typeof a.title=="string"?a.title:"",l=typeof a.description=="string"?a.description:"",i=typeof a.code=="string"?a.code:"";return e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-lg p-3 border border-[var(--border-default)]",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0",children:r+1}),o&&e.jsx("span",{className:"text-xs font-bold text-[var(--fg-primary)]",children:o})]}),l&&e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] ml-7 leading-relaxed",children:l}),i&&e.jsx("pre",{className:"text-[11px] font-mono bg-slate-800 text-green-300 p-2.5 rounded-md mt-1.5 ml-7 overflow-x-auto whitespace-pre-wrap",children:i})]},r)})})]}),si=({label:t,constraints:s})=>{if(!s)return null;const a=s,r=(a.guards?.length||0)+(a.boundaries?.length||0)+(a.preconditions?.length||0)+(a.sideEffects?.length||0);return r?e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(Ve,{size:11,className:"text-amber-500"})," ",t," ",e.jsx("span",{className:"text-amber-500 font-mono",children:r})]}),e.jsxs("div",{className:"space-y-1.5 text-xs text-[var(--fg-secondary)]",children:[a.guards?.map((o,l)=>e.jsxs("div",{className:"flex gap-1.5 items-start",children:[e.jsx("span",{className:`text-xs mt-0.5 ${o.severity==="error"?"text-[var(--status-error)]":"text-[var(--status-warning)]"}`,children:"●"}),e.jsx("code",{className:"font-mono text-[10px] bg-[var(--bg-subtle)] px-1.5 py-0.5 rounded",children:o.pattern}),o.message&&e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)]",children:["— ",o.message]})]},l)),a.boundaries?.map((o,l)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("span",{className:"text-[var(--status-warning)]",children:"●"}),o]},l)),a.preconditions?.map((o,l)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("span",{className:"text-[var(--accent)]",children:"◆"}),o]},l)),a.sideEffects?.map((o,l)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("span",{className:"text-pink-400",children:"⚡"}),o]},l))]})]}):null},ai=({delivery:t,language:s})=>{if(!t)return null;const{topicHint:a,whenClause:r,doClause:o,dontClause:l,coreCode:i}=t;if(!o&&!r&&!l&&!a&&!i)return null;const p=s==="objectivec"||s==="objc"||s==="objective-c"?"objectivec":s||"text";return e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(Ge,{size:11,className:"text-indigo-400"})," Cursor Delivery"]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-xl p-4 text-xs space-y-1.5",children:[a&&e.jsxs("div",{children:[e.jsx("span",{className:"text-indigo-400 font-medium",children:"Topic:"}),e.jsx("span",{className:"text-[var(--fg-primary)]",children:a})]}),r&&e.jsxs("div",{children:[e.jsx("span",{className:"text-blue-400 font-medium",children:"When:"}),e.jsx("span",{className:"text-[var(--fg-primary)]",children:r})]}),o&&e.jsxs("div",{children:[e.jsx("span",{className:"text-emerald-400 font-medium",children:"Do:"}),e.jsx("span",{className:"text-[var(--fg-primary)]",children:o})]}),l&&e.jsxs("div",{children:[e.jsx("span",{className:"text-red-400 font-medium",children:"Don't:"}),e.jsx("span",{className:"text-[var(--fg-primary)]",children:l})]}),i&&e.jsxs("div",{children:[e.jsx("span",{className:"text-purple-400 font-medium",children:"Core Code:"}),e.jsx("div",{className:"mt-1",children:e.jsx(vt,{code:i,language:p})})]})]})]})},Ee={Description:Vo,Reasoning:Jo,Quality:Yo,MarkdownSection:Qo,CodePattern:Zo,Headers:Xo,Rationale:ei,Steps:ti,Constraints:si,Delivery:ai},ri=er("inline-flex items-center rounded-[var(--radius-sm)] px-2 py-0.5 text-xs font-medium leading-none whitespace-nowrap transition-all",{variants:{variant:{default:"bg-[var(--bg-subtle)] text-[var(--fg-muted)] border border-[var(--border-default)]",blue:"bg-[var(--accent-subtle)] text-[var(--accent)] border border-[var(--accent)]/15",green:"bg-[var(--success-subtle)] text-[var(--success)] border border-[var(--success)]/15",amber:"bg-[var(--warning-subtle)] text-[var(--warning)] border border-[var(--warning)]/15",red:"bg-[var(--danger-subtle)] text-[var(--danger)] border border-[var(--danger)]/15",info:"bg-[var(--info-subtle)] text-[var(--info)] border border-[var(--info)]/15",outline:"border border-[var(--border-default)] text-[var(--fg-muted)] bg-transparent",gradient:"text-white border-0"}},defaultVariants:{variant:"default"}}),Vs=n.forwardRef(({className:t,variant:s,style:a,...r},o)=>{const l=s==="gradient"?{background:"var(--accent-gradient)",...a}:a;return e.jsx("span",{ref:o,className:je(ri({variant:s,className:t})),style:l,...r})});Vs.displayName="Badge";const ni=420,li=({className:t="bg-black/20 backdrop-blur-[1px]"})=>e.jsx("div",{className:`absolute inset-0 ${t}`}),$e=({children:t,onClick:s,className:a="",style:r})=>{const{isOpen:o}=Zt();return e.jsx("div",{className:`fixed inset-0 overflow-hidden ${a}`,style:{right:o?ni:0,...r},onClick:s,children:t})};$e.Backdrop=li;const oi=n.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,className:je("rounded-[var(--radius-lg)] border border-[var(--border-default)] bg-[var(--bg-surface)]","transition-all duration-250 ease-out","hover:border-[var(--border-emphasis)] hover:shadow-[var(--shadow-lg)] hover:-translate-y-0.5","dark:hover:shadow-[0_8px_32px_rgba(0,0,0,0.4),0_0_1px_rgba(255,255,255,0.06)]",t),...s}));oi.displayName="Card";const ii=n.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,className:je("flex items-center justify-between p-5 pb-0",t),...s}));ii.displayName="CardHeader";const ci=n.forwardRef(({className:t,...s},a)=>e.jsx("h3",{ref:a,className:je("text-sm font-semibold text-[var(--fg-default)] leading-tight tracking-tight",t),...s}));ci.displayName="CardTitle";const di=n.forwardRef(({className:t,...s},a)=>e.jsx("p",{ref:a,className:je("text-sm text-[var(--fg-muted)] leading-relaxed",t),...s}));di.displayName="CardDescription";const ui=n.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,className:je("p-5",t),...s}));ui.displayName="CardContent";const mi=n.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,className:je("flex items-center px-5 pb-5 pt-0",t),...s}));mi.displayName="CardFooter";const pi=n.forwardRef(({className:t,...s},a)=>e.jsx(_n,{ref:a,className:je("border-b border-[var(--border-muted)]",t),...s}));pi.displayName="AccordionItem";const xi=n.forwardRef(({className:t,children:s,...a},r)=>e.jsx(Fn,{className:"flex",children:e.jsxs(xr,{ref:r,className:je("flex flex-1 items-center justify-between py-3 text-sm font-medium text-[var(--fg-default)] transition-all","hover:text-[var(--fg-default)] [&[data-state=open]>svg]:rotate-180",t),...a,children:[s,e.jsx(gt,{className:"h-4 w-4 shrink-0 text-[var(--fg-subtle)] transition-transform duration-200"})]})}));xi.displayName=xr.displayName;const gi=n.forwardRef(({className:t,children:s,...a},r)=>e.jsx(gr,{ref:r,className:"overflow-hidden text-sm data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...a,children:e.jsx("div",{className:je("pb-4 pt-0",t),children:s})}));gi.displayName=gr.displayName;function Xe({className:t,...s}){return e.jsx("div",{className:je("rounded-[var(--radius-md)] animate-shimmer",t),...s})}const Zr={sm:"w-[min(92vw,560px)]",md:"w-[min(92vw,700px)]","md-lg":"w-[min(92vw,800px)]",lg:"w-[min(92vw,960px)]",xl:"w-[min(92vw,1100px)]",full:"w-[min(96vw,1280px)]"};function hi({title:t,leading:s,subtitle:a,className:r,children:o}){return e.jsxs("div",{className:je("flex items-center justify-between px-5 py-3 border-b border-[var(--border-default)] bg-[var(--bg-surface)] shrink-0",r),children:[e.jsxs("div",{className:"flex items-center flex-1 min-w-0 mr-3 gap-2",children:[s,t&&e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-bold text-[var(--fg-primary)] text-lg leading-snug break-words",children:t}),a&&e.jsx("span",{className:"text-xs text-[var(--fg-muted)] mt-0.5 block truncate",children:a})]})]}),o&&e.jsx("div",{className:"flex items-center gap-1 shrink-0",children:o})]})}function bi({currentIndex:t,total:s,onPrev:a,onNext:r,hasPrev:o,hasNext:l}){const i=o!==void 0?!o:t<=0,p=l!==void 0?!l:t>=s-1;return e.jsxs(e.Fragment,{children:[e.jsx(We,{variant:"ghost",size:"icon-sm",onClick:a,disabled:i,children:e.jsx(Xs,{size:16})}),e.jsxs("span",{className:"text-xs text-[var(--fg-muted)] tabular-nums",children:[t+1,"/",s]}),e.jsx(We,{variant:"ghost",size:"icon-sm",onClick:r,disabled:p,children:e.jsx(Ke,{size:16})})]})}function fi({isWide:t,onToggle:s,title:a}){return e.jsx(We,{variant:"ghost",size:"icon-sm",onClick:s,title:a,children:t?e.jsx(il,{size:16}):e.jsx(ea,{size:16})})}function vi({children:t}){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-px h-5 bg-[var(--border-default)] mx-1"}),t]})}function yi({onClose:t}){return e.jsx(We,{variant:"ghost",size:"icon-sm",onClick:t,children:e.jsx(ze,{size:16})})}function ji({className:t,padded:s=!1,children:a}){return e.jsx("div",{className:je("flex-1 overflow-y-auto",s&&"p-5 space-y-5",t),children:a})}function wi({className:t,children:s}){return e.jsx("div",{className:je("shrink-0 border-t border-[var(--border-default)] px-5 py-3 bg-[var(--bg-surface)] flex items-center justify-between",t),children:s})}function Ni({width:t,size:s="md",animationDuration:a="0.25s",className:r,children:o}){return e.jsx("div",{className:je("relative h-full bg-[var(--bg-surface)] dark:bg-[var(--bg-surface)]/95 dark:backdrop-blur-xl shadow-2xl flex flex-col border-l border-[var(--border-default)] dark:border-[var(--glass-border)]",t||Zr[s],r),style:{animation:`slideInRight ${a} ease-out`},onClick:l=>l.stopPropagation(),children:o})}function Ie({open:t,onClose:s,size:a="md",className:r,animationDuration:o="0.25s",children:l}){return t?e.jsxs($e,{className:"z-30 flex justify-end",onClick:s,children:[e.jsx($e.Backdrop,{className:"bg-black/20 dark:bg-black/40 backdrop-blur-sm"}),e.jsx("div",{className:je("relative h-full bg-[var(--bg-surface)] dark:bg-[var(--bg-surface)]/95 dark:backdrop-blur-xl shadow-2xl flex flex-col border-l border-[var(--border-default)] dark:border-[var(--glass-border)] dark:shadow-[0_0_80px_rgba(0,0,0,0.5)]",Zr[a],r),style:{animation:`slideInRight ${o} ease-out`},onClick:i=>i.stopPropagation(),children:l})]}):null}Ie.Header=hi;Ie.Nav=bi;Ie.WidthToggle=fi;Ie.HeaderActions=vi;Ie.CloseButton=yi;Ie.Body=ji;Ie.Footer=wi;Ie.Panel=Ni;const Ls={rule:{label:"Rule",color:"text-red-700",bg:"bg-red-50",border:"border-red-200",icon:Ve},pattern:{label:"Pattern",color:"text-violet-700",bg:"bg-violet-50",border:"border-violet-200",icon:St},fact:{label:"Fact",color:"text-cyan-700",bg:"bg-cyan-50",border:"border-cyan-200",icon:Ue}},rs={"code-pattern":"recipes.knowledgeTypes.codePattern",architecture:"recipes.knowledgeTypes.architecture","best-practice":"recipes.knowledgeTypes.bestPractice","code-standard":"recipes.knowledgeTypes.codeStandard","call-chain":"recipes.knowledgeTypes.callChain",rule:"recipes.knowledgeTypes.rule"};function He(t){return(t.name||t.title||"Untitled").replace(/\.md$/i,"")}function ki(t){return t.content?.pattern||""}function Ci(t){const s=(t.language||"").toLowerCase();return["objectivec","objc","objective-c","obj-c"].includes(s)?"objectivec":t.language||"text"}function Xr(t){if(t==null)return!1;const s=typeof t=="string"?new Date(t).getTime():t;return!isNaN(s)&&s>9466848e5}function Ia(t){return Xr(t)?(typeof t=="string"?new Date(t):new Date(t)).toLocaleDateString("zh-CN",{year:"numeric",month:"2-digit",day:"2-digit"}):""}const Si=({recipes:t,handleDeleteRecipe:s,onRefresh:a,idTitleMap:r,currentPage:o,onPageChange:l,pageSize:i,onPageSizeChange:p})=>{const{t:d}=Ae(),[g,x]=n.useState("newest"),[h,u]=n.useState("desc"),m=[{key:"newest",label:d("recipes.sortNewest"),defaultDir:"desc"},{key:"quality",label:d("recipes.sortQuality"),defaultDir:"desc"},{key:"usage",label:d("recipes.sortUsage"),defaultDir:"desc"},{key:"alpha",label:d("recipes.sortAlpha"),defaultDir:"asc"},{key:"category",label:d("recipes.sortCategory"),defaultDir:"asc"}],[c,j]=n.useState(1),[S,D]=n.useState(12),I=o??c,P=i??S,Y=l??j,w=p?k=>p(k):k=>{D(k),j(1)},{isWide:G,toggle:_}=ia(),[N,E]=n.useState(null),[L,$]=n.useState("view"),[U,q]=n.useState({title:"",description:"",markdown:"",codePattern:"",rationale:"",tags:[],tagInput:""}),[A,y]=n.useState(!1),W=n.useRef(!0),[re,he]=n.useState(!1),[ue,V]=n.useState("related"),[B,oe]=n.useState("");n.useEffect(()=>()=>{W.current=!1},[]);const me=[{key:"related",label:d("knowledgeGraph.relationAssociates"),icon:"∼"},{key:"dependsOn",label:d("knowledgeGraph.relationDependsOn"),icon:"⊕"},{key:"inherits",label:d("knowledgeGraph.relationInherits"),icon:"↑"},{key:"implements",label:d("knowledgeGraph.relationImplements"),icon:"◇"},{key:"calls",label:d("knowledgeGraph.relationCalls"),icon:"→"},{key:"dataFlow",label:d("knowledgeGraph.relationDataFlow"),icon:"⇢"},{key:"conflicts",label:d("knowledgeGraph.relationConflicts"),icon:"✕"},{key:"extends",label:d("knowledgeGraph.relationExtends"),icon:"⊃"}],R=k=>{E(k),$("view"),q({title:k.name?.replace(/\.md$/,"")||"",description:k.description||"",markdown:k.content?.markdown||"",codePattern:k.content?.pattern||"",rationale:k.content?.rationale||"",tags:k.tags||[],tagInput:""}),he(!1),oe("")},T=()=>{E(null),$("view"),he(!1),oe("")},ee=async()=>{if(!(!N||A)){y(!0);try{const k=N.id||N.name;await Z.knowledgeUpdate(k,{title:U.title,description:U.description,tags:U.tags,content:{...N.content||{},pattern:U.codePattern,markdown:U.markdown,rationale:U.rationale}}),W.current&&($("view"),a?.())}catch(k){ne(ke(k,d("common.saveFailed")),{title:d("common.operationFailed"),type:"error"})}finally{W.current&&y(!1)}}},ie=async k=>{if(N)try{await Z.setRecipeAuthority(N.id||N.name,k),a?.()}catch(b){ne(ke(b,d("common.operationFailed")),{title:d("common.operationFailed"),type:"error"})}},xe=k=>{const b=k.replace(/\.md$/i,"").toLowerCase();return t.find(z=>He(z).toLowerCase()===b)},pe=n.useMemo(()=>{const k=new Map;if(r)for(const[b,z]of Object.entries(r))k.set(b,z);for(const b of t)b.id&&k.set(b.id,He(b)),b.name&&k.set(b.name,He(b));return k},[t,r]),[M,Ce]=n.useState(!1),F=async(k,b)=>{if(!N||M)return;const z={};if(N.relations)for(const[se,be]of Object.entries(N.relations))z[se]=[...be];const le=z[k]||[],O=b.replace(/\.md$/i,"");if(le.some(se=>(typeof se=="string"?se:se.target||se.id||se.title||"").replace(/\.md$/i,"").toLowerCase()===O.toLowerCase()))return;z[k]=[...le,O];const v=N;E({...N,relations:z}),he(!1),oe(""),Ce(!0);try{await Z.updateRecipeRelations(N.id||N.name,z)}catch(se){E(v),ne(ke(se,d("common.operationFailed")),{title:d("common.operationFailed"),type:"error"})}finally{Ce(!1)}},Se=async(k,b)=>{if(!N||M)return;const z={};if(N.relations)for(const[v,se]of Object.entries(N.relations))z[v]=[...se];const le=z[k]||[];z[k]=le.filter(v=>(typeof v=="string"?v:v.target||v.id||v.title||"").replace(/\.md$/i,"").toLowerCase()!==b.replace(/\.md$/i,"").toLowerCase()),z[k].length===0&&delete z[k];const O=N;E({...N,relations:z}),Ce(!0);try{await Z.updateRecipeRelations(N.id||N.name,z)}catch(v){E(O),ne(ke(v,d("common.operationFailed")),{title:d("common.operationFailed"),type:"error"})}finally{Ce(!1)}};n.useEffect(()=>{N&&!t.find(k=>He(k)===He(N))&&T()},[t,N]),n.useEffect(()=>{o==null&&j(1)},[t.length,o]);const Te=it.useMemo(()=>{if(g==="newest")return t;const k=[...t],b=h==="asc"?1:-1;return k.sort((z,le)=>{let O=0,v=0;switch(g){case"alpha":return O=He(z).toLowerCase(),v=He(le).toLowerCase(),b*(O<v?-1:O>v?1:0);case"quality":O=z.quality?.overall??-1,v=le.quality?.overall??-1;break;case"usage":O=(z.stats?.guardUsageCount??0)+(z.stats?.humanUsageCount??0)+(z.stats?.aiUsageCount??0),v=(le.stats?.guardUsageCount??0)+(le.stats?.humanUsageCount??0)+(le.stats?.aiUsageCount??0);break;case"category":return O=(z.category||"").toLowerCase(),v=(le.category||"").toLowerCase(),b*(O<v?-1:O>v?1:0)}return b*(O-v)}),k},[t,g,h]),_e=Math.ceil(Te.length/P),Me=(I-1)*P,te=Te.slice(Me,Me+P),de=k=>{Y(k),window.scrollTo({top:0,behavior:"smooth"})},f=N?Te.findIndex(k=>He(k)===He(N)):-1,J=()=>{f>0&&R(Te[f-1])},ge=()=>{f<Te.length-1&&R(Te[f+1])},ve=({recipe:k})=>{const b=k.kind?Ls[k.kind]:null,z=k.category||"Utility",le=k.knowledgeType,O=[];return b&&O.push(b.label),O.push(z),le&&rs[le]&&O.push(d(rs[le])),k.language&&O.push(k.language.toUpperCase()),k.trigger&&O.push(k.trigger),e.jsx("span",{className:"text-[11px] text-[var(--fg-muted)] truncate",children:O.join("  ·  ")})};return e.jsxs("div",{className:"relative pb-6",children:[t.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-24 text-center",children:[e.jsx(br,{size:48,className:"text-[var(--fg-muted)] mb-4 opacity-40"}),e.jsx("p",{className:"font-medium text-[var(--fg-secondary)] mb-1",children:d("recipes.noResults")}),e.jsx("p",{className:"text-sm text-[var(--fg-muted)]",children:d("recipes.noContent")})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-4 border-b border-[var(--border-default)] pb-3",children:[m.map(k=>{const b=g===k.key;return e.jsxs("button",{onClick:()=>{b?u(z=>z==="asc"?"desc":"asc"):(x(k.key),u(k.defaultDir)),Y(1)},className:je("px-4 py-1.5 rounded-md text-xs font-medium transition-colors flex items-center gap-1",b?"bg-[var(--accent-subtle)] text-[var(--accent)] border border-[var(--accent-emphasis)]":"text-[var(--fg-muted)] hover:bg-[var(--bg-subtle)] border border-transparent"),children:[k.label,b&&g!=="newest"&&(h==="asc"?e.jsx(cl,{size:12}):e.jsx(dl,{size:12}))]},k.key)}),e.jsx("span",{className:"ml-auto text-xs text-[var(--fg-muted)]",children:d("recipes.totalCount",{count:t.length})})]}),e.jsx("div",{children:te.map(k=>{const b=He(k),z=k.description||k.usageGuide||"",le=N&&He(N)===b,O=k.kind?Ls[k.kind]:null;return e.jsx("div",{onClick:()=>R(k),className:je("group relative cursor-pointer py-4 px-4 rounded-lg transition-colors hover:bg-[var(--bg-subtle)] after:absolute after:bottom-0 after:left-4 after:right-4 after:h-px after:bg-[var(--border-default)] last:after:hidden",le&&"bg-[var(--accent-subtle)]"),children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] text-sm break-words leading-snug truncate",children:b}),O&&e.jsx(Vs,{variant:O.label==="Rule"?"red":O.label==="Pattern"?"blue":"default",className:"text-[9px] uppercase shrink-0",children:O.label}),k.stats?.authority!=null&&k.stats.authority>=4&&e.jsxs("span",{className:"text-amber-500 text-[11px] shrink-0",children:["★ ",k.stats.authority]})]}),z&&e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] line-clamp-1 leading-relaxed mb-1.5",children:z.replace(/^#+\s*/gm,"").replace(/\*\*/g,"")}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ve,{recipe:k,compact:!0}),k.tags&&k.tags.length>0&&e.jsxs("span",{className:"text-[11px] text-[var(--fg-muted)]",children:[k.tags.slice(0,3).join(", "),k.tags.length>3&&` +${k.tags.length-3}`]})]})]}),e.jsx("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity shrink-0",children:e.jsxs(Or,{children:[e.jsx(Hr,{asChild:!0,children:e.jsx(We,{variant:"ghost",size:"icon-sm",onClick:v=>v.stopPropagation(),children:e.jsx(ul,{size:14})})}),e.jsxs(oa,{align:"end",children:[e.jsxs(kt,{onClick:v=>{v.stopPropagation(),R(k)},children:[e.jsx(Ut,{size:14,className:"mr-2"})," ",d("common.preview")]}),e.jsxs(kt,{onClick:v=>{v.stopPropagation(),R(k),$("edit")},children:[e.jsx(It,{size:14,className:"mr-2"})," ",d("common.edit")]}),e.jsx(vs,{}),e.jsxs(kt,{className:"text-[var(--status-error)]",onClick:v=>{v.stopPropagation(),s(k.name||k.id||"")},children:[e.jsx(qe,{size:14,className:"mr-2"})," ",d("recipes.deleteRecipe")]})]})]})})]})},k.id||b)})})]}),t.length>0&&e.jsx(ca,{currentPage:I,totalPages:_e,totalItems:Te.length,pageSize:P,onPageChange:de,onPageSizeChange:w}),N&&(()=>{const k=N,b=He(k),z=ki(k),le=Ci(k),O=k.content;return e.jsxs(Ie,{open:!!N,onClose:T,size:G?"lg":"md",children:[e.jsxs(Ie.Header,{title:b,leading:e.jsx("button",{onClick:()=>{s(k.name||k.id||""),T()},title:d("recipes.deleteRecipe"),className:"p-1.5 text-[var(--fg-muted)] hover:text-red-500 rounded-md transition-colors opacity-30 hover:opacity-100 shrink-0",children:e.jsx(qe,{size:14})}),children:[e.jsx(Ie.Nav,{currentIndex:f,total:Te.length,onPrev:J,onNext:ge}),e.jsxs(Ie.HeaderActions,{children:[e.jsxs("div",{className:"flex bg-[var(--bg-subtle)] p-0.5 rounded-lg mr-1",children:[e.jsxs("button",{onClick:()=>$("view"),className:je("px-2.5 py-1 rounded-md text-xs font-bold transition-all flex items-center gap-1",L==="view"?"bg-[var(--bg-surface)] shadow-sm text-[var(--accent)]":"text-[var(--fg-muted)] hover:text-[var(--fg-secondary)]"),children:[e.jsx(Ut,{size:H.sm})," ",d("common.preview")]}),e.jsxs("button",{onClick:()=>{$("edit")},className:je("px-2.5 py-1 rounded-md text-xs font-bold transition-all flex items-center gap-1",L==="edit"?"bg-[var(--bg-surface)] shadow-sm text-[var(--accent)]":"text-[var(--fg-muted)] hover:text-[var(--fg-secondary)]"),children:[e.jsx(It,{size:H.sm})," ",d("common.edit")]})]}),e.jsx(Ie.WidthToggle,{isWide:G,onToggle:_}),e.jsx(Ie.CloseButton,{onClose:T})]})]}),L==="edit"?e.jsxs(e.Fragment,{children:[e.jsxs(Ie.Body,{padded:!0,children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-1.5 block",children:d("recipes.recipeDetail")}),e.jsx("input",{type:"text",value:U.title,onChange:v=>q(se=>({...se,title:v.target.value})),className:"w-full px-3 py-2 text-sm border border-[var(--border-default)] rounded-lg bg-[var(--bg-root)] text-[var(--fg-primary)] focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)] focus:border-[var(--accent-emphasis)]"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-1.5 block",children:d("recipes.description")}),e.jsx("textarea",{value:U.description,onChange:v=>q(se=>({...se,description:v.target.value})),rows:2,className:"w-full px-3 py-2 text-sm border border-[var(--border-default)] rounded-lg bg-[var(--bg-root)] text-[var(--fg-primary)] focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)] resize-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-1.5 block",children:d("recipes.tags")}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:U.tags.map((v,se)=>e.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] px-2 py-0.5 rounded bg-[var(--accent-subtle)] text-[var(--accent)] border border-[var(--border-default)] font-medium",children:[v,e.jsx("button",{onClick:()=>q(be=>({...be,tags:be.tags.filter((fe,De)=>De!==se)})),className:"text-[var(--fg-muted)] hover:text-[var(--status-error)]",children:e.jsx(ze,{size:10})})]},se))}),e.jsx("div",{className:"flex gap-2",children:e.jsx("input",{type:"text",value:U.tagInput,onChange:v=>q(se=>({...se,tagInput:v.target.value})),onKeyDown:v=>{v.key==="Enter"&&U.tagInput.trim()&&(v.preventDefault(),q(se=>({...se,tags:[...se.tags,se.tagInput.trim()],tagInput:""})))},placeholder:d("recipes.tags"),className:"flex-1 px-3 py-1.5 text-xs border border-[var(--border-default)] rounded-lg bg-[var(--bg-root)] text-[var(--fg-primary)] focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)]"})})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-1.5 block flex items-center gap-1.5",children:[e.jsx(Qe,{size:11,className:"text-[var(--accent)]"})," ",d("recipes.markdown")]}),e.jsx("textarea",{value:U.markdown,onChange:v=>q(se=>({...se,markdown:v.target.value})),rows:4,className:"w-full px-3 py-2 text-sm border border-[var(--border-default)] rounded-lg bg-[var(--bg-root)] text-[var(--fg-primary)] focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)] resize-y font-mono",placeholder:d("recipes.markdown")})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-1.5 block flex items-center gap-1.5",children:[e.jsx(At,{size:11,className:"text-[var(--status-success)]"})," ",d("recipes.code")]}),e.jsx("div",{className:"border border-[var(--border-default)] rounded-lg overflow-hidden",style:{minHeight:200},children:e.jsx(ys,{value:U.codePattern,onChange:v=>q(se=>({...se,codePattern:v})),language:le,height:"200px",showLineNumbers:!0})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-1.5 block",children:d("recipes.designRationale")}),e.jsx("textarea",{value:U.rationale,onChange:v=>q(se=>({...se,rationale:v.target.value})),rows:3,className:"w-full px-3 py-2 text-sm border border-[var(--border-default)] rounded-lg bg-[var(--bg-root)] text-[var(--fg-primary)] focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)] resize-y",placeholder:d("recipes.designRationale")})]})]}),e.jsxs(Ie.Footer,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-[var(--fg-muted)]",children:d("recipes.qualityAuthorityScore")}),e.jsx(tt,{value:String(k.stats?.authority??3),onChange:v=>ie(parseInt(v)),options:[1,2,3,4,5].map(v=>({value:String(v),label:`${"⭐".repeat(v)} ${v}`})),size:"xs",className:"font-bold text-amber-600 bg-amber-50 border-amber-100"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(We,{variant:"ghost",onClick:()=>$("view"),disabled:A,children:d("common.cancel")}),e.jsxs(We,{variant:"primary",onClick:ee,disabled:A,loading:A,children:[!A&&e.jsx(ws,{size:H.sm}),d(A?"common.saving":"common.save")]})]})]})]}):e.jsxs(Ie.Body,{children:[e.jsx(da,{badges:(()=>{const v=k.kind?Ls[k.kind]:null,se=k.category||"Utility",be=et[se]||et.All,fe=[];return v&&fe.push({label:v.label,className:`${v.bg} ${v.color} ${v.border}`,icon:v.icon}),fe.push({label:se,className:`font-bold uppercase ${be?.bg||"bg-[var(--bg-subtle)]"} ${be?.color||"text-[var(--fg-muted)]"} ${be?.border||"border-[var(--border-default)]"}`}),k.knowledgeType&&fe.push({label:rs[k.knowledgeType]?d(rs[k.knowledgeType]):k.knowledgeType,className:"bg-purple-50 text-purple-700 border-purple-200"}),k.language&&fe.push({label:k.language,className:"uppercase font-bold text-[var(--fg-secondary)] bg-[var(--bg-subtle)] border-[var(--border-default)]"}),k.trigger&&fe.push({label:k.trigger,className:"font-mono font-bold bg-amber-50 text-amber-700 border-amber-200"}),k.source&&k.source!=="unknown"&&fe.push({label:k.source,className:"bg-[var(--bg-subtle)] text-[var(--fg-secondary)] border-[var(--border-default)]"}),fe})(),metadata:(()=>{const v=[];return k.scope&&v.push({icon:Ct,iconClass:"text-teal-400",label:d("candidates.path"),value:k.scope==="universal"?d("common.all"):k.scope==="project-specific"?d("candidates.category"):k.scope}),k.complexity&&v.push({icon:Ge,iconClass:"text-orange-400",label:d("knowledge.complexity"),value:k.complexity==="advanced"?d("knowledge.complexityAdvanced"):k.complexity==="intermediate"?d("knowledge.complexityIntermediate"):k.complexity==="beginner"?d("knowledge.complexityBeginner"):k.complexity}),k.source&&k.source!=="unknown"&&v.push({icon:Ct,iconClass:"text-violet-400",label:d("recipes.sourceLabel"),value:k.source==="bootstrap-scan"?d("recipes.sourceBootstrap"):k.source==="agent"?d("recipes.sourceAiScan"):k.source}),k.updatedAt&&Xr(k.updatedAt)&&v.push({icon:Ye,iconClass:"text-[var(--fg-muted)]",label:d("candidates.updatedAt"),value:Ia(k.updatedAt)}),v})(),tags:k.tags,id:k.id,sourceFile:k.sourceFile,sourceFileLabel:d("candidates.path")}),e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ta,{size:12,className:je("text-purple-400",M&&"animate-spin")}),e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase",children:d("recipes.relations")}),(()=>{const v=k.relations?Object.values(k.relations).flat().length:0;return v>0?e.jsx(Vs,{variant:"blue",className:"text-[9px]",children:v}):null})()]}),e.jsx(We,{variant:re?"secondary":"primary",size:"sm",onClick:()=>{he(!re),oe("")},children:re?e.jsxs(e.Fragment,{children:[e.jsx(ze,{size:10})," ",d("common.cancel")]}):e.jsxs(e.Fragment,{children:[e.jsx(mt,{size:10})," ",d("recipes.editBtn")]})})]}),re&&e.jsxs("div",{className:"mb-3 bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-lg p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(tt,{value:ue,onChange:v=>V(v),options:me.map(v=>({value:v.key,label:`${v.icon} ${v.label}`})),size:"xs",className:"font-bold"}),e.jsxs("div",{className:"flex-1 relative",children:[e.jsx(xt,{size:12,className:"absolute left-2 top-1/2 -translate-y-1/2 text-[var(--fg-muted)]"}),e.jsx("input",{type:"text",placeholder:d("recipes.searchPlaceholder"),value:B,onChange:v=>oe(v.target.value),className:"w-full text-xs bg-[var(--bg-root)] border border-[var(--border-default)] rounded pl-7 pr-2 py-1 outline-none text-[var(--fg-primary)]",autoFocus:!0})]})]}),B.length>0&&e.jsx("div",{className:"max-h-36 overflow-y-auto rounded border border-[var(--border-default)] bg-[var(--bg-root)] divide-y divide-[var(--border-default)]",children:(()=>{const v=t.filter(se=>He(se)===b?!1:He(se).toLowerCase().includes(B.toLowerCase())).slice(0,10);return v.length?v.map(se=>{const be=He(se),fe=k.relations&&Object.values(k.relations).flat().some(De=>(typeof De=="string"?De:De.target||De.id||De.title||"").replace(/\.md$/i,"").toLowerCase()===be.toLowerCase());return e.jsxs("div",{className:je("flex items-center justify-between px-3 py-1.5 text-xs",fe||M?"bg-[var(--bg-subtle)] text-[var(--fg-muted)]":"hover:bg-[var(--bg-subtle)] cursor-pointer"),onClick:()=>!fe&&!M&&F(ue,be),children:[e.jsx("span",{className:"font-medium truncate mr-2",children:be}),fe?e.jsx("span",{className:"text-[9px] text-[var(--fg-muted)] font-bold shrink-0",children:d("recipes.relations")}):e.jsxs("span",{className:"text-[9px] text-[var(--accent)] font-bold shrink-0",children:["+ ",d("recipes.editBtn")]})]},be)}):e.jsx("div",{className:"text-xs text-[var(--fg-muted)] py-3 text-center",children:d("recipes.noResults")})})()})]}),k.relations&&Object.entries(k.relations).some(([,v])=>Array.isArray(v)&&v.length>0)?e.jsx("div",{className:"space-y-1.5",children:me.map(({key:v,label:se,icon:be})=>{const fe=k.relations?.[v];return!fe||!Array.isArray(fe)||fe.length===0?null:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("span",{className:"text-[10px] font-mono text-[var(--fg-muted)] shrink-0 whitespace-nowrap pt-0.5",children:[be," ",se]}),e.jsx("div",{className:"flex flex-wrap gap-1",children:fe.map((De,ae)=>{const we=typeof De=="string"?De:De.target||De.id||De.title||JSON.stringify(De),Oe=xe(we)||(pe.has(we)?xe(pe.get(we)):void 0),rt=Oe?He(Oe):pe.get(we)||we;return e.jsxs("span",{className:je("group/rel inline-flex items-center gap-1 px-1.5 py-0.5 border rounded text-[10px] font-mono transition-colors",Oe?"bg-[var(--accent-subtle)] border-[var(--accent-emphasis)] text-[var(--accent)] cursor-pointer hover:brightness-95":"bg-[var(--bg-root)] border-[var(--border-default)] text-[var(--fg-secondary)]"),onClick:()=>Oe&&R(Oe),title:Oe?d("candidates.viewDetail"):rt,children:[rt.replace(/\.md$/i,""),e.jsx("button",{onClick:ct=>{ct.stopPropagation(),!M&&window.confirm(`${d("common.delete")}: ${rt.replace(/\.md$/i,"")}?`)&&Se(v,we)},disabled:M,className:"opacity-0 group-hover/rel:opacity-100 text-[var(--danger)] hover:text-[var(--danger)] transition-opacity ml-1 p-0.5 rounded hover:bg-[var(--danger-subtle)]",title:d("common.delete"),children:e.jsx(ze,{size:10})})]},ae)})})]},v)})}):!re&&e.jsx("div",{className:"text-xs text-[var(--fg-muted)] py-2 text-center",children:d("recipes.noContent")})]}),e.jsxs("div",{className:"px-6 py-3 border-b border-[var(--border-default)]",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-xl p-3 text-center border border-[var(--border-default)]",children:[e.jsx("div",{className:"text-lg font-bold text-amber-600",children:k.stats?.authority??"—"}),e.jsx("div",{className:"text-[10px] text-[var(--fg-muted)] font-medium",children:d("recipes.qualityAuthorityScore")})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-xl p-3 text-center border border-[var(--border-default)]",children:[e.jsx("div",{className:"text-lg font-bold text-[var(--accent)]",children:k.stats?.authorityScore!=null?k.stats.authorityScore.toFixed(1):"—"}),e.jsx("div",{className:"text-[10px] text-[var(--fg-muted)] font-medium",children:d("recipes.qualityGreat")})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-xl p-3 text-center border border-[var(--border-default)]",children:[e.jsx("div",{className:"text-lg font-bold text-[var(--fg-primary)]",children:k.stats?k.stats.guardUsageCount+k.stats.humanUsageCount+k.stats.aiUsageCount:0}),e.jsx("div",{className:"text-[10px] text-[var(--fg-muted)] font-medium",children:d("recipes.qualitySolid")})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-xl p-3 text-center border border-[var(--border-default)]",children:[e.jsx("div",{className:"text-sm font-bold text-[var(--fg-secondary)]",children:Ia(k.stats?.lastUsedAt)||d("recipes.noContent")}),e.jsx("div",{className:"text-[10px] text-[var(--fg-muted)] font-medium",children:d("recipes.qualityGood")})]})]}),k.stats!=null&&(k.stats.guardUsageCount>0||k.stats.humanUsageCount>0||k.stats.aiUsageCount>0)&&e.jsxs("div",{className:"flex items-center gap-4 mt-2 text-[10px] text-[var(--fg-muted)]",children:[e.jsxs("span",{children:["Guard: ",k.stats.guardUsageCount]}),e.jsxs("span",{children:["Human: ",k.stats.humanUsageCount]}),e.jsxs("span",{children:["AI: ",k.stats.aiUsageCount]})]})]}),e.jsx(Ee.Reasoning,{reasoning:k.reasoning,labels:{section:d("recipes.reasoning"),source:d("recipes.sourceColon"),confidence:d("recipes.confidenceColon"),alternatives:d("recipes.alternativesLabel")}}),e.jsx(Ee.Quality,{quality:k.quality,labels:{section:d("recipes.qualityGrade"),completeness:d("recipes.qualityCompleteness"),adaptation:d("recipes.qualityAdaptation"),documentation:d("recipes.qualityDocumentation")}}),e.jsx(Ee.Description,{label:d("recipes.description"),text:k.description}),e.jsx(Ee.MarkdownSection,{label:d("recipes.markdown"),content:O?.markdown}),e.jsx(Ee.Headers,{label:d("recipes.headers"),headers:k.headers}),e.jsx(Ee.CodePattern,{label:d("recipes.code"),code:z,language:le}),e.jsx(Ee.Rationale,{label:d("recipes.designRationale"),text:O?.rationale}),e.jsx(Ee.Steps,{label:d("recipes.steps"),steps:O?.steps}),O?.codeChanges&&O.codeChanges.length>0&&e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:d("recipes.codeChanges")}),e.jsx("div",{className:"space-y-2",children:O.codeChanges.map((v,se)=>e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-3 py-1.5 bg-[var(--bg-subtle)] border-b border-[var(--border-default)] flex items-center gap-2",children:[e.jsx(pt,{size:11,className:"text-[var(--accent)]"}),e.jsx("code",{className:"text-[10px] font-mono text-[var(--fg-secondary)]",children:v.file})]}),v.explanation&&e.jsx("p",{className:"text-[11px] text-[var(--fg-muted)] px-3 py-1.5 border-b border-[var(--border-default)] bg-[var(--bg-subtle)]",children:v.explanation}),e.jsxs("div",{className:"p-2 bg-red-50/10 border-b border-[var(--border-default)]",children:[e.jsx("div",{className:"text-[9px] font-bold text-[var(--status-error)] mb-0.5 uppercase",children:"Before"}),e.jsx("pre",{className:"text-[11px] text-[var(--fg-secondary)] whitespace-pre-wrap break-words font-mono",children:v.before||d("recipes.emptyValue")})]}),e.jsxs("div",{className:"p-2 bg-emerald-50/10",children:[e.jsx("div",{className:"text-[9px] font-bold text-[var(--status-success)] mb-0.5 uppercase",children:"After"}),e.jsx("pre",{className:"text-[11px] text-[var(--fg-primary)] whitespace-pre-wrap break-words font-mono",children:v.after})]})]},se))})]}),O?.verification&&e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:d("recipes.validation")}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-xl p-4 space-y-1.5",children:[O.verification.method&&e.jsxs("p",{className:"text-xs text-[var(--fg-secondary)]",children:[e.jsx("span",{className:"font-bold text-[var(--status-success)]",children:d("recipes.verificationMethod")})," ",O.verification.method]}),O.verification.expectedResult&&e.jsxs("p",{className:"text-xs text-[var(--fg-secondary)]",children:[e.jsx("span",{className:"font-bold text-[var(--status-success)]",children:d("recipes.verificationExpected")})," ",O.verification.expectedResult]}),O.verification.testCode&&e.jsx("pre",{className:"text-[11px] font-mono bg-slate-800 text-green-300 p-2.5 rounded-md overflow-x-auto whitespace-pre-wrap mt-1",children:O.verification.testCode})]})]}),e.jsx(Ee.Constraints,{label:d("recipes.constraints"),constraints:k.constraints})]})]})})()]})};function yt(t){return t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"k":String(t)}function Ai(t){const s=new Map(t.map(r=>[r.date,r])),a=[];for(let r=6;r>=0;r--){const o=new Date;o.setDate(o.getDate()-r);const l=o.toISOString().slice(0,10);a.push(s.get(l)||{date:l,input_tokens:0,output_tokens:0,total_tokens:0,call_count:0})}return a}const Di={user:"bg-blue-500",mcp:"bg-purple-500",bootstrap:"bg-amber-500",guard:"bg-rose-500",analyst:"bg-indigo-500",producer:"bg-green-500"},Ri=()=>{const{t}=Ae(),[s,a]=n.useState([]),[r,o]=n.useState([]),[l,i]=n.useState({input_tokens:0,output_tokens:0,total_tokens:0,call_count:0,avg_per_call:0}),[p,d]=n.useState(!0),[g,x]=n.useState(null);n.useEffect(()=>{let c=!1;return(async()=>{try{const j=await Z.getTokenUsage7Days();if(c)return;a(j.daily||[]),o(j.bySource||[]),i(j.summary||{input_tokens:0,output_tokens:0,total_tokens:0,call_count:0,avg_per_call:0})}catch(j){c||x(ke(j,t("tokenUsageChart.loadFailed")))}finally{c||d(!1)}})(),()=>{c=!0}},[]);const h=n.useMemo(()=>Ai(s),[s]),u=n.useMemo(()=>Math.max(...h.map(c=>c.total_tokens),1),[h]);if(p)return e.jsxs("div",{className:"flex items-center justify-center py-10",children:[e.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-2 border-blue-500 border-t-transparent"}),e.jsx("span",{className:"ml-2 text-slate-500 text-sm",children:t("tokenUsageChart.loading")})]});if(g)return e.jsx("p",{className:"text-red-500 text-sm py-4 text-center",children:g});const m=l.total_tokens===0;return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(ns,{label:t("tokenUsageChart.totalToken"),value:yt(l.total_tokens),sub:t("tokenUsageChart.totalSub"),color:"blue"}),e.jsx(ns,{label:t("tokenUsageChart.input"),value:yt(l.input_tokens),sub:"Prompt",color:"green"}),e.jsx(ns,{label:t("tokenUsageChart.output"),value:yt(l.output_tokens),sub:"Completion",color:"purple"}),e.jsx(ns,{label:t("tokenUsageChart.calls"),value:String(l.call_count),sub:t("tokenUsageChart.avgPerCall",{avg:yt(l.avg_per_call)}),color:"amber"})]}),m?e.jsx("div",{className:"text-center py-8 text-slate-400 text-sm",children:t("tokenUsageChart.emptyState")}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold text-slate-700 mb-3",children:t("tokenUsageChart.dailyUsage")}),e.jsx("div",{className:"flex items-end gap-1.5 h-40",children:h.map(c=>{const j=c.input_tokens/u*100,S=c.output_tokens/u*100,D=t(`tokenUsageChart.weekday${new Date(c.date+"T00:00:00").getDay()}`);return e.jsxs("div",{className:"flex-1 flex flex-col items-center gap-1 group relative",children:[e.jsxs("div",{className:"absolute -top-16 left-1/2 -translate-x-1/2 bg-slate-800 text-white text-xs rounded px-2 py-1 opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap pointer-events-none z-10",children:[e.jsx("p",{children:c.date}),e.jsx("p",{children:t("tokenUsageChart.dailyDetail",{input:yt(c.input_tokens),output:yt(c.output_tokens)})}),e.jsx("p",{children:t("tokenUsageChart.dailyCalls",{count:String(c.call_count)})})]}),e.jsxs("div",{className:"w-full flex flex-col justify-end",style:{height:"120px"},children:[e.jsx("div",{className:"bg-green-400 rounded-t-sm w-full transition-all",style:{height:`${j}%`,minHeight:c.input_tokens>0?"2px":"0"}}),e.jsx("div",{className:"bg-purple-400 rounded-b-sm w-full transition-all",style:{height:`${S}%`,minHeight:c.output_tokens>0?"2px":"0"}})]}),e.jsx("span",{className:"text-[10px] text-slate-400",children:D})]},c.date)})}),e.jsxs("div",{className:"flex gap-4 mt-2 text-xs text-slate-500 justify-center",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-sm bg-green-400 inline-block"})," ",t("tokenUsageChart.legendInput")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-sm bg-purple-400 inline-block"})," ",t("tokenUsageChart.legendOutput")]})]})]}),r.length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold text-slate-700 mb-3",children:t("tokenUsageChart.sourceDistribution")}),e.jsx("div",{className:"space-y-2",children:r.map(c=>{const j=l.total_tokens>0?c.total_tokens/l.total_tokens*100:0,S=Di[c.source]||"bg-slate-400";return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"w-20 text-xs text-slate-600 text-right truncate",children:c.source}),e.jsx("div",{className:"flex-1 bg-slate-100 rounded-full h-3 overflow-hidden",children:e.jsx("div",{className:`${S} h-full rounded-full transition-all`,style:{width:`${j}%`,minWidth:j>0?"4px":"0"}})}),e.jsx("span",{className:"w-16 text-xs text-slate-500 text-right",children:yt(c.total_tokens)}),e.jsxs("span",{className:"w-12 text-xs text-slate-400 text-right",children:[j.toFixed(0),"%"]})]},c.source)})})]})]})]})};function ns({label:t,value:s,sub:a,color:r}){const o={blue:"bg-blue-50 border-blue-200 text-blue-700",green:"bg-green-50 border-green-200 text-green-700",purple:"bg-purple-50 border-purple-200 text-purple-700",amber:"bg-amber-50 border-amber-200 text-amber-700"},l=o[r]||o.blue;return e.jsxs("div",{className:`rounded-lg border p-3 ${l}`,children:[e.jsx("p",{className:"text-xs opacity-70",children:t}),e.jsx("p",{className:"text-xl font-bold",children:s}),e.jsx("p",{className:"text-[10px] opacity-60",children:a})]})}const ht=({id:t,title:s,icon:a,isExpanded:r,onToggle:o,children:l})=>e.jsxs("section",{className:"border border-[var(--border-default)] rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>o(t),className:"w-full flex items-center justify-between p-4 bg-[var(--bg-subtle)] hover:bg-[var(--bg-muted)] active:bg-[var(--bg-muted)] outline-none focus:outline-none focus-visible:outline-none transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[a,e.jsx("h2",{className:"text-lg font-bold text-[var(--fg-primary)]",children:s})]}),r?e.jsx(gt,{size:H.lg}):e.jsx(Ke,{size:H.lg})]}),r&&e.jsx("div",{className:"p-4 bg-[var(--bg-surface)]",children:l})]}),Ii=()=>{const{t}=Ae(),[s,a]=n.useState(new Set(["quick-start"])),r=o=>{const l=new Set(s);l.has(o)?l.delete(o):l.add(o),a(l)};return e.jsxs("div",{className:"max-w-5xl mx-auto py-8 px-4",children:[e.jsxs("div",{className:"mb-8 text-center",children:[e.jsx("h1",{className:"text-4xl font-bold text-[var(--fg-primary)] mb-4",children:t("help.pageTitle")}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-lg max-w-3xl mx-auto text-center",children:t("help.subtitle")}),e.jsx("p",{className:"text-[var(--fg-muted)] text-sm mt-2",children:t("help.techSpecs")}),e.jsxs("div",{className:"mt-6 flex gap-3 justify-center text-sm",children:[e.jsxs("a",{href:"https://github.com/GxFn/AutoSnippet",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 px-5 py-2.5 bg-[var(--bg-subtle)] border border-[var(--border-default)] text-[var(--fg-primary)] rounded-full hover:bg-[var(--bg-muted)] transition-colors",children:[e.jsx(ml,{size:H.sm}),t("help.viewGithub")]}),e.jsxs("a",{href:"https://docs.gaoxuefeng.com/part1/ch01-introduction.html",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 px-5 py-2.5 bg-blue-600 text-white rounded-full hover:bg-blue-700 transition-colors",children:[e.jsx(Ue,{size:H.sm}),t("help.fullDocs"),e.jsx(Nr,{size:12})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(ht,{id:"token-usage",title:t("help.tokenUsageLast7Days"),icon:e.jsx(Tt,{size:H.xl,className:"text-blue-600"}),isExpanded:s.has("token-usage"),onToggle:r,children:e.jsx(Ri,{})}),e.jsx(ht,{id:"quick-start",title:t("help.quickStart"),icon:e.jsx(Kt,{size:H.xl,className:"text-blue-600"}),isExpanded:s.has("quick-start"),onToggle:r,children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"bg-blue-50 rounded-lg p-4 border border-blue-200",children:[e.jsx("div",{className:"bg-blue-600 text-white rounded-full w-8 h-8 flex items-center justify-center mb-3 font-bold",children:"1"}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:t("help.step1Title")}),e.jsx("pre",{className:"bg-blue-100/70 text-blue-900 px-3 py-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-all",children:e.jsxs("code",{children:["npm install -g autosnippet",`
`,"cd your-project",`
`,"asd setup"]})})]}),e.jsxs("div",{className:"bg-green-50 rounded-lg p-4 border border-green-200",children:[e.jsx("div",{className:"bg-green-600 text-white rounded-full w-8 h-8 flex items-center justify-center mb-3 font-bold",children:"2"}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:t("help.step2Title")}),e.jsx("pre",{className:"bg-green-100/70 text-green-900 px-3 py-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-all",children:e.jsx("code",{children:"asd ui"})}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mt-2",children:t("help.step2Desc")})]}),e.jsxs("div",{className:"bg-purple-50 rounded-lg p-4 border border-purple-200",children:[e.jsx("div",{className:"bg-purple-600 text-white rounded-full w-8 h-8 flex items-center justify-center mb-3 font-bold",children:"3"}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:t("help.step3Title")}),e.jsx("pre",{className:"bg-purple-100/70 text-purple-900 px-3 py-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-all",children:e.jsx("code",{children:"asd upgrade"})}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mt-2",children:t("help.step3Desc")})]}),e.jsxs("div",{className:"bg-amber-50 rounded-lg p-4 border border-amber-200",children:[e.jsx("div",{className:"bg-amber-600 text-white rounded-full w-8 h-8 flex items-center justify-center mb-3 font-bold",children:"4"}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:t("help.step4Title")}),e.jsx("pre",{className:"bg-amber-100/70 text-amber-900 px-3 py-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-all mb-2",children:e.jsx("code",{children:"asd coldstart"})}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.step4Desc1")}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.step4Desc2")})]})]})}),e.jsxs(ht,{id:"concepts",title:t("help.coreConcepts"),icon:e.jsx(Gs,{size:H.xl,className:"text-blue-600"}),isExpanded:s.has("concepts"),onToggle:r,children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-[var(--fg-primary)] mb-3",children:t("help.threeRoles")}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full border border-[var(--border-default)] rounded-lg text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-[var(--bg-subtle)]",children:[e.jsx("th",{className:"px-4 py-3 border-b text-left font-semibold",children:t("help.roleColumn")}),e.jsx("th",{className:"px-4 py-3 border-b text-left font-semibold",children:t("help.responsibilityColumn")}),e.jsx("th",{className:"px-4 py-3 border-b text-left font-semibold",children:t("help.capabilityColumn")})]})}),e.jsxs("tbody",{children:[e.jsxs("tr",{className:"hover:bg-[var(--bg-subtle)]",children:[e.jsx("td",{className:"px-4 py-3 border-b font-medium text-blue-700",children:t("help.roleDeveloper")}),e.jsx("td",{className:"px-4 py-3 border-b",children:t("help.developerResp")}),e.jsx("td",{className:"px-4 py-3 border-b text-xs",dangerouslySetInnerHTML:{__html:t("help.developerCap")}})]}),e.jsxs("tr",{className:"hover:bg-[var(--bg-subtle)]",children:[e.jsx("td",{className:"px-4 py-3 border-b font-medium text-green-700",children:t("help.roleCursorAgent")}),e.jsx("td",{className:"px-4 py-3 border-b",children:t("help.cursorAgentResp")}),e.jsx("td",{className:"px-4 py-3 border-b text-xs",dangerouslySetInnerHTML:{__html:t("help.cursorAgentCap")}})]}),e.jsxs("tr",{className:"hover:bg-[var(--bg-subtle)]",children:[e.jsx("td",{className:"px-4 py-3 font-medium text-purple-700",children:t("help.roleChatAgent")}),e.jsx("td",{className:"px-4 py-3",children:t("help.chatAgentResp")}),e.jsx("td",{className:"px-4 py-3 text-xs",dangerouslySetInnerHTML:{__html:t("help.chatAgentCap")}})]})]})]})})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-[var(--fg-primary)] mb-3",children:t("help.coreComponents")}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 [&_li]:break-words",children:[e.jsxs("div",{className:"bg-green-50 rounded-lg p-4 border border-green-200",children:[e.jsxs("h4",{className:"font-semibold text-green-900 mb-2 flex items-center gap-2",children:[e.jsx(Be,{size:H.lg}),t("help.bootstrapLabel")]}),e.jsx("p",{className:"text-green-800 text-sm mb-3",children:t("help.bootstrapDesc")}),e.jsxs("ul",{className:"text-green-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.bootstrapBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.bootstrapBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.bootstrapBullet3")}})]})]}),e.jsxs("div",{className:"bg-purple-50 rounded-lg p-4 border border-purple-200",children:[e.jsxs("h4",{className:"font-semibold text-purple-900 mb-2 flex items-center gap-2",children:[e.jsx(pl,{size:H.lg}),t("help.candidatesLabel")]}),e.jsx("p",{className:"text-purple-800 text-sm mb-3",children:t("help.candidatesDesc")}),e.jsxs("ul",{className:"text-purple-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.candidatesBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.candidatesBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.candidatesBullet3")}})]})]}),e.jsxs("div",{className:"bg-blue-50 rounded-lg p-4 border border-blue-200",children:[e.jsxs("h4",{className:"font-semibold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(pt,{size:H.lg}),t("help.recipeLabel")]}),e.jsx("p",{className:"text-blue-800 text-sm mb-3",children:t("help.recipeDesc")}),e.jsxs("ul",{className:"text-blue-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.recipeBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.recipeBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.recipeBullet3")}})]})]}),e.jsxs("div",{className:"bg-indigo-50 rounded-lg p-4 border border-indigo-200",children:[e.jsxs("h4",{className:"font-semibold text-indigo-900 mb-2 flex items-center gap-2",children:[e.jsx(ga,{size:H.lg}),t("help.chatAgentLabel")]}),e.jsx("p",{className:"text-indigo-800 text-sm mb-3",children:t("help.chatAgentDesc")}),e.jsxs("ul",{className:"text-indigo-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.chatAgentCompBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.chatAgentCompBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.chatAgentCompBullet3")}})]})]}),e.jsxs("div",{className:"bg-amber-50 rounded-lg p-4 border border-amber-200",children:[e.jsxs("h4",{className:"font-semibold text-amber-900 mb-2 flex items-center gap-2",children:[e.jsx(xt,{size:H.lg}),t("help.searchPipelineLabel")]}),e.jsx("p",{className:"text-amber-800 text-sm mb-3",children:t("help.searchPipelineDesc")}),e.jsxs("ul",{className:"text-amber-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.searchPipelineBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.searchPipelineBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.searchPipelineBullet3")}})]})]}),e.jsxs("div",{className:"bg-cyan-50 rounded-lg p-4 border border-cyan-200",children:[e.jsxs("h4",{className:"font-semibold text-cyan-900 mb-2 flex items-center gap-2",children:[e.jsx(ha,{size:H.lg}),t("help.taskGraphLabel")]}),e.jsx("p",{className:"text-cyan-800 text-sm mb-3",children:t("help.taskGraphDesc")}),e.jsxs("ul",{className:"text-cyan-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.taskGraphBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.taskGraphBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.taskGraphBullet3")}})]})]}),e.jsxs("div",{className:"bg-rose-50 rounded-lg p-4 border border-rose-200",children:[e.jsxs("h4",{className:"font-semibold text-rose-900 mb-2 flex items-center gap-2",children:[e.jsx(Ve,{size:H.lg}),t("help.guardLabel")]}),e.jsx("p",{className:"text-rose-800 text-sm mb-3",children:t("help.guardDesc")}),e.jsxs("ul",{className:"text-rose-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.guardCompBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.guardCompBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.guardCompBullet3")}})]})]}),e.jsxs("div",{className:"bg-teal-50 rounded-lg p-4 border border-teal-200",children:[e.jsxs("h4",{className:"font-semibold text-teal-900 mb-2 flex items-center gap-2",children:[e.jsx(ba,{size:H.lg}),t("help.ideIntegrationLabel")]}),e.jsx("p",{className:"text-teal-800 text-sm mb-3",children:t("help.ideIntegrationDesc")}),e.jsxs("ul",{className:"text-teal-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.ideIntegrationBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.ideIntegrationBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.ideIntegrationBullet3")}})]})]}),e.jsxs("div",{className:"bg-orange-50 rounded-lg p-4 border border-orange-200",children:[e.jsxs("h4",{className:"font-semibold text-orange-900 mb-2 flex items-center gap-2",children:[e.jsx(hr,{size:H.lg}),t("help.securityLabel")]}),e.jsx("p",{className:"text-orange-800 text-sm mb-3",children:t("help.securityDesc")}),e.jsxs("ul",{className:"text-orange-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.securityBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.securityBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.securityBullet3")}})]})]})]})]}),e.jsxs("div",{className:"mt-6 mb-6 p-4 bg-[var(--bg-subtle)] rounded-lg border border-[var(--border-default)]",children:[e.jsx("h3",{className:"text-lg font-semibold text-[var(--fg-primary)] mb-3",children:t("help.archOverviewLabel")}),e.jsxs("div",{className:"flex items-center justify-between gap-1 text-xs overflow-x-auto pb-2",children:[e.jsx("div",{className:"bg-indigo-100 text-indigo-700 px-3 py-2 rounded-lg font-medium text-center shrink-0",children:t("help.archOverviewBootstrap")}),e.jsx("span",{className:"text-[var(--fg-muted)] shrink-0",children:"→"}),e.jsx("div",{className:"bg-blue-100 text-blue-700 px-3 py-2 rounded-lg font-medium text-center shrink-0",children:t("help.archOverviewKB")}),e.jsx("span",{className:"text-[var(--fg-muted)] shrink-0",children:"→"}),e.jsx("div",{className:"bg-blue-100 text-blue-700 px-3 py-2 rounded-lg font-medium text-center shrink-0",children:t("help.archOverviewPipeline")}),e.jsx("span",{className:"text-[var(--fg-muted)] shrink-0",children:"→"}),e.jsx("div",{className:"bg-emerald-100 text-emerald-700 px-3 py-2 rounded-lg font-medium text-center shrink-0",children:t("help.archOverviewAgent")}),e.jsx("span",{className:"text-[var(--fg-muted)] shrink-0",children:"→"}),e.jsx("div",{className:"bg-amber-100 text-amber-700 px-3 py-2 rounded-lg font-medium text-center shrink-0",children:t("help.archOverviewTask")}),e.jsx("span",{className:"text-[var(--fg-muted)] shrink-0",children:"→"}),e.jsx("div",{className:"bg-emerald-100 text-emerald-700 px-3 py-2 rounded-lg font-medium text-center shrink-0",children:t("help.archOverviewOutput")})]}),e.jsxs("div",{className:"mt-2 flex items-center justify-center gap-3 text-xs",children:[e.jsxs("span",{className:"bg-rose-100 text-rose-700 px-3 py-1.5 rounded-lg font-medium",children:["↕ ",t("help.archOverviewSecurity")," ↕"]}),e.jsxs("span",{className:"bg-teal-100 text-teal-700 px-3 py-1.5 rounded-lg font-medium",children:["↕ ",t("help.archOverviewIDE")," ↕"]})]})]}),e.jsxs("div",{className:"mt-6 rounded-lg p-5 border border-[var(--border-default)] bg-[var(--bg-subtle)]",children:[e.jsx("h3",{className:"text-lg font-semibold text-[var(--fg-primary)] mb-5",children:t("help.knowledgeLoop")}),e.jsx("div",{className:"flex items-start justify-between gap-0 overflow-x-auto pb-2",children:[{step:1,color:"blue",key:"loopStep1",subKey:"loopStep1Sub"},{step:2,color:"green",key:"loopStep2",subKey:"loopStep2Sub"},{step:3,color:"purple",key:"loopStep3",subKey:"loopStep3Sub"},{step:4,color:"amber",key:"loopStep4",subKey:"loopStep4Sub"},{step:5,color:"rose",key:"loopStep5",subKey:"loopStep5Sub"}].map((o,l)=>e.jsxs(it.Fragment,{children:[e.jsxs("div",{className:"flex-1 min-w-[90px] flex flex-col items-center text-center",children:[e.jsx("div",{className:`w-11 h-11 rounded-full flex items-center justify-center font-bold text-lg text-white shadow-md mb-2.5 bg-${o.color}-500`,children:o.step}),e.jsx("p",{className:"text-[var(--fg-primary)] font-semibold text-sm leading-tight",children:t(`help.${o.key}`)}),e.jsx("p",{className:"text-[var(--fg-muted)] text-xs mt-1 font-mono",children:t(`help.${o.subKey}`)})]}),l<4&&e.jsxs("div",{className:"flex items-center pt-3 px-1 shrink-0",children:[e.jsx("div",{className:"w-6 h-px bg-[var(--border-default)]"}),e.jsx("span",{className:"text-[var(--fg-muted)] text-xs mx-0.5",children:"›"}),e.jsx("div",{className:"w-6 h-px bg-[var(--border-default)]"})]})]},o.step))}),e.jsx("div",{className:"mt-4 flex items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-2 text-xs text-[var(--fg-muted)]",children:[e.jsx("span",{className:"inline-block w-8 h-px bg-rose-400/50"}),e.jsx("span",{className:"italic",children:t("help.loopStep5")}),e.jsx("span",{children:"→"}),e.jsx("span",{className:"italic",children:t("help.loopStep1")}),e.jsx("span",{className:"inline-block w-8 h-px bg-blue-400/50"})]})})]})]}),e.jsxs(ht,{id:"agent-arch",title:t("help.agentArchTitle"),icon:e.jsx(Mt,{size:H.xl,className:"text-blue-600"}),isExpanded:s.has("agent-arch"),onToggle:r,children:[e.jsx("p",{className:"text-[var(--fg-secondary)] text-sm mb-5",children:t("help.agentArchDesc")}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5",children:[e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-indigo-100 flex items-center justify-center shrink-0",children:e.jsx(Ge,{size:H.lg,className:"text-indigo-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.agentArchPresetTitle")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.agentArchPresetDesc")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchPresetChat")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchPresetInsight")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchPresetLark")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchPresetRemoteExec")}})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-emerald-100 flex items-center justify-center shrink-0",children:e.jsx(Wt,{size:H.lg,className:"text-emerald-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.agentArchStrategyTitle")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.agentArchStrategyDesc")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchStrategySingle")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchStrategyPipeline")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchStrategyFanOut")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchStrategyAdaptive")}})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-blue-100 flex items-center justify-center shrink-0",children:e.jsx(Be,{size:H.lg,className:"text-blue-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.agentArchCapTitle")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.agentArchCapDesc")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchCapConversation")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchCapCodeAnalysis")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchCapKnowledgeProd")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchCapScanProd")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchCapSystem")}})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-purple-100 flex items-center justify-center shrink-0",children:e.jsx(Gs,{size:H.lg,className:"text-purple-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.agentArchMemoryTitle")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.agentArchMemoryDesc")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchMemoryWorking")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchMemorySession")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchMemoryPersistent")}})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-amber-100 flex items-center justify-center shrink-0",children:e.jsx(ga,{size:H.lg,className:"text-amber-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.agentArchContextTitle")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.agentArchContextDesc")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchContextWindow")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchContextTracker")}})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-rose-100 flex items-center justify-center shrink-0",children:e.jsx(Rs,{size:H.lg,className:"text-rose-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.agentArchToolsTitle")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.agentArchToolsDesc")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchToolsInternal")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchToolsMcp")}})]}),e.jsxs("div",{className:"mt-3 pt-3 border-t border-[var(--border-default)]",children:[e.jsx("p",{className:"text-xs font-semibold text-[var(--fg-primary)] mb-1",children:t("help.agentArchRouterTitle")}),e.jsx("p",{className:"text-xs text-[var(--fg-secondary)]",children:t("help.agentArchRouterDesc")})]})]})]})]}),e.jsxs(ht,{id:"features",title:t("help.coreFeatures"),icon:e.jsx(Be,{size:H.xl,className:"text-blue-600"}),isExpanded:s.has("features"),onToggle:r,children:[e.jsx("p",{className:"text-[var(--fg-secondary)] text-sm mb-5",children:t("help.coreFeaturesDesc")}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5",children:[e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-blue-100 flex items-center justify-center shrink-0",children:e.jsx(kr,{size:H.lg,className:"text-blue-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.knowledgeBuild")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.kbBuildDesc")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.kbBuildBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.kbBuildBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.kbBuildBullet3")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.kbBuildBullet4")}})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-emerald-100 flex items-center justify-center shrink-0",children:e.jsx(xt,{size:H.lg,className:"text-emerald-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.semanticSearchLabel")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.semSearchDescShort")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.semSearchBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.semSearchBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.semSearchBullet3")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.semSearchBullet4")}})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-purple-100 flex items-center justify-center shrink-0",children:e.jsx(Ve,{size:H.lg,className:"text-purple-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.guardCompliance")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.guardComplianceDesc")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditFeatureBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditFeatureBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditFeatureBullet3")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditFeatureBullet4")}})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-amber-100 flex items-center justify-center shrink-0",children:e.jsx(ha,{size:H.lg,className:"text-amber-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.featureTaskGraphTitle")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.featureTaskGraphDesc")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.featureTaskGraphBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.featureTaskGraphBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.featureTaskGraphBullet3")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.featureTaskGraphBullet4")}})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-rose-100 flex items-center justify-center shrink-0",children:e.jsx(pt,{size:H.lg,className:"text-rose-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.wikiDocGen")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.wikiDocGenDesc")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.wikiDocBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.wikiDocBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.wikiDocBullet3")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.wikiDocBullet4")}})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-teal-100 flex items-center justify-center shrink-0",children:e.jsx(at,{size:H.lg,className:"text-teal-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.dataSync")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.syncDescShort")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.syncBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.syncBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.syncBullet3")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.syncBullet4")}})]})]})]})]}),e.jsxs(ht,{id:"editor-directives",title:t("help.editorDirectives"),icon:e.jsx(Rs,{size:H.xl,className:"text-blue-600"}),isExpanded:s.has("editor-directives"),onToggle:r,children:[e.jsx("p",{className:"text-[var(--fg-secondary)] text-sm mb-4",children:t("help.editorDirectivesNote")}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-lg p-4 border border-[var(--border-default)]",children:[e.jsxs("h4",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:[e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"// as:create"})," · ",e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"asc"})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-sm mb-2",children:t("help.createDirective")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.createDirBullet1")}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.createDirBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.createDirBullet3")}})]})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-lg p-4 border border-[var(--border-default)]",children:[e.jsxs("h4",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:[e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"// as:search"})," · ",e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"ass"})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-sm mb-2",children:t("help.searchDirective")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.searchDirBullet1")}),e.jsx("li",{children:t("help.searchDirBullet2")}),e.jsx("li",{children:t("help.searchDirBullet3")})]})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-lg p-4 border border-[var(--border-default)]",children:[e.jsxs("h4",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:[e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"// as:audit"})," · ",e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"asa"})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-sm mb-2",children:t("help.auditDirective")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.auditDirBullet1")}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditDirBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditDirBullet3")}})]})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-lg p-4 border border-[var(--border-default)]",children:[e.jsxs("h4",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:[e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"// as:include"})," · ",e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"// as:import"})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-sm mb-2",children:t("help.includeDirective")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.includeDirBullet1")}),e.jsx("li",{children:t("help.includeDirBullet2")})]})]})]})]}),e.jsxs(ht,{id:"cursor-integration",title:t("help.cursorIntegration"),icon:e.jsx(ut,{size:H.xl,className:"text-blue-600"}),isExpanded:s.has("cursor-integration"),onToggle:r,children:[e.jsxs("div",{className:"mb-5",children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-3",children:t("help.skills10")}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-2",children:[{name:"intent",descKey:"help.skillIntent"},{name:"concepts",descKey:"help.skillConcepts"},{name:"candidates",descKey:"help.skillCandidates"},{name:"recipes",descKey:"help.skillRecipes"},{name:"guard",descKey:"help.skillGuard"},{name:"structure",descKey:"help.skillStructure"},{name:"analysis",descKey:"help.skillAnalysis"},{name:"coldstart",descKey:"help.skillColdstart"},{name:"create",descKey:"help.skillCreate"},{name:"lifecycle",descKey:"help.skillLifecycle"},{name:"devdocs",descKey:"help.skillDevdocs"}].map(o=>e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-lg px-3 py-2 text-center",children:[e.jsx("p",{className:"text-xs font-mono text-blue-600",children:o.name}),e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] mt-0.5",children:t(o.descKey)})]},o.name))})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-3",children:t("help.mcp16")}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full border border-[var(--border-default)] rounded-lg text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-[var(--bg-subtle)]",children:[e.jsx("th",{className:"px-3 py-2 border-b text-left",children:t("help.mcpLayerHeader")}),e.jsx("th",{className:"px-3 py-2 border-b text-left",children:t("help.mcpToolHeader")}),e.jsx("th",{className:"px-3 py-2 border-b text-left",children:t("help.mcpDescHeader")})]})}),e.jsxs("tbody",{children:[e.jsx("tr",{className:"bg-blue-50/30",children:e.jsx("td",{colSpan:3,className:"px-3 py-1.5 border-b font-semibold text-blue-700 text-xs",children:t("help.mcpAgentLayerHeader")})}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"health"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpHealthDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"capabilities"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpCapabilitiesDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"search"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpSearchDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"knowledge"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpKnowledgeDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"structure"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpStructureDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"graph"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpGraphDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"call_context"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpCallContextDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"guard"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpGuardDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsxs("td",{className:"px-3 py-2 border-b",children:[e.jsx("code",{children:"submit_knowledge"})," / ",e.jsx("code",{children:"submit_knowledge_batch"})," / ",e.jsx("code",{children:"save_document"})]}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpSubmitDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"skill"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpSkillDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"bootstrap"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpBootstrapDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"dimension_complete"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpDimensionCompleteDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsxs("td",{className:"px-3 py-2 border-b",children:[e.jsx("code",{children:"wiki_plan"})," / ",e.jsx("code",{children:"wiki_finalize"})]}),e.jsxs("td",{className:"px-3 py-2 border-b",children:[t("help.mcpWikiPlanDesc")," · ",t("help.mcpWikiFinalizeDesc")]})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"task"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpTaskDesc")})]}),e.jsx("tr",{className:"bg-amber-50/30",children:e.jsx("td",{colSpan:3,className:"px-3 py-1.5 border-b font-semibold text-amber-700 text-xs",children:t("help.mcpAdminLayerHeader")})}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"admin"}),e.jsxs("td",{className:"px-3 py-2 border-b",children:[e.jsx("code",{children:"enrich_candidates"})," / ",e.jsx("code",{children:"validate_candidate"})," / ",e.jsx("code",{children:"check_duplicate"})]}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpEnrichDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-medium",children:"admin"}),e.jsx("td",{className:"px-3 py-2",children:e.jsx("code",{children:"knowledge_lifecycle"})}),e.jsx("td",{className:"px-3 py-2",children:t("help.mcpLifecycleDesc")})]})]})]})}),e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] mt-2",children:t("help.mcpWriteNote")})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-3",children:t("help.usageExamples")}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"bg-blue-50 rounded p-3 border border-blue-200",children:[e.jsx("p",{className:"font-medium text-blue-900 text-sm mb-1",children:t("help.exampleSearchKB")}),e.jsx("p",{className:"text-blue-800 text-xs",children:t("help.exampleSearchKBDesc")})]}),e.jsxs("div",{className:"bg-green-50 rounded p-3 border border-green-200",children:[e.jsx("p",{className:"font-medium text-green-900 text-sm mb-1",children:t("help.exampleBatchScan")}),e.jsx("p",{className:"text-green-800 text-xs",children:t("help.exampleBatchScanDesc")})]}),e.jsxs("div",{className:"bg-purple-50 rounded p-3 border border-purple-200",children:[e.jsx("p",{className:"font-medium text-purple-900 text-sm mb-1",children:t("help.exampleSubmitCode")}),e.jsx("p",{className:"text-purple-800 text-xs",children:t("help.exampleSubmitCodeDesc")})]})]})]}),e.jsxs("div",{className:"mt-5",children:[e.jsxs("h3",{className:"font-semibold text-[var(--fg-primary)] mb-3 flex items-center gap-2",children:[e.jsx(ba,{size:H.lg,className:"text-blue-600"}),t("help.vscodeExtension")]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-sm mb-3",children:t("help.vscodeExtDesc")}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3 mb-3",children:[e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-lg p-3",children:[e.jsx("h4",{className:"font-semibold text-[var(--fg-primary)] text-sm mb-1",children:t("help.vscodeExtTaskTool")}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.vscodeExtTaskToolDesc")})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-lg p-3",children:[e.jsx("h4",{className:"font-semibold text-[var(--fg-primary)] text-sm mb-1",children:t("help.vscodeExtGuardDiag")}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.vscodeExtGuardDiagDesc")})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-lg p-3",children:[e.jsx("h4",{className:"font-semibold text-[var(--fg-primary)] text-sm mb-1",children:t("help.vscodeExtCodeLens")}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.vscodeExtCodeLensDesc")})]})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-lg p-3",children:[e.jsx("h4",{className:"font-semibold text-[var(--fg-primary)] text-sm mb-2",children:"Commands"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-1 text-xs text-[var(--fg-secondary)]",children:[e.jsx("p",{children:t("help.vscodeExtCmd1")}),e.jsx("p",{children:t("help.vscodeExtCmd2")}),e.jsx("p",{children:t("help.vscodeExtCmd3")}),e.jsx("p",{children:t("help.vscodeExtCmd4")}),e.jsx("p",{children:t("help.vscodeExtCmd5")})]})]})]})]}),e.jsx(ht,{id:"cli-reference",title:t("help.cliReference"),icon:e.jsx(Rs,{size:H.xl,className:"text-blue-600"}),isExpanded:s.has("cli-reference"),onToggle:r,children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:t("help.initAndEnv")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd setup"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliSetupDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd status"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliStatusDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd ui"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliUiDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd upgrade"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliUpgradeDesc")})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:t("help.kbManagement")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd sync"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliSyncDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd ais [Target]"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliAisDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd watch"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliWatchDesc")})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:t("help.cliColdstartAndScan")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd coldstart"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliColdstartDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd cursor-rules"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliCursorRulesDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd mirror"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliMirrorDesc")})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:t("help.searchAndAudit")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd search <query>"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliSearchDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd guard <file>"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliGuardDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd guard:ci"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliGuardCiDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd guard:staged"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliGuardStagedDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd server"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliServerDesc")})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:t("help.cliTaskManagement")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd task list"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliTaskListDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd task ready"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliTaskReadyDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd task prime"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliTaskPrimeDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd task stats"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliTaskStatsDesc")})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:t("help.maintenanceUpgrade")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd upgrade"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliUpgradeMcpDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd sync --force"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliSyncForceDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd sync --dry-run"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliSyncDryDesc")})]})]})]})]})})]}),e.jsx("div",{className:"mt-8 p-4 bg-blue-50 border border-blue-200 rounded-lg text-center",children:e.jsx("p",{className:"text-[var(--fg-primary)] text-sm",dangerouslySetInnerHTML:{__html:t("help.footerHint",{link:`<a href="https://github.com/GxFn/AutoSnippet" target="_blank" rel="noopener noreferrer" class="text-blue-600 hover:underline font-medium">${t("help.footerGithubReadme")}</a>`,cmd:'<code class="bg-blue-100 px-1.5 py-0.5 rounded text-xs">asd status</code>'})}})})]})};function Ti(){const[t,s]=n.useState(null);n.useEffect(()=>{const l=Cs(),i=h=>{s({status:"running",total:h.total,current:0,progress:0,refined:0,failed:0,items:h.candidateIds.map(u=>({candidateId:u,title:"",status:"pending"}))})},p=h=>{s(u=>u&&{...u,current:h.current,progress:h.progress,items:u.items.map(m=>m.candidateId===h.candidateId?{...m,title:h.title,status:"refining"}:m)})},d=h=>{s(u=>u&&{...u,current:h.current,progress:h.progress,refined:h.refinedSoFar,items:u.items.map(m=>m.candidateId===h.candidateId?{...m,title:h.title,status:"done",refined:h.refined}:m)})},g=h=>{s(u=>u&&{...u,current:h.current,progress:h.progress,failed:u.failed+1,items:u.items.map(m=>m.candidateId===h.candidateId?{...m,title:h.title,status:"failed",error:h.error}:m)})},x=h=>{s(u=>u&&{...u,status:"completed",progress:100,refined:h.refined,failed:h.failed})};return l.on("refine:started",i),l.on("refine:item-started",p),l.on("refine:item-completed",d),l.on("refine:item-failed",g),l.on("refine:completed",x),()=>{l.off("refine:started",i),l.off("refine:item-started",p),l.off("refine:item-completed",d),l.off("refine:item-failed",g),l.off("refine:completed",x)}},[]);const a=n.useCallback(()=>s(null),[]),r=t?.status==="running",o=t?.status==="completed";return{refine:t,isRefining:r,isRefineDone:o,resetRefine:a}}const Ei=({refine:t,isRefineDone:s,onDismiss:a})=>{const{t:r}=Ae(),o=n.useRef(!1);if(n.useEffect(()=>{if(s&&t&&!o.current){o.current=!0;const p=t.failed>0?r("refineProgress.doneMsgWithFail",{refined:String(t.refined),failed:String(t.failed)}):r("refineProgress.doneMsg",{refined:String(t.refined)});ne(p,{title:r("refineProgress.doneTitle"),type:t.failed>0?"error":"success"})}},[s,t]),n.useEffect(()=>{t||(o.current=!1)},[t]),!t)return null;const l=t.items.find(p=>p.status==="refining"),i=t.items.filter(p=>p.status==="done"||p.status==="failed").length;return e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-4 mb-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`p-1.5 rounded-lg ${s?"bg-emerald-50":"bg-blue-50"}`,children:s?e.jsx(ot,{className:"w-4 h-4 text-emerald-600"}):e.jsx(Le,{className:"w-4 h-4 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-slate-800",children:r(s?"refineProgress.doneTitle":"refineProgress.runningTitle")}),e.jsxs("p",{className:"text-xs text-slate-500",children:[s?t.failed>0?r("refineProgress.doneMsgWithFail",{refined:String(t.refined),failed:String(t.failed)}):r("refineProgress.doneMsg",{refined:String(t.refined)}):r("refineProgress.progressMsg",{done:String(i),total:String(t.total)}),l&&!s&&e.jsxs("span",{className:"ml-2 text-blue-600",children:[e.jsx(Ne,{className:"w-3 h-3 inline animate-spin mr-1"}),l.title||l.candidateId.slice(0,8)]})]})]})]}),s&&a&&e.jsx("button",{onClick:a,className:"text-xs px-2.5 py-1 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-600 transition-colors",children:r("refineProgress.closeBtn")})]}),e.jsx("div",{className:"w-full h-1.5 bg-slate-100 rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full transition-all duration-500 ease-out ${s?t.failed>0?"bg-amber-400":"bg-emerald-500":"bg-blue-500"}`,style:{width:`${t.progress}%`}})}),s&&t.failed>0&&e.jsxs("div",{className:"mt-2 text-xs text-red-500 flex items-center gap-1",children:[e.jsx(ze,{className:"w-3 h-3"}),t.items.filter(p=>p.status==="failed").map(p=>p.title||p.candidateId.slice(0,8)).join("、")]})]})},ls={_watch:"silentLabels.watch",_draft:"silentLabels.draft",_cli:"silentLabels.cli",_pending:"silentLabels.pending",_recipe:"silentLabels.recipe"},os={architecture:"bootstrap.dimLabels.architecture","coding-standards":"bootstrap.dimLabels.codingStandards","design-patterns":"bootstrap.dimLabels.designPatterns","error-resilience":"bootstrap.dimLabels.errorResilience","concurrency-async":"bootstrap.dimLabels.concurrencyAsync","data-event-flow":"bootstrap.dimLabels.dataEventFlow","networking-api":"bootstrap.dimLabels.networkingApi","ui-interaction":"bootstrap.dimLabels.uiInteraction","testing-quality":"bootstrap.dimLabels.testingQuality","security-auth":"bootstrap.dimLabels.securityAuth","performance-optimization":"bootstrap.dimLabels.performanceOptimization","observability-logging":"bootstrap.dimLabels.observabilityLogging","agent-guidelines":"bootstrap.dimLabels.agentGuidelines","swift-objc-idiom":"bootstrap.dimLabels.swiftObjcIdiom","ts-js-module":"bootstrap.dimLabels.tsJsModule","python-structure":"bootstrap.dimLabels.pythonStructure","jvm-annotation":"bootstrap.dimLabels.jvmAnnotation","go-module":"bootstrap.dimLabels.goModule","rust-ownership":"bootstrap.dimLabels.rustOwnership","csharp-dotnet":"bootstrap.dimLabels.csharpDotnet","react-patterns":"bootstrap.dimLabels.reactPatterns","vue-patterns":"bootstrap.dimLabels.vuePatterns","spring-patterns":"bootstrap.dimLabels.springPatterns","swiftui-patterns":"bootstrap.dimLabels.swiftuiPatterns","django-fastapi":"bootstrap.dimLabels.djangoFastapi",bootstrap:"bootstrap.dimLabels.bootstrap"};function Pi(t,s,a,r){return[...t].sort(([o],[l])=>{const i=r(o),p=r(l);if(i&&!p)return 1;if(!i&&p)return-1;const d=a(o),g=a(l);if(d&&!g)return-1;if(!d&&g)return 1;const x=s(o),h=s(l);return x&&!h?1:!x&&h?-1:o.localeCompare(l)})}function Bt(t,s){if(!t)return"";const a=typeof t=="number"?t:Number(t),r=a<1e12?a*1e3:a,o=new Date(r);if(isNaN(o.getTime())||o.getFullYear()<2e3)return"";const i=new Date().getTime()-o.getTime();if(i<0)return o.toLocaleDateString();const p=Math.floor(i/6e4);if(p<1)return s("candidates.timeJustNow");if(p<60)return s("candidates.timeMinutesAgo",{n:p});const d=Math.floor(p/60);if(d<24)return s("candidates.timeHoursAgo",{n:d});const g=Math.floor(d/24);return g<7?s("candidates.timeDaysAgo",{n:g}):o.toLocaleDateString()}function Mi(t,s=4){return t?la(t).split(`
`).slice(0,s).join(`
`):""}function Li(t){return t==null?{ring:"stroke-slate-200",text:"text-[var(--fg-muted)]",bg:"bg-[var(--bg-subtle)]",labelKey:""}:t>=.8?{ring:"stroke-emerald-500",text:"text-emerald-600 dark:text-emerald-400",bg:"bg-emerald-500/10",labelKey:"candidates.confidenceHighLabel"}:t>=.6?{ring:"stroke-blue-500",text:"text-blue-600 dark:text-blue-400",bg:"bg-blue-500/10",labelKey:"candidates.confidenceMediumLabel"}:t>=.4?{ring:"stroke-amber-500",text:"text-amber-600 dark:text-amber-400",bg:"bg-amber-500/10",labelKey:"candidates.confidenceMediumLowLabel"}:{ring:"stroke-red-500",text:"text-red-600 dark:text-red-400",bg:"bg-red-500/10",labelKey:"candidates.confidenceLowLabel"}}const Ta={"bootstrap-scan":{labelKey:"candidates.sourceAiScanLabel",color:"text-violet-600 dark:text-violet-400 bg-violet-500/10 border-violet-500/20"},mcp:{labelKey:"candidates.sourceMcpLabel",color:"text-blue-600 dark:text-blue-400 bg-blue-500/10 border-blue-500/20"},manual:{labelKey:"candidates.sourceManualLabel",color:"text-emerald-600 dark:text-emerald-400 bg-emerald-500/10 border-emerald-500/20"},"file-watcher":{labelKey:"candidates.sourceFileWatcherLabel",color:"text-orange-600 dark:text-orange-400 bg-orange-500/10 border-orange-500/20"},clipboard:{labelKey:"candidates.sourceClipboardLabel",color:"text-pink-600 dark:text-pink-400 bg-pink-500/10 border-pink-500/20"},cli:{labelKey:"CLI",color:"text-[var(--fg-secondary)] bg-[var(--bg-subtle)] border-[var(--border-default)]"},agent:{labelKey:"AI Agent",color:"text-violet-600 dark:text-violet-400 bg-violet-500/10 border-violet-500/20"},submit_with_check:{labelKey:"candidates.sourceSubmitCheckLabel",color:"text-teal-600 dark:text-teal-400 bg-teal-500/10 border-teal-500/20"},"bootstrap-fallback":{labelKey:"candidates.sourceFallbackLabel",color:"text-amber-600 dark:text-amber-400 bg-amber-500/10 border-amber-500/20"}},_i=({value:t,size:s=36})=>{const a=(s-6)/2,r=2*Math.PI*a,o=t!=null?Math.max(0,Math.min(1,t)):0,l=r*(1-o),{ring:i,text:p}=Li(t);return e.jsxs("div",{className:"relative flex items-center justify-center",style:{width:s,height:s},children:[e.jsxs("svg",{width:s,height:s,className:"-rotate-90",children:[e.jsx("circle",{cx:s/2,cy:s/2,r:a,fill:"none",stroke:"currentColor",strokeWidth:3,className:"text-[var(--border-default)]"}),e.jsx("circle",{cx:s/2,cy:s/2,r:a,fill:"none",strokeWidth:3,strokeLinecap:"round",className:i,strokeDasharray:r,strokeDashoffset:l,style:{transition:"stroke-dashoffset 0.5s ease"}})]}),e.jsx("span",{className:`absolute text-[9px] font-bold ${p}`,children:t!=null?`${Math.round(t*100)}`:"—"})]})},Fi=({data:t,isShellTarget:s,isSilentTarget:a=()=>!1,isPendingTarget:r=()=>!1,handleDeleteCandidate:o,handleDeleteAllInTarget:l,onAuditCandidate:i,onAuditAllInTarget:p,onEditRecipe:d,onColdStart:g,onRescan:x,isScanning:h,isBootstrapping:u,onRefresh:m})=>{const{t:c}=Ae(),[j,S]=n.useState(null),{isWide:D,toggle:I}=ia(),[P,Y]=n.useState(new Set),[w]=n.useState(new Set),[G,_]=n.useState(!1),[N]=n.useState(!1),E=Zt(),{refine:L,isRefining:$,isRefineDone:U,resetRefine:q}=Ti(),[A,y]=n.useState({}),[W,re]=n.useState(null),[he,ue]=n.useState({}),[V,B]=n.useState({sort:"score-desc"}),oe=t?.candidates?Object.entries(t.candidates):[],me=Pi(oe,s,a,r),R=me.map(([te])=>te),T=!!(t?.recipes&&t.recipes.length>0),ee=oe.length>0,ie=T||ee,xe=W&&R.includes(W)?W:R[0]??null;n.useEffect(()=>{R.length>0&&(!W||!R.includes(W))&&re(R[0])},[R.join(","),W]);const pe=n.useMemo(()=>{if(!t?.candidates)return null;let te=0,de=0,f=0;for(const ge of Object.values(t.candidates))for(const ve of ge.items)te++,de+=ve.reasoning?.confidence??0,(ve.content?.pattern&&ve.content.pattern.trim().length>0||ve.coreCode&&ve.coreCode.trim().length>0)&&f++;const J=te>0?de/te:0;return{total:te,avgConfidence:J,withCode:f}},[t?.candidates]),M=n.useMemo(()=>{if(!xe||!t?.candidates?.[xe])return null;const te=t.candidates[xe].items,de=te.length,f=te.reduce((ve,k)=>ve+(k.reasoning?.confidence??0),0)/(de||1),J=te.filter(ve=>ve.content?.pattern&&ve.content.pattern.trim().length>0||ve.coreCode&&ve.coreCode.trim().length>0).length,ge=new Map;return te.forEach(ve=>{const k=ve.source||"unknown";ge.set(k,(ge.get(k)||0)+1)}),{total:de,avgConfidence:f,withCode:J,sources:ge}},[xe,t?.candidates]),Ce=n.useMemo(()=>{const te=new Map;if(t?.idTitleMap)for(const[de,f]of Object.entries(t.idTitleMap))te.set(de,f);if(t?.candidates)for(const de of Object.values(t.candidates))for(const f of de.items)f.id&&f.title&&te.set(f.id,f.title);if(t?.recipes)for(const de of t.recipes)de.id&&de.name&&te.set(de.id,de.name.replace(/\.md$/i,""));return te},[t?.idTitleMap,t?.candidates,t?.recipes]),F=n.useCallback(async te=>{if(!P.has(te)){Y(de=>new Set(de).add(te));try{const de=await Z.enrichCandidates([te]);de.enriched>0?ne(`${de.results?.[0]?.filledFields?.length||0} ${c("candidates.approveSuccess")}`,{title:c("candidates.aiRefine")}):ne(c("recipes.noContent"),{title:c("candidates.aiRefine"),type:"info"});try{const f=await Z.getCandidate(te);ue(J=>({...J,[te]:f}))}catch{}}catch(de){ne(ke(de,c("common.operationFailed")),{title:c("common.operationFailed"),type:"error"})}finally{Y(de=>{const f=new Set(de);return f.delete(te),f})}}},[P,m]),Se=n.useCallback(async()=>{if(G||!xe||!t?.candidates?.[xe])return;const te=t.candidates[xe].items;if(te.length!==0){_(!0);try{let de=0;for(let f=0;f<te.length;f+=20){const J=te.slice(f,f+20).map(ve=>ve.id),ge=await Z.enrichCandidates(J);de+=ge.enriched}ne(`${de}/${te.length} ${c("candidates.batchDeleteDone",{count:de})}`,{title:c("candidates.aiRefine")}),m?.()}catch(de){ne(ke(de,c("common.operationFailed")),{title:c("common.operationFailed"),type:"error"})}finally{_(!1)}}},[G,xe,t?.candidates,m]),Te=n.useCallback(async te=>{try{const de=await Z.getCandidate(te);ue(f=>({...f,[te]:de}))}catch{}},[]),_e=n.useCallback(()=>{if(!xe||!t?.candidates?.[xe])return;const te=t.candidates[xe].items,de=te.map(f=>f.id);E.openRefine({candidateIds:de,candidates:te,onCandidateUpdated:Te})},[xe,t?.candidates,E,Te]),Me=n.useCallback(te=>{if(!xe||!t?.candidates?.[xe])return;S(te);const de=t.candidates[xe].items;E.openRefine({candidateIds:[te],candidates:de,onCandidateUpdated:Te})},[xe,t?.candidates,E,Te]);return e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"mb-4 flex flex-wrap justify-between items-center gap-3 shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-500/10 border border-blue-500/20 flex items-center justify-center shrink-0",children:e.jsx(hs,{className:"text-blue-600",size:20})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-lg xl:text-xl font-bold text-[var(--fg-primary)]",children:"AI Scan Candidates"}),e.jsx("p",{className:"text-xs text-[var(--fg-muted)] mt-0.5 truncate",children:c("candidates.title")})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[!u&&e.jsx(e.Fragment,{children:ie?x&&ee&&e.jsxs("button",{onClick:x,disabled:h,className:`flex items-center gap-1.5 px-3.5 py-2 rounded-lg text-xs font-bold transition-all ${h?"text-[var(--fg-muted)] bg-[var(--bg-subtle)] cursor-not-allowed":"text-blue-600 dark:text-blue-400 bg-blue-500/10 border border-blue-500/20 hover:bg-blue-500/20"}`,title:c("candidates.rescanTitle"),children:[h?e.jsx(Ne,{size:14,className:"animate-spin"}):e.jsx(at,{size:14}),c(h?"common.loading":"candidates.rescanBtn")]}):g&&e.jsxs("button",{onClick:g,disabled:h,className:`flex items-center gap-1.5 px-3.5 py-2 rounded-lg text-xs font-bold transition-all ${h?"text-[var(--fg-muted)] bg-[var(--bg-subtle)] cursor-not-allowed":"text-violet-600 dark:text-violet-400 bg-violet-500/10 border border-violet-500/20 hover:bg-violet-500/20"}`,title:c("candidates.coldStartTitle"),children:[h?e.jsx(Ne,{size:14,className:"animate-spin"}):e.jsx(Kt,{size:14}),c(h?"common.loading":"candidates.sourceBootstrap")]})}),M&&M.total>0&&e.jsxs("button",{onClick:Se,disabled:G||N,className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-all ${G||N?"text-[var(--fg-muted)] bg-[var(--bg-subtle)] cursor-not-allowed":"text-amber-600 dark:text-amber-400 bg-amber-500/10 border border-amber-500/20 hover:bg-amber-500/20"}`,title:c("candidates.enrichTitle"),children:[G?e.jsx(Ne,{size:14,className:"animate-spin"}):e.jsx(us,{size:14}),c(G?"common.loading":"candidates.aiEnrich")]}),M&&M.total>0&&e.jsxs("button",{onClick:_e,disabled:N||G||$,className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-all ${N||G||$?"text-[var(--fg-muted)] bg-[var(--bg-subtle)] cursor-not-allowed":"text-emerald-600 dark:text-emerald-400 bg-emerald-500/10 border border-emerald-500/20 hover:bg-emerald-500/20"}`,title:c("candidates.refineTitle"),children:[N||$?e.jsx(Ne,{size:14,className:"animate-spin"}):e.jsx(Le,{size:14}),c(N||$?"common.loading":"candidates.aiRefine")]}),pe&&e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-[var(--bg-subtle)] border border-[var(--border-default)]",children:[e.jsx(Tt,{size:14,className:"text-[var(--fg-muted)]"}),e.jsx("span",{className:"text-[var(--fg-secondary)]",children:c("candidates.totalCount",{count:pe.total})})]}),e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-emerald-500/10 border border-emerald-500/20",children:[e.jsx("span",{className:"text-emerald-500",children:c("candidates.confidence")}),e.jsxs("strong",{className:"text-emerald-700",children:[Math.round(pe.avgConfidence*100),"%"]})]})]}),!u&&g&&ie&&e.jsxs("button",{onClick:g,disabled:h,className:`ml-auto flex items-center gap-1 px-2.5 py-1.5 rounded-md text-[11px] transition-all ${h?"text-[var(--fg-muted)] cursor-not-allowed":"text-[var(--fg-muted)] hover:text-red-600 hover:bg-red-50"}`,title:c("candidates.cleanRebuildTitle"),children:[h?e.jsx(Ne,{size:12,className:"animate-spin"}):e.jsx(qe,{size:12}),c("candidates.cleanRebuildBtn")]})]})]}),L&&e.jsx(Ei,{refine:L,isRefineDone:U,onDismiss:()=>{q(),m?.()}}),oe.length>0&&e.jsx("div",{className:"shrink-0 bg-[var(--bg-surface)] border border-[var(--border-default)] rounded-xl px-3 py-2 mb-3 shadow-sm",children:e.jsx("div",{className:"flex items-center gap-1.5 flex-wrap",children:R.map(te=>{const de=a(te),f=ls[te]?c(ls[te]):void 0,ge=t?.candidates[te]?.items?.length??0,ve=xe===te,k=et[te]||et.All;return e.jsxs("button",{onClick:()=>re(te),className:`flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-bold whitespace-nowrap transition-all border
                    ${ve?`bg-[var(--bg-surface)] ${k?.color||"text-blue-600"} border-[var(--border-emphasis)] shadow-sm ring-1 ring-inset ring-[var(--border-emphasis)]`:"bg-[var(--bg-subtle)] text-[var(--fg-secondary)] border-[var(--border-default)] hover:border-[var(--border-emphasis)] hover:bg-[var(--bg-subtle)]"}`,children:[(()=>{const b=k?.icon||gs;return e.jsx(b,{size:H.sm,className:ve?"":"text-[var(--fg-muted)]"})})(),e.jsx("span",{children:os[te]?c(os[te]):te}),de&&f&&e.jsx("span",{className:"text-[9px] text-amber-600 dark:text-amber-400 border border-amber-200 dark:border-amber-700 px-1 rounded",children:f}),e.jsx("span",{className:`text-[10px] font-normal rounded-full px-1.5 ${ve?"bg-[var(--bg-subtle)]":"bg-[var(--bg-subtle)] text-[var(--fg-muted)]"}`,children:ge})]},te)})})}),e.jsxs("div",{className:"flex-1 overflow-y-auto pr-1 pb-6",children:[(!t?.candidates||Object.keys(t.candidates).length===0)&&!u&&e.jsxs("div",{className:"h-72 flex flex-col items-center justify-center bg-[var(--bg-surface)] rounded-2xl border border-dashed border-[var(--border-default)] text-[var(--fg-muted)]",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-[var(--bg-subtle)] flex items-center justify-center mb-4",children:e.jsx(hs,{size:32,className:"text-[var(--fg-muted)]"})}),e.jsx("p",{className:"text-sm font-medium text-[var(--fg-secondary)]",children:c("candidates.noResults")}),e.jsx("p",{className:"mt-2 text-xs max-w-sm text-center leading-relaxed text-[var(--fg-muted)]",children:c("candidates.emptyHint")}),ie?e.jsxs(e.Fragment,{children:[x&&e.jsxs("button",{onClick:x,disabled:h,className:`mt-4 flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${h?"text-[var(--fg-muted)] bg-[var(--bg-subtle)] cursor-not-allowed":"text-blue-600 dark:text-blue-400 bg-blue-500/10 border border-blue-500/20 hover:bg-blue-500/20"}`,children:[h?e.jsx(Ne,{size:16,className:"animate-spin"}):e.jsx(at,{size:16}),c(h?"common.loading":"candidates.rescanBtn")]}),e.jsx("p",{className:"mt-3 text-[11px] text-[var(--fg-muted)]",children:c("candidates.rescanHint")})]}):e.jsxs(e.Fragment,{children:[g&&e.jsxs("button",{onClick:g,disabled:h,className:`mt-4 flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${h?"text-[var(--fg-muted)] bg-[var(--bg-subtle)] cursor-not-allowed":"text-violet-600 dark:text-violet-400 bg-violet-500/10 border border-violet-500/20 hover:bg-violet-500/20"}`,children:[h?e.jsx(Ne,{size:16,className:"animate-spin"}):e.jsx(Kt,{size:16}),c(h?"common.loading":"candidates.sourceBootstrap")]}),e.jsx("p",{className:"mt-3 text-[11px] text-[var(--fg-muted)]",children:c("candidates.emptyHintIde")})]})]}),(!t?.candidates||Object.keys(t.candidates).length===0)&&u&&e.jsxs("div",{className:"h-72 flex flex-col items-center justify-center bg-[var(--bg-surface)] rounded-2xl border border-dashed border-violet-500/30 text-[var(--fg-muted)]",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-violet-500/10 flex items-center justify-center mb-4",children:e.jsx(Ne,{size:32,className:"text-violet-400 animate-spin"})}),e.jsx("p",{className:"text-sm font-medium text-violet-400",children:c("common.loading")}),e.jsx("p",{className:"mt-2 text-xs text-center leading-relaxed text-[var(--fg-muted)]",children:c("candidates.scanningHint")})]}),t&&xe&&me.filter(([te])=>te===xe).map(([te,de])=>{const f=s(te),J=a(te),ge=ls[te]?c(ls[te]):c("candidates.silent"),ve=A[te]||{page:1,pageSize:12},k=ve.page,b=ve.pageSize,z=de.items.sort((ae,we)=>V.sort==="default"?0:V.sort==="score-desc"?(we.quality?.overall??0)-(ae.quality?.overall??0):V.sort==="score-asc"?(ae.quality?.overall??0)-(we.quality?.overall??0):V.sort==="confidence-desc"?(we.reasoning?.confidence??0)-(ae.reasoning?.confidence??0):0),le=z.length,O=Math.ceil(le/b),v=(k-1)*b,se=z.slice(v,v+b),be=ae=>{y(we=>({...we,[te]:{...ve,page:ae}}))},fe=ae=>{y(we=>({...we,[te]:{page:1,pageSize:ae}}))},De=et[te]||et.All;return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 rounded-xl bg-[var(--bg-surface)] border border-[var(--border-default)] shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[(()=>{const ae=De?.icon||gs;return e.jsx(ae,{size:18,className:De?.color||"text-blue-600"})})(),e.jsx("span",{className:"text-base font-bold text-[var(--fg-primary)] truncate",children:os[te]?c(os[te]):te}),J&&e.jsx("span",{className:"text-[10px] font-bold text-amber-600 dark:text-amber-400 border border-amber-500/20 bg-amber-500/10 px-1.5 py-0.5 rounded",children:ge}),f&&!J&&e.jsx("span",{className:"text-[10px] font-bold text-[var(--fg-muted)] border border-[var(--border-default)] bg-[var(--bg-subtle)] px-1.5 py-0.5 rounded",children:"SHELL"}),e.jsxs("span",{className:"text-[11px] text-[var(--fg-muted)] flex items-center gap-1",children:[e.jsx(Ye,{size:11}),c("candidates.scannedAt",{time:Bt(de.scanTime,c)||new Date(de.scanTime).toLocaleString()})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 rounded-lg bg-[var(--bg-subtle)] border border-[var(--border-default)]",children:[e.jsx(xl,{size:12,className:"text-[var(--fg-muted)]"}),e.jsx(tt,{value:V.sort,onChange:ae=>B(we=>({...we,sort:ae})),options:[{value:"score-desc",label:`${c("candidates.sortScore")} ↓`},{value:"score-asc",label:`${c("candidates.sortScore")} ↑`},{value:"confidence-desc",label:`${c("candidates.sortConfidence")} ↓`},{value:"default",label:c("candidates.sortDefault")}],size:"xs",className:"border-none bg-transparent"})]}),e.jsx("div",{className:"h-4 w-px bg-[var(--border-default)]"}),e.jsx("button",{onClick:()=>p(se,te),className:"text-[11px] font-bold text-blue-600 dark:text-blue-400 hover:text-blue-700 px-2.5 py-1.5 rounded-lg hover:bg-blue-500/10 transition-colors",children:c("candidates.approveCurrentPage")})]}),e.jsx("div",{className:"h-5 w-px bg-[var(--border-default)]"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[11px] text-[var(--fg-muted)] font-medium",children:c("candidates.totalCount",{count:le})}),le>0&&e.jsxs("span",{className:"text-[11px] text-emerald-600 font-medium ml-1.5 pl-2 border-l border-[var(--border-default)]",children:[c("candidates.confidence")," ",Math.round(de.items.reduce((ae,we)=>ae+(we.reasoning?.confidence??0),0)/le*100),"%"]})]}),e.jsx("div",{className:"ml-auto",children:e.jsxs("button",{onClick:()=>l(te),className:"flex items-center gap-1 px-2.5 py-1.5 rounded-md text-[11px] transition-all text-[var(--fg-muted)] hover:text-red-600 hover:bg-red-50",title:c("candidates.deleteAll"),children:[e.jsx(qe,{size:12}),c("candidates.deleteAll")]})})]}),e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3 items-start",children:se.map(ae=>{const we=j===ae.id,Oe=ae.reasoning?.confidence??null,rt=(ae.quality?.overall??0)>0?ae.quality?.overall??null:null,ct=Ta[ae.source||""]||{labelKey:ae.source||"",color:"text-[var(--fg-secondary)] bg-[var(--bg-subtle)] border-[var(--border-default)]"},Xt=et[ae.category||""]||et.All||{};return e.jsxs("div",{onClick:()=>S(we?null:ae.id),className:`bg-[var(--bg-surface)] rounded-xl border overflow-hidden hover:shadow-lg transition-all duration-200 flex flex-col group cursor-pointer
                          ${f?"opacity-75":""}
                          ${we?"ring-2 ring-blue-300 border-blue-300 shadow-md":"border-[var(--border-default)] hover:border-[var(--border-emphasis)]"}`,children:[e.jsx("div",{className:"px-4 pt-3.5 pb-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mb-1.5",children:[e.jsxs("span",{className:`text-[10px] font-bold px-1.5 py-0.5 rounded uppercase flex items-center gap-1 border bg-[var(--bg-subtle)] ${Xt?.color||"text-[var(--fg-muted)]"} border-[var(--border-default)]`,children:[(()=>{const nt=Xt?.icon||Ge;return e.jsx(nt,{size:10})})(),ae.category||"general"]}),ae.knowledgeType&&e.jsx("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-indigo-500/10 text-indigo-600 dark:text-indigo-400 border border-indigo-500/20",children:ae.knowledgeType}),ae.source&&ae.source!=="unknown"&&e.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border ${ct.color}`,children:ct.labelKey.startsWith("candidates.")?c(ct.labelKey):ct.labelKey}),ae.complexity&&e.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border
                                    ${ae.complexity==="advanced"?"bg-violet-500/10 text-violet-600 dark:text-violet-400 border-violet-500/20":ae.complexity==="intermediate"?"bg-sky-500/10 text-sky-600 dark:text-sky-400 border-sky-500/20":"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20"}`,children:ae.complexity==="advanced"?c("knowledge.complexityAdvanced"):ae.complexity==="intermediate"?c("knowledge.complexityIntermediate"):c("knowledge.complexityBeginner")})]}),e.jsx("h3",{className:"font-bold text-sm text-[var(--fg-primary)] leading-snug mb-1 line-clamp-1",children:ae.title}),e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] line-clamp-2 leading-relaxed",children:ae.description||""})]}),e.jsxs("div",{className:"flex flex-col items-center gap-1 shrink-0",children:[e.jsx(_i,{value:Oe}),e.jsx("span",{className:"text-[9px] text-[var(--fg-muted)] font-medium",children:c("candidates.confidence")})]})]})}),ae.reasoning?.whyStandard&&!/^Submitted via /i.test(ae.reasoning.whyStandard)&&e.jsx("div",{className:"px-4 py-2 bg-gradient-to-r from-indigo-500/10 to-transparent border-t border-indigo-500/10",children:e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx(Mt,{size:12,className:"text-indigo-400 mt-0.5 shrink-0"}),e.jsx("p",{className:"text-[11px] text-indigo-600 dark:text-indigo-400 opacity-80 line-clamp-1 leading-relaxed",children:ae.reasoning.whyStandard})]})}),rt!=null&&e.jsx("div",{className:"flex flex-wrap items-center gap-1.5 px-4 py-2 border-t border-[var(--border-default)]",children:e.jsxs("span",{className:"text-[10px] font-bold px-2 py-0.5 rounded-full bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border border-emerald-500/20 flex items-center gap-1",children:[e.jsx(bt,{size:10}),c("candidates.overallScore",{score:(rt*100).toFixed(0)+"%"})]})}),ae.content?.pattern&&e.jsxs("div",{className:"overflow-hidden border-t border-[var(--border-default)]/60",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5",style:{background:"#282c34"},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(At,{size:11,className:"text-[var(--fg-secondary)]"}),e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] font-mono uppercase tracking-wide",children:ae.language||"code"})]}),e.jsx("span",{className:"text-[10px] text-[var(--fg-secondary)] font-mono tabular-nums",children:c("candidates.linesCount",{count:ae.content.pattern.split(`
`).length})})]}),e.jsxs("div",{className:"relative max-h-[80px] overflow-hidden",children:[e.jsx(vt,{code:Mi(ae.content.pattern,3),language:ae.language==="objc"?"objectivec":ae.language,className:"!rounded-none"}),ae.content.pattern.split(`
`).length>3&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-6 bg-gradient-to-t from-[#282c34] to-transparent pointer-events-none"})]})]}),e.jsxs("div",{className:"flex justify-between items-center px-4 py-2.5 border-t border-[var(--border-default)] bg-[var(--bg-subtle)] mt-auto",onClick:nt=>nt.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap min-w-0",children:[ae.trigger&&e.jsx("span",{className:"text-[10px] font-mono px-2 py-0.5 rounded-md bg-[var(--bg-surface)] border border-[var(--border-default)] text-[var(--fg-secondary)] font-bold",children:ae.trigger}),e.jsx("span",{className:"text-[10px] uppercase font-bold text-[var(--fg-muted)] bg-[var(--bg-surface)] border border-[var(--border-default)] px-1.5 py-0.5 rounded-md",children:ae.language}),ae.tags&&ae.tags.length>0&&ae.tags.slice(0,3).map((nt,Ss)=>e.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded-md bg-blue-500/10 text-blue-600 dark:text-blue-400 border border-blue-500/20 font-medium",children:typeof nt=="string"?nt:String(nt)},Ss)),ae.tags&&ae.tags.length>3&&e.jsxs("span",{className:"text-[9px] text-[var(--fg-muted)]",children:["+",ae.tags.length-3]}),ae.createdAt&&Bt(ae.createdAt,c)&&e.jsxs("span",{className:"text-[9px] text-[var(--fg-muted)] flex items-center gap-0.5",children:[e.jsx(Ye,{size:9}),Bt(ae.createdAt,c)]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[e.jsx("button",{onClick:()=>{o(te,ae.id),j===ae.id&&S(null)},title:c("common.delete"),className:"p-1.5 text-[var(--fg-muted)] hover:text-red-500 rounded-lg transition-colors opacity-30 hover:opacity-100",children:e.jsx(qe,{size:14})}),e.jsx("div",{className:"h-4 w-px bg-[var(--border-default)]"}),e.jsx("button",{onClick:()=>F(ae.id),disabled:P.has(ae.id),title:c("candidates.enrichTitleSingle"),className:`p-1.5 rounded-lg transition-colors flex items-center gap-1 text-[11px] font-medium ${P.has(ae.id)?"text-[var(--fg-muted)] cursor-not-allowed":"text-amber-500 hover:text-amber-600 hover:bg-amber-500/10"}`,children:P.has(ae.id)?e.jsx(Ne,{size:14,className:"animate-spin"}):e.jsx(us,{size:14})}),e.jsx("button",{onClick:()=>Me(ae.id),disabled:w.has(ae.id),title:c("candidates.refineTitleSingle"),className:`p-1.5 rounded-lg transition-colors flex items-center gap-1 text-[11px] font-medium ${w.has(ae.id)?"text-[var(--fg-muted)] cursor-not-allowed":"text-emerald-500 hover:text-emerald-600 hover:bg-emerald-500/10"}`,children:w.has(ae.id)?e.jsx(Ne,{size:14,className:"animate-spin"}):e.jsx(Le,{size:14})}),e.jsxs("button",{onClick:()=>i(ae,te),className:"text-[11px] font-bold text-blue-600 dark:text-blue-400 hover:text-blue-700 px-3 py-1.5 rounded-lg bg-blue-500/10 hover:bg-blue-500/20 transition-colors flex items-center gap-1",children:[e.jsx(It,{size:12})," ",c("candidates.approveAndSave")]}),(ae.lifecycle==="pending"||ae.lifecycle==="staging")&&e.jsxs("button",{onClick:async()=>{try{await Z.promoteCandidateToRecipe(ae.id),ne(c("candidates.approveSuccess"),{title:c("candidates.approveSuccess")}),m?.()}catch(nt){ne(ke(nt,c("common.operationFailed")),{title:c("common.operationFailed"),type:"error"})}},className:"text-[11px] font-bold text-emerald-600 dark:text-emerald-400 hover:text-emerald-700 px-3 py-1.5 rounded-lg bg-emerald-500/10 hover:bg-emerald-500/20 transition-colors flex items-center gap-1",title:c("candidates.approve"),children:[e.jsx(Kt,{size:12})," ",c("candidates.approve")]})]})]})]},ae.id)})}),le>12&&e.jsx(ca,{currentPage:k,totalPages:O,totalItems:le,pageSize:b,onPageChange:be,onPageSizeChange:fe})]},te)})]}),j&&xe&&t?.candidates?.[xe]&&(()=>{const te=t.candidates[xe].items,de=te.find(v=>v.id===j);if(!de)return null;const f=he[j]||de,J=te.findIndex(v=>v.id===j),ge=J>0,ve=J<te.length-1,k=()=>{ge&&S(te[J-1].id)},b=()=>{ve&&S(te[J+1].id)},z=f.reasoning,le=et[f.category||""]||et.All||{},O=Ta[f.source||""]||{labelKey:f.source||"",color:"text-[var(--fg-secondary)] bg-[var(--bg-subtle)] border-[var(--border-default)]"};return e.jsxs($e,{className:"z-30 flex justify-end",onClick:()=>{S(null)},children:[e.jsx($e.Backdrop,{className:"bg-black/20 dark:bg-black/40 backdrop-blur-sm"}),e.jsxs(Ie.Panel,{size:D?"lg":"md",children:[e.jsxs(Ie.Header,{title:f.title,leading:e.jsx("button",{onClick:()=>{o(xe,f.id),S(null)},title:c("common.delete"),className:"p-1.5 text-[var(--fg-muted)] hover:text-red-500 rounded-md transition-colors opacity-30 hover:opacity-100 shrink-0",children:e.jsx(qe,{size:14})}),children:[e.jsx(Ie.Nav,{currentIndex:J,total:te.length,onPrev:k,onNext:b,hasPrev:ge,hasNext:ve}),e.jsxs(Ie.HeaderActions,{children:[e.jsx(Ie.WidthToggle,{isWide:D,onToggle:I,title:c(D?"common.collapse":"common.expand")}),e.jsx(Ie.CloseButton,{onClose:()=>{S(null)}})]})]}),e.jsxs(Ie.Body,{children:[e.jsx(da,{badges:(()=>{const v=[];return v.push({label:f.category||"general",className:`font-bold uppercase bg-[var(--bg-subtle)] ${le?.color||"text-[var(--fg-muted)]"} border-[var(--border-default)]`}),f.knowledgeType&&v.push({label:f.knowledgeType,className:"bg-purple-500/10 text-purple-600 dark:text-purple-400 border-purple-500/20"}),f.language&&v.push({label:f.language,className:"uppercase font-bold text-[var(--fg-secondary)] bg-[var(--bg-subtle)] border-[var(--border-default)]"}),f.complexity&&v.push({label:f.complexity==="advanced"?c("knowledge.complexityAdvanced"):f.complexity==="intermediate"?c("knowledge.complexityIntermediate"):c("knowledge.complexityBeginner"),className:f.complexity==="advanced"?"bg-violet-500/10 text-violet-600 dark:text-violet-400 border-violet-500/20":f.complexity==="intermediate"?"bg-sky-500/10 text-sky-600 dark:text-sky-400 border-sky-500/20":"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20"}),f.trigger&&v.push({label:f.trigger,className:"font-mono font-bold bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/20"}),f.source&&f.source!=="unknown"&&v.push({label:O.labelKey.startsWith("candidates.")?c(O.labelKey):O.labelKey,className:O.color}),f.lifecycle==="staging"?v.push({label:"staging",className:"bg-blue-500/10 text-blue-600 dark:text-blue-400 border-blue-500/20"}):f.lifecycle&&f.lifecycle!=="pending"&&v.push({label:f.lifecycle,className:"bg-[var(--bg-subtle)] text-[var(--fg-secondary)] border-[var(--border-default)]"}),v})(),metadata:(()=>{const v=[];return f.scope&&v.push({icon:Ct,iconClass:"text-teal-400",label:c("candidates.path"),value:f.scope==="universal"?c("common.all"):f.scope==="project-specific"||f.scope==="module-level"?c("candidates.category"):f.scope}),f.source&&f.source!=="unknown"&&v.push({icon:Ct,iconClass:"text-violet-400",label:c("candidates.source"),value:O.labelKey.startsWith("candidates.")?c(O.labelKey):O.labelKey}),f.createdAt&&Bt(f.createdAt,c)&&v.push({icon:Ye,iconClass:"text-[var(--fg-muted)]",label:c("candidates.createdAt"),value:Bt(f.createdAt,c)}),v})(),tags:f.tags,maxTags:10}),e.jsx(Ee.Description,{label:c("candidates.description"),text:f.description}),e.jsx(Ee.Reasoning,{reasoning:z,labels:{section:c("knowledge.reasoning"),source:`${c("candidates.source")}:`,confidence:`${c("candidates.confidence")}:`,alternatives:`${c("candidates.viewDetail")}:`},filterSubmitted:!0}),e.jsx(Ee.Quality,{quality:f.quality,labels:{section:c("candidates.qualityDimensions"),completeness:c("recipes.qualityCompleteness"),adaptation:c("recipes.qualityAdaptation"),documentation:c("recipes.qualityDocumentation")}}),(()=>{const v=f.relations?Object.entries(f.relations).flatMap(([be,fe])=>Array.isArray(fe)?fe.map(De=>({...De,type:be})):[]):[];return f.agentNotes||f.aiInsight||v.length>0?e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(Le,{size:11,className:"text-emerald-400"})," ",c("candidates.refineEnhanced")]}),e.jsxs("div",{className:"bg-emerald-50/30 border border-emerald-100 rounded-xl p-4 space-y-2.5 text-xs",children:[f.aiInsight&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)] font-bold",children:[c("candidates.viewDetail"),":"]}),e.jsx("p",{className:"text-sm text-[var(--fg-primary)] leading-relaxed mt-0.5",children:f.aiInsight})]}),f.agentNotes&&f.agentNotes.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] font-bold",children:c("candidates.agentNotes")}),e.jsx("ul",{className:"mt-1 space-y-0.5",children:f.agentNotes.map((be,fe)=>e.jsxs("li",{className:"flex items-start gap-1.5 text-[var(--fg-secondary)]",children:[e.jsx("span",{className:"text-emerald-400 mt-0.5",children:"•"}),be]},fe))})]}),v.length>0&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)] font-bold",children:[c("recipes.relations"),":"]}),e.jsx("div",{className:"mt-1 space-y-1",children:v.map((be,fe)=>e.jsxs("div",{className:"flex items-start gap-1.5 text-[var(--fg-secondary)]",children:[e.jsx("span",{className:"text-[9px] font-bold px-1 py-0.5 rounded bg-emerald-100 text-emerald-700 shrink-0 uppercase",children:be.type}),e.jsx("span",{className:"font-medium text-[var(--fg-primary)]",children:Ce.get(be.target)||be.target}),be.description&&e.jsxs("span",{className:"text-[var(--fg-muted)]",children:["— ",be.description]})]},fe))})]})]})]}):null})(),e.jsx(Ee.CodePattern,{label:c("knowledge.codePattern"),code:f.content?.pattern,language:f.language}),e.jsx(Ee.MarkdownSection,{label:c("knowledge.markdownDoc"),content:f.content?.markdown}),e.jsx(Ee.Delivery,{delivery:{topicHint:f.topicHint,whenClause:f.whenClause,doClause:f.doClause,dontClause:f.dontClause,coreCode:f.coreCode},language:f.language}),e.jsx(Ee.Rationale,{label:c("candidates.rationale"),text:f.content?.rationale}),e.jsx(Ee.Headers,{label:c("candidates.headers"),headers:f.headers}),e.jsx(Ee.Steps,{label:c("recipes.steps"),steps:f.content?.steps})]}),e.jsxs(Ie.Footer,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:()=>F(f.id),disabled:P.has(f.id),title:c("candidates.enrichTitleBottom"),className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium transition-colors ${P.has(f.id)?"text-[var(--fg-muted)] cursor-not-allowed":"text-amber-600 hover:bg-amber-50 border border-amber-200"}`,children:[P.has(f.id)?e.jsx(Ne,{size:14,className:"animate-spin"}):e.jsx(us,{size:14}),c("candidates.enrichShort")]}),e.jsxs("button",{onClick:()=>Me(f.id),disabled:w.has(f.id),title:c("candidates.refineTitleBottom"),className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium transition-colors ${w.has(f.id)?"text-[var(--fg-muted)] cursor-not-allowed":"text-emerald-600 hover:bg-emerald-50 border border-emerald-200"}`,children:[w.has(f.id)?e.jsx(Ne,{size:14,className:"animate-spin"}):e.jsx(Le,{size:14}),c("candidates.refineShort")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:()=>{i(f,xe),S(null)},className:"flex items-center gap-1.5 px-4 py-2 rounded-lg text-xs font-bold text-blue-600 bg-blue-50 hover:bg-blue-100 border border-blue-200 transition-colors",children:[e.jsx(It,{size:14})," ",c("candidates.approveAndSave")]}),(f.lifecycle==="pending"||f.lifecycle==="staging")&&e.jsxs("button",{onClick:async()=>{try{await Z.promoteCandidateToRecipe(f.id),ne(c("candidates.approveSuccess"),{title:c("candidates.approveSuccess")}),m?.()}catch(v){ne(ke(v,c("common.operationFailed")),{title:c("common.operationFailed"),type:"error"})}},className:"flex items-center gap-1.5 px-4 py-2 rounded-lg text-xs font-bold text-emerald-700 bg-emerald-50 hover:bg-emerald-100 border border-emerald-200 transition-colors",children:[e.jsx(Kt,{size:14})," ",c("candidates.approve")]})]})]})]})]})})()]})},zi=({isOpen:t,onClose:s,currentFile:a,targetName:r,language:o="",onSelectRecipe:l})=>{const{t:i}=Ae(),[p,d]=n.useState(""),[g,x]=n.useState([]),[h,u]=n.useState(null),[m,c]=n.useState(!1),[j,S]=n.useState(null),[D,I]=n.useState(!1),[P,Y]=n.useState(null),w=async()=>{if(p.trim()){c(!0);try{const _=await Z.search(p,{context:{language:o},limit:10});x((_.items||[]).map(N=>({name:(N.title||N.name||"")+".md",content:N.content?.pattern||N.content?.markdown||N.content?.code||"",similarity:N.score||0,authority:N.authorityScore||0,matchType:N.matchType||"ranked",qualityScore:N.qualityScore||0,usageCount:N.usageCount||0}))),u(null)}catch(_){console.error("Context-aware search failed:",_),alert(i("search.searchFailed"))}finally{c(!1)}}},G=_=>{_.key==="Enter"&&w()};return t?e.jsxs($e,{className:"z-30 flex",children:[e.jsx($e.Backdrop,{className:"bg-black/20 dark:bg-black/40 backdrop-blur-sm"}),e.jsxs("div",{className:"relative w-full max-w-2xl ml-auto bg-white shadow-xl flex flex-col max-h-screen",children:[e.jsxs("div",{className:"border-b border-slate-200 p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{className:"text-xl font-bold text-slate-900",children:i("search.title")}),e.jsx("button",{onClick:s,className:"p-1 hover:bg-slate-100 rounded-lg transition-colors",children:e.jsx(ze,{size:H.lg,className:"text-slate-500"})})]}),h&&e.jsx("div",{className:"mb-4 p-3 bg-blue-50 border border-blue-200 rounded-lg text-sm",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Be,{size:H.md,className:"text-blue-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1",children:[h.targetInfo?.targetName&&e.jsxs("div",{className:"text-blue-900 font-medium flex items-center gap-2 mb-1",children:[e.jsx(fa,{size:H.sm}),"Target: ",h.targetInfo.targetName]}),h.fileInfo?.imports&&h.fileInfo.imports.length>0&&e.jsxs("div",{className:"text-blue-800 text-xs mt-2",children:[e.jsx("strong",{children:i("search.importedFrameworks")})," ",h.fileInfo.imports.slice(0,3).join(", "),h.fileInfo.imports.length>3&&` +${h.fileInfo.imports.length-3}`]}),h.targetInfo?.suggestedApis&&h.targetInfo.suggestedApis.length>0&&e.jsxs("div",{className:"text-blue-800 text-xs mt-1",children:[e.jsx("strong",{children:i("search.relatedApis")})," ",h.targetInfo.suggestedApis.slice(0,3).join(", ")]})]})]})}),e.jsxs("div",{className:"relative",children:[e.jsx(xt,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-400",size:H.md}),e.jsx("input",{type:"text",placeholder:i("search.searchPlaceholder"),value:p,onChange:_=>d(_.target.value),onKeyDown:G,className:"w-full pl-10 pr-4 py-2 border border-slate-300 rounded-lg text-sm outline-none focus:ring-2 focus:ring-blue-500/20 transition-all"})]}),e.jsxs("button",{onClick:w,disabled:!p.trim()||m,className:"mt-3 w-full py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 disabled:bg-blue-300 transition-colors flex items-center justify-center gap-2",children:[m&&e.jsx(Ne,{size:H.sm,className:"animate-spin"}),i(m?"search.searching":"search.searchBtn")]})]}),e.jsxs("div",{className:"flex-1 overflow-auto",children:[g.length===0&&!m&&e.jsx("div",{className:"flex items-center justify-center h-full text-slate-500",children:e.jsxs("div",{className:"text-center",children:[e.jsx(kr,{size:H.xxl,className:"mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:i("search.emptyHint")})]})}),g.map((_,N)=>e.jsxs("div",{className:"border-b border-slate-200 p-4 hover:bg-slate-50 transition-colors cursor-pointer",onClick:()=>{S(j===N?null:N),_.name&&l?.(_.name)},children:[e.jsxs("div",{className:"flex items-start justify-between mb-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-slate-900 text-sm",children:_.name}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-slate-100 rounded text-xs text-slate-600",children:[e.jsx(Be,{size:H.xs}),Math.round(_.similarity*100),"%"]}),_.isContextRelevant&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-green-100 rounded text-xs text-green-700",children:[e.jsx(fa,{size:H.xs}),i("search.contextRelevant")]}),_.matchType&&e.jsx("span",{className:"text-xs text-slate-500",children:_.matchType==="semantic"?i("search.matchSemantic"):i("search.matchKeyword")})]})]}),e.jsx("button",{onClick:E=>{E.stopPropagation(),S(j===N?null:N)},className:"p-1 hover:bg-slate-200 rounded transition-colors",children:j===N?"▼":"▶"})]}),_.stats&&e.jsxs("div",{className:"text-xs text-slate-500 mb-2 flex gap-3",children:[_.stats.authorityScore!==void 0&&e.jsxs("span",{children:[i("search.authorityScore"),": ",_.stats.authorityScore]}),_.usageCount!==void 0&&e.jsxs("span",{children:[i("search.usage"),": ",i("search.usageCount",{count:_.usageCount})]})]}),j===N&&e.jsxs("div",{className:"mt-3 pt-3 border-t border-slate-200",children:[_.recommendReason&&e.jsxs("div",{className:"text-xs text-slate-600 bg-blue-50 p-2 rounded mb-2 border border-blue-100",children:[e.jsx("p",{className:"font-medium text-blue-700 mb-0.5",children:i("search.recommendReason")}),e.jsx("p",{children:_.recommendReason})]}),e.jsxs("div",{className:"text-xs text-slate-600 max-h-[200px] overflow-auto bg-slate-50 p-3 rounded",children:[_.content.substring(0,500),"..."]}),e.jsx("button",{onClick:E=>{E.stopPropagation(),Y(_),I(!0)},className:"mt-2 w-full py-1.5 bg-blue-50 text-blue-600 rounded text-xs font-medium hover:bg-blue-100 transition-colors",children:i("search.viewFullContent")})]})]},N)),m&&e.jsx("div",{className:"flex items-center justify-center h-32",children:e.jsx(Ne,{size:H.lg,className:"animate-spin text-blue-600"})}),g.length===0&&p&&!m&&e.jsx("div",{className:"flex items-center justify-center h-32",children:e.jsxs("div",{className:"text-center text-slate-500",children:[e.jsx(Et,{size:H.xl,className:"mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:i("search.noResults")})]})})]})]}),D&&P&&e.jsxs($e,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx($e.Backdrop,{className:"bg-black/20 dark:bg-black/40 backdrop-blur-sm"}),e.jsxs("div",{className:"relative bg-white rounded-lg shadow-2xl w-full max-w-2xl max-h-[90vh] flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"border-b border-slate-200 p-6 flex items-start justify-between shrink-0",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-bold text-slate-900",children:P.name}),e.jsxs("div",{className:"flex items-center gap-4 mt-2",children:[e.jsxs("span",{className:"text-xs bg-blue-100 text-blue-700 px-2 py-1 rounded",children:[i("search.similarity"),": ",Math.round(P.similarity*100),"%"]}),P.isContextRelevant&&e.jsxs("span",{className:"text-xs bg-green-100 text-green-700 px-2 py-1 rounded",children:["✓ ",i("search.contextRelevant")]}),P.qualityScore!==void 0&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-blue-100 rounded text-xs text-blue-700 font-medium",children:["🤖 ",i("search.quality"),": ",(P.qualityScore*100).toFixed(0),"%"]}),P.stats?.authorityScore!==void 0&&e.jsxs("span",{className:"text-xs bg-purple-100 text-purple-700 px-2 py-1 rounded",children:[i("search.authorityScore"),": ",Math.round(P.stats.authorityScore*100)/100]})]})]}),e.jsx("button",{onClick:()=>I(!1),className:"p-1 hover:bg-slate-100 rounded transition-colors shrink-0",children:e.jsx(ze,{size:H.lg,className:"text-slate-500"})})]}),e.jsx("div",{className:"overflow-auto flex-1 p-6",children:e.jsx("div",{className:"prose prose-sm max-w-none",children:P.content?e.jsx(vt,{code:P.content,language:"markdown"}):e.jsx("p",{className:"text-slate-500 text-sm",children:i("search.noContent")})})}),e.jsxs("div",{className:"border-t border-slate-200 p-4 bg-slate-50 flex justify-end gap-2 shrink-0",children:[e.jsx("button",{onClick:()=>I(!1),className:"px-4 py-2 text-slate-700 hover:bg-slate-200 rounded transition-colors text-sm font-medium",children:i("common.close")}),l&&e.jsxs("button",{onClick:()=>{l(P.name),I(!1)},className:"px-4 py-2 bg-blue-600 text-white hover:bg-blue-700 rounded transition-colors text-sm font-medium flex items-center gap-2",children:[e.jsx(Ke,{size:H.md}),i("search.useRecipe")]})]})]})]})]}):null},Ea=t=>na(t.language)||"text";function Bi(t){const s=[],a=t.match(/#import\s+"([^"]+)"/);if(a){const i=a[1].replace(/\.h$/,"");s.push(i)}const r=t.match(/#import\s+<([^>]+)>/);if(r){const i=r[1].replace(/\.h$/,"").split("/");s.push(...i)}const o=t.match(/^import\s+(\w+)/);o&&s.push(o[1]);const l=t.match(/@import\s+(\w+)/);return l&&s.push(l[1]),[...new Set(s.filter(Boolean))]}function Gt(t,s){if(!s||!s.trim())return"unknown";const a=Bi(t);return a.length===0?"unknown":a.some(r=>s.includes(r))?"used":"unused"}function Gi(t){return t.startsWith("#import ")||t.startsWith("import ")||t.startsWith("@import ")?t.trim():t.startsWith("<")||t.startsWith('"')?`#import ${t.trim()}`:t.trim()}const $i=[{value:"",label:"—"},{value:"networking",label:"Networking"},{value:"ui",label:"UI"},{value:"data",label:"Data"},{value:"architecture",label:"Architecture"},{value:"conventions",label:"Conventions"}],Oi=t=>{const s=(t.content?.pattern||"").trim();if(!s)return!1;const a=s.split(`
`).filter(o=>o.trim());return!(a.filter(o=>/^\s*(#{1,6}\s|[-*>]\s|\d+\.\s)/.test(o)).length>a.length*.3)},Hi=({res:t,index:s,editingCodeIndex:a,setEditingCodeIndex:r,expandedEditIndex:o,setExpandedEditIndex:l,handleUpdateScanResult:i,handleSaveExtracted:p,handlePromoteToCandidate:d,isSavingRecipe:g=!1})=>{const{t:x}=Ae(),[h,u]=n.useState(!1),m=o===s,c=t.headers||[],j=t.content?.pattern||"",S=t.content?.markdown||"",D=t.description||"",I=t.tags||[],P=Oi(t),Y=(w,G)=>{i(s,{content:{...t.content||{},[w]:G}})};return e.jsxs("div",{className:"bg-slate-50 dark:bg-[#1a1d24] rounded-2xl border border-slate-200 dark:border-slate-700 overflow-hidden shadow-sm",children:[e.jsxs("div",{className:"px-5 pt-4 pb-3 bg-gradient-to-b from-white to-slate-50/50 dark:from-[#252526] dark:to-[#1e1e1e] border-b border-slate-100 dark:border-slate-700",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5",children:x("scanResult.knowledgeEntryTitle")}),t.scanMode==="project"?e.jsxs("span",{className:"text-[9px] font-bold px-1.5 py-0.5 rounded bg-indigo-100 text-indigo-700 border border-indigo-200 flex items-center gap-1",children:[e.jsx(Ge,{size:10})," PROJECT"]}):t.scanMode==="target"?e.jsxs("span",{className:"text-[9px] font-bold px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 border border-blue-200 flex items-center gap-1",children:[e.jsx(Be,{size:10})," ",t.candidateTargetName||"TARGET"]}):t.lifecycle?e.jsx("span",{className:`text-[9px] font-bold px-1.5 py-0.5 rounded flex items-center gap-1 ${t.lifecycle==="pending"?"bg-amber-100 text-amber-700 border border-amber-200":t.lifecycle==="active"?"bg-green-100 text-green-700 border border-green-200":"bg-slate-100 text-slate-600 border border-slate-200"}`,children:t.lifecycle==="pending"?x("scanResult.lifecyclePending"):t.lifecycle==="active"?x("scanResult.lifecycleActive"):t.lifecycle==="deprecated"?x("scanResult.lifecycleDeprecated"):t.lifecycle}):null,t.source&&t.source!=="unknown"&&e.jsx("span",{className:"text-[9px] font-medium px-1.5 py-0.5 rounded bg-violet-50 text-violet-600 border border-violet-100",children:t.source==="agent"?"AI Agent":t.source==="bootstrap-scan"?x("scanResult.aiScan"):t.source})]}),e.jsx("input",{className:"font-semibold bg-transparent border-b-2 border-transparent hover:border-slate-200 focus:border-blue-500 outline-none px-0.5 text-lg w-full text-slate-800 placeholder:text-slate-300",value:t.title||"",onChange:w=>i(s,{title:w.target.value})})]}),e.jsxs("div",{className:"flex gap-2 shrink-0 pt-3",children:[d&&e.jsxs("button",{onClick:()=>d(t,s),className:"text-xs px-4 py-2 rounded-lg font-bold transition-all shadow-sm flex items-center gap-1.5 active:scale-95 bg-white dark:bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border border-emerald-200 dark:border-emerald-700/40 hover:bg-emerald-50 dark:hover:bg-emerald-500/20 whitespace-nowrap",children:[e.jsx(hs,{size:H.md}),"Candidate"]}),e.jsxs("button",{onClick:()=>p(t),disabled:g,className:`text-xs px-4 py-2 rounded-lg font-bold transition-all shadow-sm flex items-center gap-1.5 active:scale-95 disabled:opacity-60 disabled:cursor-not-allowed whitespace-nowrap ${P&&t.mode==="full"?"bg-blue-600 text-white hover:bg-blue-700 dark:bg-blue-500/20 dark:text-blue-300 dark:hover:bg-blue-500/30 dark:border dark:border-blue-500/30":"bg-amber-600 text-white hover:bg-amber-700 dark:bg-amber-500/20 dark:text-amber-300 dark:hover:bg-amber-500/30 dark:border dark:border-amber-500/30"}`,children:[g?e.jsx(Ne,{size:H.md,className:"animate-spin"}):e.jsx(Cr,{size:H.md}),x(g?"scanResult.saving":P?"scanResult.saveAsRecipe":"scanResult.saveAsKnowledge")]})]})]}),e.jsxs("div",{className:"flex items-end gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:x("scanResult.trigger")}),e.jsx("input",{className:"font-mono font-bold text-blue-600 bg-blue-50/80 border border-blue-100 px-2.5 py-1 rounded-md outline-none text-xs focus:ring-2 focus:ring-blue-500/20 w-44",value:t.trigger||"",placeholder:x("scanResult.triggerPlaceholder"),onChange:w=>i(s,{trigger:w.target.value})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:"Kind"}),e.jsx(tt,{value:t.kind||"pattern",onChange:w=>i(s,{kind:w}),options:[{value:"rule",label:"Rule"},{value:"pattern",label:"Pattern"},{value:"fact",label:"Fact"}],size:"xs"})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:"Topic"}),e.jsx(tt,{value:t.topicHint||"",onChange:w=>i(s,{topicHint:w}),options:$i.map(w=>({value:w.value,label:w.label})),size:"xs"})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:x("scanResult.category")}),e.jsx(tt,{value:t.category||"",onChange:w=>i(s,{category:w}),options:$l.filter(w=>w!=="All").map(w=>({value:w,label:w})),size:"xs"})]}),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-px h-6 bg-slate-200 self-end mb-0.5"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:x("scanResult.language")}),e.jsx(tt,{value:na(t.language),onChange:w=>i(s,{language:w}),options:bs.map(w=>({value:w.id,label:w.label})),size:"xs"})]})]}),t.moduleName&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-px h-6 bg-slate-200 self-end mb-0.5"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:x("scanResult.module")}),e.jsx("span",{className:"text-[11px] bg-purple-50 text-purple-700 border border-purple-100 px-2 py-1 rounded-md font-mono font-bold",children:t.moduleName})]})]}),e.jsx("div",{className:"w-px h-6 bg-slate-200 self-end mb-0.5"}),P&&e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:x("scanResult.mode")}),e.jsxs("div",{className:"flex bg-white dark:bg-[#252a36] p-0.5 rounded-md border border-slate-200 dark:border-slate-600",children:[e.jsx("button",{onClick:()=>i(s,{mode:"full"}),className:`px-2.5 py-0.5 rounded text-[10px] font-bold transition-all ${t.mode==="full"?"bg-blue-100 shadow-sm text-blue-600":"text-slate-400 hover:text-slate-500"}`,children:"Full"}),e.jsx("button",{onClick:()=>i(s,{mode:"preview"}),className:`px-2.5 py-0.5 rounded text-[10px] font-bold transition-all ${t.mode==="preview"?"bg-amber-100 shadow-sm text-amber-600":"text-slate-400 hover:text-slate-500"}`,children:"Recipe Only"})]})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:x("scanResult.difficulty")}),e.jsx(tt,{value:t.difficulty||"intermediate",onChange:w=>i(s,{difficulty:w,complexity:w}),options:[{value:"beginner",label:x("scanResult.difficultyBeginner")},{value:"intermediate",label:x("scanResult.difficultyIntermediate")},{value:"advanced",label:x("scanResult.difficultyAdvanced")}],size:"xs"})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:x("scanResult.authorityScore")}),e.jsx(tt,{value:String(t.authority??t.stats?.authority??3),onChange:w=>i(s,{authority:parseInt(w)}),options:[{value:"1",label:"⭐ 1",icon:""},{value:"2",label:"⭐⭐ 2",icon:""},{value:"3",label:"⭐⭐⭐ 3",icon:""},{value:"4",label:"⭐⭐⭐⭐ 4",icon:""},{value:"5",label:"⭐⭐⭐⭐⭐ 5",icon:""}],size:"xs",className:"font-bold text-amber-600 bg-amber-50 border-amber-100"})]})]}),e.jsx("div",{className:"mt-2.5",children:e.jsxs("div",{className:"flex flex-wrap gap-1 items-center bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 rounded-md px-1.5 py-0.5 min-h-[28px] focus-within:ring-2 focus-within:ring-blue-500/20",children:[I.map((w,G)=>e.jsxs("span",{className:"flex items-center gap-0.5 text-[10px] font-bold bg-blue-50 text-blue-700 border border-blue-200 px-1.5 py-0 rounded",children:[w,e.jsx("button",{onClick:()=>{const _=[...I];_.splice(G,1),i(s,{tags:_})},className:"text-blue-400 hover:text-red-500 transition-colors leading-none text-[10px]",title:"{t('scanResult.removeTag')}",children:"×"})]},G)),e.jsx("input",{className:"flex-1 min-w-[80px] text-[11px] text-slate-600 outline-none bg-transparent py-0.5",placeholder:I.length===0?x("scanResult.tagsPlaceholder"):"",onKeyDown:w=>{const G=w.currentTarget,_=G.value.trim();if((w.key==="Enter"||w.key===","||w.key===",")&&_){w.preventDefault();const N=_.replace(/[,,]/g,"").trim();N&&!I.includes(N)&&i(s,{tags:[...I,N]}),G.value=""}else if(w.key==="Backspace"&&!G.value&&I.length>0){const N=[...I];N.pop(),i(s,{tags:N})}},onBlur:w=>{const G=w.currentTarget.value.trim().replace(/[,,]/g,"").trim();G&&!I.includes(G)&&i(s,{tags:[...I,G]}),w.currentTarget.value=""}})]})}),P&&c.length>0&&e.jsxs("div",{className:"mt-2 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase",children:x("scanResult.headers")}),e.jsxs("button",{onClick:()=>l(o===s?null:s),className:`text-[10px] font-bold px-2 py-0.5 rounded-md transition-colors border ${m?"text-blue-700 bg-blue-100 border-blue-300":"text-blue-600 bg-blue-50 border-blue-100 hover:bg-blue-100"}`,children:[x(m?"scanResult.collapseHeaders":"scanResult.editHeaders")," (",c.length,")"]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[9px] text-slate-400",children:"Include:"}),e.jsx("button",{onClick:()=>i(s,{includeHeaders:t.includeHeaders===!1}),className:`w-7 h-4 rounded-full relative transition-colors ${t.includeHeaders!==!1?"bg-blue-600":"bg-slate-300"}`,title:t.includeHeaders!==!1?x("scanResultCard.includeMarkOn"):x("scanResultCard.includeMarkOff"),children:e.jsx("div",{className:`absolute top-0.5 w-2.5 h-2.5 bg-white rounded-full transition-all ${t.includeHeaders!==!1?"right-0.5":"left-0.5"}`})}),e.jsx("span",{className:"text-[9px] font-bold text-slate-600",children:t.includeHeaders!==!1?"ON":"OFF"})]}),(()=>{const w=c.filter(_=>Gt(_,j)==="used").length,G=c.filter(_=>Gt(_,j)==="unused").length;return e.jsxs("span",{className:"text-[9px] text-slate-400",children:[w>0&&e.jsxs("span",{className:"text-green-600 font-bold",children:[w," ",x("scanResult.referenced")]}),w>0&&G>0&&" · ",G>0&&e.jsxs("span",{className:"text-amber-600 font-bold",children:[G," ",x("scanResult.unreferenced")]})]})})()]}),m&&e.jsxs("div",{className:"space-y-2 bg-slate-50/80 dark:bg-[#1e2028] rounded-lg p-3 border border-slate-200 dark:border-slate-700",children:[e.jsxs("div",{className:"flex items-center justify-end gap-1.5",children:[e.jsx("button",{onClick:()=>{const w=c.map(G=>Gi(G));i(s,{headers:w})},className:"text-[9px] px-2 py-0.5 bg-slate-200 text-slate-600 rounded hover:bg-slate-300 font-bold",title:x("scanResultCard.formatHeaders"),children:x("scanResult.formatHeaders")}),c.some(w=>Gt(w,j)==="unused")&&e.jsx("button",{onClick:()=>{const w=c.filter(G=>Gt(G,j)!=="unused");i(s,{headers:w})},className:"text-[9px] px-2 py-0.5 bg-amber-100 text-amber-700 rounded hover:bg-amber-200 font-bold",title:x("scanResultCard.cleanUnused"),children:x("scanResult.cleanUnused")}),e.jsx("button",{onClick:()=>{const w=[...c,Na(t.language)];i(s,{headers:w})},className:"text-[9px] px-2 py-0.5 bg-green-500 text-white rounded hover:bg-green-600 font-bold",children:x("scanResult.addHeader")})]}),e.jsx("div",{className:"space-y-1",children:c.map((w,G)=>{const _=Gt(w,j);return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${_==="used"?"bg-green-500":_==="unused"?"bg-amber-400":"bg-slate-300"}`,title:x(_==="used"?"scanResult.usedInCode":_==="unused"?"scanResult.unusedInCode":"scanResult.unknown")}),e.jsx("input",{className:`flex-1 text-xs font-mono bg-white dark:bg-[#252a36] border rounded px-2 py-1 outline-none focus:border-blue-400 ${_==="unused"?"border-amber-300 text-amber-700 dark:border-amber-700 dark:text-amber-400":"border-slate-200 dark:border-slate-600"}`,value:w,onChange:N=>{const E=[...c];E[G]=N.target.value,i(s,{headers:E})},placeholder:Na(t.language)}),_==="unused"&&e.jsx("span",{className:"text-[8px] text-amber-500 font-bold shrink-0",children:x("scanResult.unreferenced")}),e.jsx("button",{onClick:()=>{const N=c.filter((E,L)=>L!==G);i(s,{headers:N})},className:"px-2 py-1 bg-red-500 text-white rounded hover:bg-red-600 text-[9px] font-bold shrink-0",children:x("scanResult.deleteHeader")})]},G)})})]})]})]}),e.jsxs("div",{className:"px-6 pb-6 pt-4 space-y-4",children:[e.jsxs("div",{className:"rounded-xl border border-cyan-200 dark:border-cyan-800/40 bg-gradient-to-br from-cyan-50/60 to-blue-50/40 dark:from-cyan-900/15 dark:to-blue-900/10 p-4 space-y-3",children:[e.jsxs("div",{className:"text-[10px] font-bold text-cyan-700 uppercase tracking-wider flex items-center gap-1.5",children:[e.jsx(Be,{size:12}),x("scanResult.cursorDelivery")]}),e.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-2 items-start",children:[e.jsx("span",{className:"text-[10px] font-bold text-emerald-600 uppercase pt-1.5 select-none",children:"Do"}),e.jsx("input",{className:"text-sm text-slate-700 dark:text-slate-300 bg-white/80 dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 rounded-lg px-3 py-1.5 outline-none focus:ring-2 focus:ring-cyan-500/20",value:t.doClause||"",onChange:w=>i(s,{doClause:w.target.value}),placeholder:"English imperative ≤60 tokens, e.g. Use dispatch_once for thread-safe singleton"}),e.jsx("span",{className:"text-[10px] font-bold text-red-500 uppercase pt-1.5 select-none",children:"Don't"}),e.jsx("input",{className:"text-sm text-slate-700 dark:text-slate-300 bg-white/80 dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 rounded-lg px-3 py-1.5 outline-none focus:ring-2 focus:ring-cyan-500/20",value:t.dontClause||"",onChange:w=>i(s,{dontClause:w.target.value}),placeholder:"English constraint (omit 'Don't' prefix), e.g. use @synchronized for singleton"}),e.jsx("span",{className:"text-[10px] font-bold text-amber-600 uppercase pt-1.5 select-none",children:"When"}),e.jsx("input",{className:"text-sm text-slate-700 dark:text-slate-300 bg-white/80 dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 rounded-lg px-3 py-1.5 outline-none focus:ring-2 focus:ring-cyan-500/20",value:t.whenClause||"",onChange:w=>i(s,{whenClause:w.target.value}),placeholder:"When implementing singleton pattern or global shared instance"})]})]}),t.reasoning&&(t.reasoning.confidence!=null||t.reasoning.whyStandard&&!/^Submitted via /i.test(t.reasoning.whyStandard))&&e.jsxs("div",{className:"rounded-xl border border-indigo-100 dark:border-indigo-800/40 bg-indigo-50/40 dark:bg-indigo-900/15 p-3 text-xs space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-indigo-600 font-bold text-[10px]",children:[x("scanResult.aiReasoning"),t.reasoning.confidence!=null&&e.jsx("span",{className:`ml-auto font-mono text-[10px] ${t.reasoning.confidence>=.7?"text-emerald-600":t.reasoning.confidence>=.4?"text-amber-600":"text-red-600"}`,children:x("scanResult.confidenceLabel",{value:Math.round(t.reasoning.confidence*100)})})]}),t.reasoning.whyStandard&&!/^Submitted via /i.test(t.reasoning.whyStandard)&&e.jsx("p",{className:"text-slate-600",children:t.reasoning.whyStandard}),t.reasoning.sources&&t.reasoning.sources.length>0&&e.jsxs("p",{className:"text-slate-400",children:[x("scanResult.sourceLabel")," ",t.reasoning.sources.join(", ")]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] font-bold text-slate-400 uppercase mb-1",children:x("scanResult.description")}),e.jsx("textarea",{rows:1,className:"w-full text-sm text-slate-600 dark:text-slate-300 bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 rounded-xl px-3 py-2 outline-none resize-none leading-relaxed focus:ring-2 focus:ring-blue-500/10",value:D,onChange:w=>i(s,{description:w.target.value,summary:w.target.value}),placeholder:x("scanResult.descPlaceholder")})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase",children:x("scanResult.markdown")}),e.jsx("button",{type:"button",onClick:()=>u(!h),className:`flex items-center gap-1 text-[10px] font-bold px-2 py-1 rounded transition-colors ${h?"text-blue-600 hover:text-blue-700 bg-blue-50":"text-slate-500 hover:text-slate-700 hover:bg-slate-100"}`,children:h?e.jsxs(e.Fragment,{children:[e.jsx(ot,{size:H.xs})," ",x("scanResult.done")]}):e.jsxs(e.Fragment,{children:[e.jsx(Os,{size:H.xs})," ",x("common.edit")]})})]}),h?e.jsx("textarea",{rows:Math.max(6,(S||"").split(`
`).length),className:"w-full text-sm text-slate-600 dark:text-slate-300 bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 rounded-xl px-3 py-2 outline-none resize-y leading-relaxed focus:ring-2 focus:ring-blue-500/10 font-mono",value:S,onChange:w=>Y("markdown",w.target.value)}):S?e.jsx("div",{className:"text-sm text-slate-600 dark:text-slate-300 bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 rounded-xl px-4 py-3 leading-relaxed whitespace-pre-wrap max-h-64 overflow-y-auto",children:S}):e.jsx("p",{className:"text-xs text-slate-400 italic py-2",children:x("scanResult.noArticle")})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase",children:x("scanResult.code")}),a===s?e.jsxs("button",{type:"button",onClick:()=>r(null),className:"flex items-center gap-1 text-[10px] font-bold text-blue-600 hover:text-blue-700 px-2 py-1 rounded bg-blue-50",children:[e.jsx(ot,{size:H.xs})," ",x("scanResult.done")]}):e.jsxs("button",{type:"button",onClick:()=>r(s),className:"flex items-center gap-1 text-[10px] font-bold text-slate-500 hover:text-slate-700 px-2 py-1 rounded hover:bg-slate-100",title:x("common.edit"),children:[e.jsx(Os,{size:H.xs})," ",x("common.edit")]})]}),a===s?e.jsx("div",{className:"rounded-xl overflow-hidden",children:e.jsx(ys,{value:j,onChange:w=>Y("pattern",w),language:Ea(t),height:`${Math.min(12,j.split(`
`).length)*20+16}px`})}):j?e.jsx(vt,{code:j,language:Ea(t),showLineNumbers:!0}):e.jsx("p",{className:"text-xs text-slate-400 italic py-4",children:x("scanResult.noCode")})]})]})]})},Pa={swift:"bg-orange-100 text-orange-700 border-orange-200",objectivec:"bg-blue-100 text-blue-700 border-blue-200",go:"bg-cyan-100 text-cyan-700 border-cyan-200",python:"bg-yellow-100 text-yellow-700 border-yellow-200",java:"bg-red-100 text-red-700 border-red-200",kotlin:"bg-purple-100 text-purple-700 border-purple-200",javascript:"bg-amber-100 text-amber-700 border-amber-200",typescript:"bg-blue-100 text-blue-700 border-blue-200",rust:"bg-orange-100 text-orange-800 border-orange-300",ruby:"bg-rose-100 text-rose-700 border-rose-200",c:"bg-gray-100 text-gray-700 border-gray-200",cpp:"bg-gray-100 text-gray-700 border-gray-200"},Ma={swift:"Swift",objectivec:"ObjC",go:"Go",python:"Py",java:"Java",kotlin:"KT",javascript:"JS",typescript:"TS",rust:"RS",ruby:"RB",c:"C",cpp:"C++"},Ki=({targets:t,filteredTargets:s,selectedTargetName:a,isScanning:r,scanProgress:o,scanFileList:l,scanResults:i,guardAudit:p,handleScanTarget:d,handleScanProject:g,handleUpdateScanResult:x,handleSaveExtracted:h,handlePromoteToCandidate:u,handleDeleteCandidate:m,onEditRecipe:c,isShellTarget:j,recipes:S=[],isSavingRecipe:D=!1,handleRefreshProject:I,onAddCustomFolder:P,onRemoveCustomFolder:Y})=>{const{t:w}=Ae(),[G,_]=n.useState(null),[N,E]=n.useState(null),[L,$]=n.useState(!1),[U]=n.useState(),[q]=n.useState(),[A,y]=n.useState([]),[W,re]=n.useState(!1),he=n.useRef(!1),ue=3,[V,B]=n.useState("modules"),oe=n.useRef(!1),me=n.useMemo(()=>s.filter(T=>!j(T.name)).length,[s,j]);n.useEffect(()=>{oe.current||t.length!==0&&(oe.current=!0,me<ue?B("folders"):B("modules"))},[t.length,me]),n.useEffect(()=>{V!=="folders"||he.current||(he.current=!0,re(!0),Z.browseDirectories("",3).then(T=>{y(T)}).catch(()=>{y([])}).finally(()=>{re(!1)}))},[V]);const R=n.useCallback(T=>{const ee={name:T.name,packageName:T.name,packagePath:T.path,targetDir:T.path,path:T.path,type:"directory",language:T.language||"unknown",discovererId:"folder-scan",discovererName:w("moduleExplorer.discovererFolderScan"),info:{source:"manual-folder-scan",originalPath:T.path},isVirtual:!0};P?.(ee),d(ee),B("modules")},[d,P,w]);return e.jsxs("div",{className:"flex gap-4 xl:gap-6 2xl:gap-8 h-full",children:[e.jsxs("div",{className:"w-64 xl:w-72 2xl:w-80 bg-[var(--bg-surface)] rounded-xl border border-[var(--border-default)] flex flex-col overflow-hidden shrink-0",children:[e.jsx("div",{className:"p-3 bg-[var(--bg-subtle)] border-b border-[var(--border-default)]",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-0.5 bg-[var(--bg-subtle)] rounded-lg p-0.5",children:[e.jsx("button",{onClick:()=>B("modules"),className:`text-[11px] px-2.5 py-1.5 rounded-md font-bold transition-all ${V==="modules"?"bg-[var(--bg-surface)] text-blue-700 shadow-sm":"text-[var(--fg-secondary)] hover:text-[var(--fg-primary)]"}`,children:w("moduleExplorer.modulesTabLabel",{count:me})}),e.jsx("button",{onClick:()=>B("folders"),className:`text-[11px] px-2.5 py-1.5 rounded-md font-bold transition-all ${V==="folders"?"bg-[var(--bg-surface)] text-blue-700 shadow-sm":"text-[var(--fg-secondary)] hover:text-[var(--fg-primary)]"}`,children:w("moduleExplorer.foldersTabLabel")})]}),I&&e.jsx("button",{onClick:I,title:w("moduleExplorer.refreshProject"),className:"p-1.5 rounded-md hover:bg-blue-50 text-[var(--fg-secondary)] hover:text-blue-600 border border-transparent hover:border-blue-200 transition-all",children:e.jsx(at,{size:H.md})})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto p-2 space-y-1",children:V==="modules"?e.jsx(e.Fragment,{children:s.map(T=>{const ee=j(T.name),ie=a===T.name,xe=T.isVirtual||T.discovererId==="folder-scan",pe=T.language||"",M=Pa[pe]||"bg-[var(--bg-subtle)] text-[var(--fg-secondary)] border-[var(--border-default)]",Ce=T.packageName&&T.packageName!==T.name?T.packageName:T.discovererName||"";return e.jsxs("button",{onClick:()=>d(T),disabled:r,className:`w-full text-left p-3 rounded-lg flex items-center justify-between group transition-all border ${r?"opacity-50 cursor-not-allowed":"hover:bg-[var(--bg-subtle)]"} ${ie?"bg-blue-50 border-blue-200 ring-1 ring-blue-200":"bg-[var(--bg-surface)] border-transparent"} ${ee?"opacity-90":""}`,children:[e.jsxs("div",{className:`flex flex-col min-w-0 flex-1 ${ee?"opacity-60":""}`,children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[!ee&&e.jsx("div",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${xe?"bg-emerald-500":"bg-blue-600"}`}),e.jsx("span",{className:`text-sm truncate ${ee?"font-medium":"font-bold"} ${ie?"text-blue-700":""}`,children:T.name}),pe&&!ee&&!xe&&pe!=="unknown"&&e.jsx("span",{className:`text-[9px] font-bold px-1.5 py-0.5 rounded border shrink-0 ${M}`,children:Ma[pe]||pe.toUpperCase()})]}),Ce&&e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] truncate pl-3",children:Ce})]}),ee?e.jsx("span",{className:"text-[9px] font-bold text-[var(--fg-muted)] border border-[var(--border-default)] px-1 rounded",children:"SHELL"}):xe&&Y?e.jsx("div",{className:"flex items-center gap-0.5 shrink-0",children:e.jsx("button",{onClick:F=>{F.stopPropagation(),Y(T.path||"")},title:w("moduleExplorer.removeFolder"),className:"p-0.5 rounded text-[var(--fg-muted)] hover:text-red-500 hover:bg-red-50 opacity-0 group-hover:opacity-100 transition-all",children:e.jsx(qe,{size:12})})}):null]},`${T.discovererId||"default"}::${T.name}`)})}):e.jsxs(e.Fragment,{children:[W?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-[var(--fg-muted)]",children:[e.jsx(Ne,{size:H.lg,className:"animate-spin mb-3 opacity-40"}),e.jsx("p",{className:"text-xs",children:w("moduleExplorer.scanningDirs")})]}):A.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-[var(--fg-muted)]",children:[e.jsx(fr,{size:H.xl,className:"mb-3 opacity-20"}),e.jsx("p",{className:"text-xs text-center px-4 leading-relaxed",children:w("moduleExplorer.noDirs")})]}):A.map((T,ee)=>{const ie=Pa[T.language]||"bg-[var(--bg-subtle)] text-[var(--fg-secondary)] border-[var(--border-default)]",xe=T.hasSourceFiles&&T.language!=="unknown"&&(()=>{if(T.depth===0)return!0;for(let pe=ee-1;pe>=0;pe--){const M=A[pe];if(M.depth<T.depth)return M.language!==T.language;if(M.depth===T.depth&&M.language===T.language&&M.hasSourceFiles)return!1}return!0})();return e.jsxs("button",{onClick:()=>R(T),disabled:r||!T.hasSourceFiles,className:`w-full text-left p-2.5 rounded-lg flex items-center gap-2.5 transition-all border border-transparent
            ${T.hasSourceFiles?r?"opacity-50 cursor-not-allowed":"hover:bg-emerald-50 hover:border-emerald-200 cursor-pointer":"opacity-40 cursor-not-allowed"}
          `,style:{paddingLeft:`${T.depth*14+10}px`},children:[e.jsx(Lt,{size:H.sm,className:T.hasSourceFiles?"text-emerald-500 shrink-0":"text-[var(--fg-muted)] shrink-0"}),e.jsx("span",{className:"text-sm font-medium flex-1 truncate",children:T.name}),xe&&e.jsx("span",{className:`text-[9px] font-bold px-1.5 py-0.5 rounded border shrink-0 ${ie}`,children:Ma[T.language]||T.language.toUpperCase()}),T.hasSourceFiles&&e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] shrink-0",children:T.sourceFileCount}),e.jsx(Ke,{size:12,className:"text-[var(--fg-muted)] shrink-0"})]},T.path)}),e.jsx("div",{className:"px-3 py-2 text-[10px] text-[var(--fg-muted)] text-center",children:w("moduleExplorer.selectFolderHint")})]})})]}),e.jsxs("div",{className:"flex-1 bg-[var(--bg-surface)] rounded-xl border border-[var(--border-default)] flex flex-col overflow-hidden relative",children:[e.jsx("div",{className:"p-4 bg-[var(--bg-subtle)] border-b border-[var(--border-default)] font-bold text-sm flex justify-between items-center",children:e.jsxs("div",{className:"flex items-center gap-2",children:[a==="__project__"?e.jsxs(e.Fragment,{children:[e.jsx(Ge,{size:H.md,className:"text-indigo-500"}),e.jsx("span",{children:w("moduleExplorer.fullProjectResults")}),i.length>0&&e.jsx("span",{className:"text-[10px] font-bold px-2 py-0.5 rounded-full bg-indigo-100 text-indigo-700 border border-indigo-200",children:"PROJECT"})]}):a?e.jsxs(e.Fragment,{children:[e.jsx(Be,{size:H.md,className:"text-blue-500"}),e.jsx("span",{children:w("moduleExplorer.moduleLabel",{name:a})}),i.length>0&&e.jsx("span",{className:"text-[10px] font-bold px-2 py-0.5 rounded-full bg-blue-100 text-blue-700 border border-blue-200",children:"MODULE"})]}):e.jsxs(e.Fragment,{children:[e.jsx(It,{size:H.md,className:"text-[var(--fg-muted)]"}),e.jsx("span",{children:w("moduleExplorer.reviewResults")})]}),i.length>0&&e.jsxs("span",{className:"text-[var(--fg-muted)] font-normal text-xs ml-1",children:["(",w("moduleExplorer.resultsCount",{count:i.length}),i[0]?.trigger?w("moduleExplorer.candidateSuffix"):"",")"]})]})}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-8 relative",children:[r&&e.jsxs("div",{className:"absolute inset-0 bg-[var(--bg-surface)] backdrop-blur-[2px] z-10 flex flex-col items-center justify-center text-blue-600 px-4 xl:px-8 overflow-y-auto",children:[e.jsxs("div",{className:"relative mb-6",children:[e.jsx("div",{className:"w-16 h-16 border-4 border-blue-100 border-t-blue-600 rounded-full animate-spin"}),e.jsx(Jt,{size:H.xxl,className:"absolute inset-0 m-auto text-blue-600 animate-pulse"})]}),e.jsx("p",{className:"font-bold text-lg animate-pulse mb-1",children:a==="__project__"?w("moduleExplorer.fullProjectScanning"):w("moduleExplorer.moduleScanLabel",{name:a||"..."})}),e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] mb-4",children:o.status}),e.jsx("div",{className:"w-full max-w-md bg-[var(--bg-subtle)] rounded-full h-2.5 overflow-hidden",children:e.jsx("div",{className:"h-full bg-blue-600 rounded-full transition-all duration-500 ease-out",style:{width:`${Math.min(o.total?o.current/o.total*100:0,98)}%`}})}),e.jsx("p",{className:"text-xs text-[var(--fg-muted)] mt-3",children:o.total?`${Math.round(o.current/o.total*100)}%`:"0%"})]}),!r&&i.length===0&&e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-[var(--fg-muted)] text-center",children:[e.jsx(gs,{size:H.xxxl,className:"mb-4 opacity-20"}),e.jsx("p",{className:"font-medium text-[var(--fg-secondary)]",children:w("moduleExplorer.knowledgeExtract")}),e.jsx("p",{className:"text-xs mt-2 max-w-sm leading-relaxed",children:w("moduleExplorer.knowledgeExtractHint")})]}),!r&&a==="__project__"&&p?.summary&&e.jsxs("div",{className:`rounded-xl border p-4 ${p.summary.totalViolations>0?"border-amber-200 bg-amber-50":"border-emerald-200 bg-emerald-50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Ve,{size:H.md,className:p.summary.totalViolations>0?"text-amber-600":"text-emerald-600"}),e.jsx("span",{className:"text-sm font-bold text-[var(--fg-primary)]",children:w("moduleExplorer.guardAuditSummary")}),e.jsx("span",{className:"text-[10px] font-bold px-2 py-0.5 rounded-full bg-indigo-100 text-indigo-700 border border-indigo-200",children:"PROJECT SCAN"})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 xl:gap-6 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[var(--fg-secondary)]",children:w("moduleExplorer.auditedFiles")}),e.jsx("span",{className:"font-bold text-[var(--fg-primary)]",children:p.summary.totalFiles})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[var(--fg-secondary)]",children:w("moduleExplorer.totalViolationsLabel")}),e.jsx("span",{className:`font-bold ${p.summary.totalViolations>0?"text-amber-700":"text-emerald-700"}`,children:p.summary.totalViolations})]}),p.summary.errors>0&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(st,{size:H.sm,className:"text-red-500"}),e.jsx("span",{className:"font-bold text-red-700",children:w("moduleExplorer.errorsCount",{count:p.summary.errors})})]}),p.summary.warnings>0&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(st,{size:H.sm,className:"text-amber-500"}),e.jsx("span",{className:"font-bold text-amber-700",children:w("moduleExplorer.warningsCount",{count:p.summary.warnings})})]})]})]}),i.map((T,ee)=>e.jsx(Hi,{res:T,index:ee,editingCodeIndex:G,setEditingCodeIndex:_,expandedEditIndex:N,setExpandedEditIndex:E,handleUpdateScanResult:x,handleSaveExtracted:h,handlePromoteToCandidate:u,isSavingRecipe:D},ee))]})]}),e.jsx(zi,{isOpen:L,onClose:()=>$(!1),targetName:q,currentFile:U,language:s.find(T=>T.name===a)?.language||"unknown",onSelectRecipe:T=>{}})]})},Js=36,_s=2*Math.PI*Js,Fs=({value:t,label:s,suffix:a="",hint:r})=>{const o=Math.max(0,Math.min(100,t)),l=_s-o/100*_s,i=o>=80?"#3b82f6":o>=50?"#f59e0b":"#ef4444";return e.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[e.jsxs("svg",{width:"84",height:"84",viewBox:"0 0 84 84",children:[e.jsx("circle",{cx:"42",cy:"42",r:Js,fill:"none",className:"stroke-[var(--border-default)]",strokeWidth:"6",opacity:.3}),e.jsx("circle",{cx:"42",cy:"42",r:Js,fill:"none",stroke:i,strokeWidth:"6",strokeLinecap:"round",strokeDasharray:_s,strokeDashoffset:l,transform:"rotate(-90 42 42)",style:{transition:"stroke-dashoffset 0.6s ease"}}),e.jsx("text",{x:"42",y:"38",textAnchor:"middle",fontSize:"20",fontWeight:"700",fill:i,dominantBaseline:"central",children:o}),e.jsx("text",{x:"42",y:"58",textAnchor:"middle",fontSize:"10",className:"fill-[var(--fg-muted)]",dominantBaseline:"central",children:a})]}),e.jsx("span",{className:"text-xs font-medium text-[var(--fg-secondary)]",children:s}),r&&e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] text-center leading-tight",children:r})]})},La={PASS:"bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300 border-emerald-300 dark:border-emerald-700",WARN:"bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300 border-amber-300 dark:border-amber-700",FAIL:"bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300 border-red-300 dark:border-red-700"},qi=({status:t,label:s})=>{const a=t.toUpperCase(),r=La[a]||La.FAIL;return e.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[e.jsx("div",{className:`w-[84px] h-[84px] rounded-full flex items-center justify-center border-2 ${r}`,children:e.jsx("span",{className:"text-lg font-extrabold tracking-wide",children:a})}),e.jsx("span",{className:"text-xs font-medium text-[var(--fg-secondary)]",children:s})]})},Ui=["rules","violations","uncertain","boundaries","audit"],Wi={violations:"guard.tabViolations",uncertain:"guard.tabUncertain",rules:"guard.tabRules",boundaries:"guard.tabBoundaries",audit:"guard.tabAudit"},Vi=({onRefresh:t})=>{const{t:s}=Ae(),[a,r]=n.useState({}),[o,l]=n.useState([]),[i,p]=n.useState([]),[d,g]=n.useState(null),[x,h]=n.useState(!0),[u,m]=n.useState(null),[c,j]=n.useState(!0),[S,D]=n.useState("violations"),[I,P]=n.useState([]),[Y,w]=n.useState(0),[G,_]=n.useState(!1),N=async()=>{try{const[R,T]=await Promise.all([Z.getGuardRules(),Z.getGuardViolations()]);r(R?.rules||{}),p(R?.projectLanguages||[]),l(T?.runs||[])}catch{r({}),l([])}finally{h(!1)}};n.useEffect(()=>{N()},[]),n.useEffect(()=>{let R=!1;return j(!0),Z.getGuardReport().then(T=>{!R&&T&&m(T)}).catch(()=>{R||m(null)}).finally(()=>{R||j(!1)}),()=>{R=!0}},[]);const E=async()=>{if(window.confirm(s("guard.clearConfirm")))try{await Z.clearViolations(),N(),t?.()}catch(R){ne(ke(R,s("common.operationFailed")),{title:s("common.operationFailed"),type:"error"})}},$=n.useMemo(()=>{const R=Object.entries(a);return i.length===0?R:R.filter(([,T])=>!T.languages||T.languages.length===0?!0:T.languages.some(ee=>i.includes(ee)))},[a,i]),U=o.reduce((R,T)=>R+T.violations.length,0),[q,A]=n.useState("all"),[y,W]=n.useState("all"),re=n.useMemo(()=>{const R=new Set;for(const[,ee]of $)(ee.languages||[]).forEach(ie=>R.add(ie));const T=bs.filter(ee=>R.has(ee.id)).map(ee=>ee.id);for(const ee of R)T.includes(ee)||T.push(ee);return T},[$]),he=R=>bs.find(T=>T.id===R)?.label||R,ue=n.useMemo(()=>{const R={error:0,warning:0,info:0};for(const[,T]of $){const ee=T.severity;R[ee]!==void 0&&R[ee]++}return R},[$]),V=R=>{const T={safety:s("guard.categorySafety"),correctness:s("guard.categoryCorrectness"),performance:s("guard.categoryPerformance"),style:s("guard.categoryStyle")};return R?T[R]||R:"—"},B=(R,T)=>{const ee=`guardRuleMessages.${R}`,ie=s(ee);return ie!==ee?ie:T},oe=(R,T)=>{if(!T)return T;const ee=`guardRuleFixSuggestions.${R}`,ie=s(ee);return ie!==ee?ie:T},me=n.useMemo(()=>$.filter(([,R])=>!(q!=="all"&&!(R.languages||[]).includes(q)||y!=="all"&&R.severity!==y)),[$,q,y]);return x?e.jsx("div",{className:"p-6 text-[var(--fg-secondary)]",children:s("common.loading")}):e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"mb-4 flex flex-wrap justify-between items-center gap-3 shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-50 border border-blue-100 flex items-center justify-center shrink-0",children:e.jsx(Ve,{className:"text-blue-600",size:20})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-lg xl:text-xl font-bold text-[var(--fg-primary)]",children:s("guard.title")}),e.jsxs("p",{className:"text-xs text-[var(--fg-muted)] mt-0.5 truncate",children:[s("guard.summary"),i.length>0&&e.jsxs("span",{className:"ml-1.5",children:["· ",s("guard.currentProject"),":",i.map(R=>he(R)).join(" / ")]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("a",{href:Hl,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-all text-[var(--fg-secondary)] bg-[var(--bg-subtle)] border border-[var(--border-default)] hover:bg-[var(--bg-subtle)]",children:[e.jsx(Nr,{size:14})," ",s("guard.reportIssue")]}),o.length>0&&e.jsxs("button",{type:"button",onClick:E,className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-all text-red-600 bg-red-50 border border-red-200 hover:bg-red-100",children:[e.jsx(qe,{size:14})," ",s("guard.clearHistory")]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-[var(--bg-subtle)] border border-[var(--border-default)]",children:[e.jsx(Ve,{size:14,className:"text-[var(--fg-muted)]"}),e.jsxs("span",{className:"text-[var(--fg-secondary)]",children:[s("guard.tableHeaders.rule")," ",e.jsx("strong",{className:"text-[var(--fg-primary)]",children:$.length})]})]}),U>0&&e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-amber-50 border border-amber-100",children:[e.jsx(st,{size:14,className:"text-amber-400"}),e.jsx("span",{className:"text-amber-600",children:s("guard.totalViolations",{count:U})})]})]})]})]}),!c&&u&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-5 shrink-0",children:[e.jsx("div",{className:"flex items-center justify-center rounded-xl border border-[var(--border-default)] bg-[var(--bg-surface)] py-4 px-3",children:e.jsx(Fs,{value:u.complianceScore,label:s("guard.metricCompliance"),suffix:"/100",hint:s("guard.hintCompliance")})}),e.jsx("div",{className:"flex items-center justify-center rounded-xl border border-[var(--border-default)] bg-[var(--bg-surface)] py-4 px-3",children:e.jsx(Fs,{value:u.coverageScore,label:s("guard.metricCoverage"),suffix:"/100",hint:s("guard.hintCoverage")})}),e.jsx("div",{className:"flex items-center justify-center rounded-xl border border-[var(--border-default)] bg-[var(--bg-surface)] py-4 px-3",children:e.jsx(Fs,{value:u.confidenceScore,label:s("guard.metricConfidence"),suffix:"%",hint:s("guard.hintConfidence")})}),e.jsx("div",{className:"flex items-center justify-center rounded-xl border border-[var(--border-default)] bg-[var(--bg-surface)] py-4 px-3",children:e.jsx(qi,{status:u.qualityGate.status,label:s("guard.metricQualityGate")})})]}),c&&e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-5 shrink-0",children:Array.from({length:4}).map((R,T)=>e.jsx("div",{className:"flex items-center justify-center rounded-xl border border-[var(--border-default)] bg-[var(--bg-surface)] py-4 px-3 h-[130px]",children:e.jsx("div",{className:"w-[84px] h-[84px] rounded-full border-4 border-[var(--border-default)] animate-pulse"})},T))}),e.jsx("div",{className:"flex items-center gap-1.5 mb-4 shrink-0",children:Ui.map(R=>{const T=S===R;let ee=null;return R==="violations"&&U>0&&(ee=e.jsx("span",{className:"ml-1.5 text-[10px] px-1.5 py-0.5 rounded-full bg-amber-100 dark:bg-amber-900/50 text-amber-700 dark:text-amber-300 font-bold",children:U})),R==="uncertain"&&u?.uncertainSummary.total&&(ee=e.jsx("span",{className:"ml-1.5 text-[10px] px-1.5 py-0.5 rounded-full bg-purple-100 dark:bg-purple-900/50 text-purple-700 dark:text-purple-300 font-bold",children:u.uncertainSummary.total})),R==="rules"&&(ee=e.jsx("span",{className:"ml-1.5 text-[10px] px-1.5 py-0.5 rounded-full bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-300 font-bold",children:$.length})),R==="boundaries"&&u?.boundaries.length&&(ee=e.jsx("span",{className:"ml-1.5 text-[10px] px-1.5 py-0.5 rounded-full bg-indigo-100 dark:bg-indigo-900/50 text-indigo-700 dark:text-indigo-300 font-bold",children:u.boundaries.length})),e.jsxs("button",{type:"button",onClick:()=>D(R),className:`px-4 py-1.5 rounded-md text-xs font-medium transition-colors flex items-center ${T?"bg-[var(--accent-subtle)] text-[var(--accent)] border border-[var(--accent-emphasis)]":"text-[var(--fg-muted)] hover:bg-[var(--bg-subtle)] border border-transparent"}`,children:[s(Wi[R]),ee]},R)})}),e.jsxs("div",{className:"flex-1 overflow-y-auto pr-1 pb-6",children:[S==="rules"&&e.jsxs("section",{className:"mb-8",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 gap-3 flex-wrap",children:[e.jsxs("h3",{className:"text-sm font-semibold text-[var(--fg-primary)] flex items-center gap-1.5",children:[e.jsx(sa,{size:14,className:"text-[var(--fg-muted)]"}),s("guard.tableHeaders.rule"),e.jsxs("span",{className:"text-[var(--fg-muted)] font-normal",children:["(",me.length,"/",$.length,")"]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:e.jsxs("div",{className:"flex items-center gap-1 text-xs",children:[e.jsx("button",{onClick:()=>W("all"),className:`px-2 py-1 rounded-md border transition-all ${y==="all"?"bg-slate-700 text-white border-slate-700":"bg-[var(--bg-surface)] text-[var(--fg-secondary)] border-[var(--border-default)] hover:bg-[var(--bg-subtle)]"}`,children:s("common.all")}),e.jsxs("button",{onClick:()=>W("error"),className:`px-2 py-1 rounded-md border transition-all flex items-center gap-1 ${y==="error"?"bg-red-600 text-white border-red-600":"bg-[var(--bg-surface)] text-red-600 border-red-200 hover:bg-red-50"}`,children:[e.jsx(Et,{size:12})," error ",e.jsxs("span",{className:"opacity-70",children:["(",ue.error,")"]})]}),e.jsxs("button",{onClick:()=>W("warning"),className:`px-2 py-1 rounded-md border transition-all flex items-center gap-1 ${y==="warning"?"bg-amber-500 text-white border-amber-500":"bg-[var(--bg-surface)] text-amber-600 border-amber-200 hover:bg-amber-50"}`,children:[e.jsx(st,{size:12})," warning ",e.jsxs("span",{className:"opacity-70",children:["(",ue.warning,")"]})]}),e.jsxs("button",{onClick:()=>W("info"),className:`px-2 py-1 rounded-md border transition-all flex items-center gap-1 ${y==="info"?"bg-blue-500 text-white border-blue-500":"bg-[var(--bg-surface)] text-blue-600 border-blue-200 hover:bg-blue-50"}`,children:[e.jsx(Hs,{size:12})," info ",e.jsxs("span",{className:"opacity-70",children:["(",ue.info,")"]})]})]})})]}),e.jsxs("div",{className:"flex items-center gap-1.5 mb-3 flex-wrap",children:[e.jsx("button",{onClick:()=>A("all"),className:`px-2.5 py-1 rounded-full text-xs font-medium border transition-all ${q==="all"?"bg-slate-700 text-white border-slate-700":"bg-[var(--bg-surface)] text-[var(--fg-secondary)] border-[var(--border-default)] hover:bg-[var(--bg-subtle)]"}`,children:s("guard.allLanguages")}),re.map(R=>{const T=$.filter(([,ee])=>(ee.languages||[]).includes(R)).length;return e.jsxs("button",{onClick:()=>A(q===R?"all":R),className:`px-2.5 py-1 rounded-full text-xs font-medium border transition-all ${q===R?"bg-indigo-600 text-white border-indigo-600":"bg-[var(--bg-surface)] text-[var(--fg-secondary)] border-[var(--border-default)] hover:bg-[var(--bg-subtle)]"}`,children:[he(R)," ",e.jsxs("span",{className:"opacity-60",children:["(",T,")"]})]},R)})]}),e.jsxs("div",{className:"mb-3 flex items-start gap-2 px-3 py-2 rounded-lg bg-indigo-50 border border-indigo-100 text-xs text-indigo-700",children:[e.jsx(Hs,{size:14,className:"shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("span",{children:s("guard.codeLevelConfigTip")}),e.jsx("span",{className:"ml-1 font-mono text-[11px] text-indigo-500",children:s("guard.codeLevelConfigPath")})]})]}),e.jsx("div",{className:"bg-[var(--bg-surface)] border border-[var(--border-default)] rounded-xl overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-[var(--bg-subtle)] border-b border-[var(--border-default)]",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left py-2 px-4 font-medium text-[var(--fg-secondary)]",children:s("guard.ruleId")}),e.jsx("th",{className:"text-left py-2 px-4 font-medium text-[var(--fg-secondary)] w-20",children:s("guard.severity")}),e.jsx("th",{className:"text-left py-2 px-4 font-medium text-[var(--fg-secondary)]",children:s("guard.message")}),e.jsx("th",{className:"text-left py-2 px-4 font-medium text-[var(--fg-secondary)] w-28",children:s("guard.languagesLabel")}),e.jsx("th",{className:"text-left py-2 px-4 font-medium text-[var(--fg-secondary)] w-20",children:s("guard.category")})]})}),e.jsx("tbody",{children:me.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:5,className:"py-4 px-4 text-[var(--fg-secondary)] text-center",children:$.length===0?s("common.noData"):s("guard.noMatchingRules")})}):me.map(([R,T])=>e.jsxs("tr",{className:"border-b border-[var(--border-default)] last:border-0 hover:bg-[var(--bg-subtle)]",children:[e.jsx("td",{className:"py-2 px-4 font-mono text-xs text-[var(--fg-primary)]",children:R}),e.jsx("td",{className:"py-2 px-4",children:e.jsx("span",{className:`text-xs font-medium px-1.5 py-0.5 rounded ${T.severity==="error"?"bg-red-100 text-red-700":T.severity==="info"?"bg-blue-100 text-blue-700":"bg-amber-100 text-amber-700"}`,children:T.severity})}),e.jsxs("td",{className:"py-2 px-4 text-[var(--fg-primary)]",children:[B(R,T.message),T.fixSuggestion&&e.jsx("span",{className:"ml-1.5 text-xs text-emerald-600",title:oe(R,T.fixSuggestion),children:"💡"})]}),e.jsx("td",{className:"py-2 px-4",children:e.jsx("div",{className:"flex flex-wrap gap-1",children:(T.languages||[]).map(ee=>e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-indigo-50 text-indigo-600 border border-indigo-100 font-medium",children:he(ee)},ee))})}),e.jsx("td",{className:"py-2 px-4 text-xs text-[var(--fg-secondary)]",children:V(T.category)})]},R))})]})})]}),S==="violations"&&e.jsxs("section",{children:[e.jsx("h3",{className:"text-sm font-semibold text-[var(--fg-primary)] mb-3",children:s("guard.violationRecords",{runs:o.length,count:U})}),o.length===0?e.jsx("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-xl py-12 text-center text-[var(--fg-secondary)]",children:s("guard.noViolations")}):e.jsx("div",{className:"space-y-2",children:o.map(R=>{const T=d===R.id,ee=R.violations.length>0;return e.jsxs("div",{className:"bg-[var(--bg-surface)] border border-[var(--border-default)] rounded-xl overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>g(T?null:R.id),className:"w-full flex items-center gap-2 py-3 px-4 text-left hover:bg-[var(--bg-subtle)] transition-colors",children:[T?e.jsx(gt,{size:H.md}):e.jsx(Ke,{size:H.md}),e.jsx("span",{className:"font-mono text-sm text-[var(--fg-primary)]",children:R.filePath}),e.jsx("span",{className:"text-xs text-[var(--fg-muted)]",children:new Date(R.triggeredAt).toLocaleString()}),ee?e.jsxs("span",{className:"ml-auto flex items-center gap-1 text-amber-600 text-xs font-medium",children:[e.jsx(st,{size:H.sm})," ",s("guard.totalViolations",{count:R.violations.length})]}):e.jsx("span",{className:"ml-auto text-[var(--fg-muted)] text-xs",children:s("guard.noViolations")})]}),T&&e.jsx("div",{className:"border-t border-[var(--border-default)] bg-[var(--bg-subtle)] p-4",children:R.violations.length===0?e.jsx("p",{className:"text-sm text-[var(--fg-secondary)]",children:s("guard.noViolations")}):e.jsx("ul",{className:"space-y-2",children:R.violations.map((ie,xe)=>{const pe=a[ie.ruleId];return e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[ie.severity==="error"?e.jsx(Et,{size:H.md,className:"text-red-500 shrink-0 mt-0.5"}):e.jsx(st,{size:H.md,className:"text-amber-500 shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsxs("div",{children:[e.jsxs("span",{className:"font-mono text-xs text-[var(--fg-secondary)]",children:["[",ie.ruleId,"] ",ie.filePath?`${ie.filePath}:${ie.line}`:`L${ie.line}`]}),ie.dimension&&e.jsx("span",{className:"ml-1.5 text-xs px-1.5 py-0.5 rounded bg-[var(--bg-subtle)] text-[var(--fg-secondary)]",children:ie.dimension==="file"?s("guard.dimFile"):ie.dimension==="target"?s("guard.dimTarget"):s("guard.dimProject")}),e.jsx("span",{className:"text-[var(--fg-primary)] ml-2",children:B(ie.ruleId,ie.message)})]}),ie.snippet&&e.jsx("pre",{className:"text-xs text-[var(--fg-secondary)] bg-[var(--bg-subtle)] p-2 rounded overflow-x-auto",children:ie.snippet}),pe&&(pe.rationale||pe.fixSuggestions?.length||pe.sourceRecipe||pe.note)&&e.jsxs("div",{className:"mt-1 rounded-lg border border-blue-100 bg-blue-50/50 p-2.5 text-xs space-y-1.5",children:[pe.rationale&&e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx(Ue,{size:12,className:"text-blue-500 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsxs("span",{className:"font-bold text-blue-700",children:[s("guard.rationale"),":"]}),e.jsx("span",{className:"text-[var(--fg-secondary)]",children:pe.rationale})]})]}),pe.fixSuggestions&&pe.fixSuggestions.length>0&&e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx(Ks,{size:12,className:"text-emerald-500 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsxs("span",{className:"font-bold text-emerald-700",children:[s("guard.fixSuggestion"),":"]}),e.jsx("ul",{className:"mt-0.5 space-y-0.5 text-[var(--fg-secondary)]",children:pe.fixSuggestions.map((M,Ce)=>e.jsxs("li",{className:"flex items-start gap-1",children:[e.jsx("span",{className:"text-emerald-400 mt-0.5",children:"•"}),e.jsx("span",{children:M}),e.jsx("button",{className:"ml-1 text-blue-500 hover:text-blue-700",title:s("guard.copyFixSuggestion"),onClick:()=>navigator.clipboard.writeText(M).catch(()=>{}),children:"⎘"})]},Ce))})]})]}),pe.sourceRecipe&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ta,{size:12,className:"text-indigo-500 shrink-0"}),e.jsxs("span",{className:"font-bold text-indigo-700",children:[s("guard.sourceRecipe"),":"]}),e.jsx("span",{className:"text-indigo-600 font-mono",children:pe.sourceRecipe})]}),!pe.rationale&&pe.note&&e.jsxs("div",{className:"text-[var(--fg-secondary)] italic",children:[s("guard.noteLabel"),":",pe.note]})]})]})]},xe)})})})]},R.id)})})]}),S==="uncertain"&&e.jsx("section",{children:!u||u.uncertainSummary.total===0?e.jsx("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-xl py-12 text-center text-[var(--fg-secondary)]",children:"暂无不确定检查结果"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"rounded-xl border border-[var(--border-default)] bg-[var(--bg-surface)] p-4",children:[e.jsx("h4",{className:"text-sm font-semibold text-[var(--fg-primary)] mb-3",children:"按层级分布"}),e.jsx("div",{className:"space-y-2",children:Object.entries(u.uncertainSummary.byLayer).map(([R,T])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-[var(--fg-secondary)]",children:R}),e.jsx("span",{className:"text-sm font-mono font-bold text-purple-600",children:T})]},R))})]}),e.jsxs("div",{className:"rounded-xl border border-[var(--border-default)] bg-[var(--bg-surface)] p-4",children:[e.jsx("h4",{className:"text-sm font-semibold text-[var(--fg-primary)] mb-3",children:"按原因分布"}),e.jsx("div",{className:"space-y-2",children:Object.entries(u.uncertainSummary.byReason).map(([R,T])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-[var(--fg-secondary)]",children:R}),e.jsx("span",{className:"text-sm font-mono font-bold text-purple-600",children:T})]},R))})]})]}),e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-purple-50 border border-purple-100 text-xs text-purple-700",children:[e.jsx(st,{size:14,className:"shrink-0"}),e.jsxs("span",{children:["共 ",u.uncertainSummary.total," 项检查因静态分析局限或规则覆盖不足而无法确定结果,建议补充规则或人工复查。"]})]})]})}),S==="boundaries"&&e.jsx("section",{children:!u||u.boundaries.length===0?e.jsx("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-xl py-12 text-center text-[var(--fg-secondary)]",children:"暂无能力边界信息"}):e.jsx("div",{className:"space-y-3",children:u.boundaries.map((R,T)=>e.jsxs("div",{className:"rounded-xl border border-[var(--border-default)] bg-[var(--bg-surface)] p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-indigo-100 text-indigo-700 border border-indigo-200 font-medium",children:R.type}),e.jsx("span",{className:"text-sm font-medium text-[var(--fg-primary)]",children:R.description})]}),R.affectedRules.length>0&&e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[e.jsx("span",{className:"text-xs text-[var(--fg-muted)]",children:"受影响规则:"}),R.affectedRules.map(ee=>e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-slate-100 text-slate-600 border border-slate-200 font-mono",children:ee},ee))]}),e.jsxs("div",{className:"flex items-start gap-1.5 text-xs text-emerald-700 bg-emerald-50 border border-emerald-100 rounded-lg px-3 py-2",children:[e.jsx(Ks,{size:12,className:"shrink-0 mt-0.5"}),e.jsx("span",{children:R.suggestedAction})]})]},T))})}),S==="audit"&&e.jsx(Yi,{logs:I,total:Y,loading:G,onLoad:()=>{_(!0),Z.getAuditLogs({offset:0,limit:50}).then(R=>{P(R?.logs??[]),w(R?.total??0)}).catch(()=>{P([]),w(0)}).finally(()=>_(!1))},onLoadMore:()=>{Z.getAuditLogs({offset:I.length,limit:50}).then(R=>{P(T=>[...T,...R?.logs??[]]),w(R?.total??0)}).catch(()=>{})},t:s})]})]})},Ji={create:"bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300",update:"bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300",delete:"bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300",transition:"bg-purple-100 dark:bg-purple-900/40 text-purple-700 dark:text-purple-300"},Yi=({logs:t,total:s,loading:a,onLoad:r,onLoadMore:o,t:l})=>(n.useEffect(()=>{r()},[]),a&&t.length===0?e.jsx("div",{className:"flex items-center justify-center h-32 text-[var(--fg-secondary)]",children:l("common.loading")}):t.length===0?e.jsx("div",{className:"flex items-center justify-center h-32 text-[var(--fg-secondary)]",children:l("guard.noAuditLogs")}):e.jsxs("section",{className:"space-y-2",children:[t.map((i,p)=>{const d=Ji[i.action]??"bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-300",g=i.result==="success"?"text-emerald-600 dark:text-emerald-400":i.result==="failure"?"text-red-600 dark:text-red-400":"text-[var(--fg-secondary)]";return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-[var(--bg-surface)] border border-[var(--border-default)]",children:[e.jsx("span",{className:"text-xs text-[var(--fg-muted)] shrink-0 w-36 tabular-nums",children:new Date(i.timestamp).toLocaleString()}),e.jsx("span",{className:"text-xs font-semibold text-[var(--fg-primary)] shrink-0",children:i.actor}),e.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-medium shrink-0 ${d}`,children:i.action}),e.jsx("span",{className:`text-xs font-medium shrink-0 ${g}`,children:i.result==="success"?"✓":i.result==="failure"?"✗":i.result}),e.jsx("span",{className:"text-xs text-[var(--fg-secondary)] truncate min-w-0 flex-1",title:i.target,children:i.target})]},p)}),t.length<s&&e.jsx("div",{className:"text-center py-2",children:e.jsx("button",{type:"button",onClick:o,className:"text-xs font-medium text-blue-600 dark:text-blue-400 hover:underline",children:l("guard.loadMore")})})]}));function Qi(t,s){const a=t>40,r=t>120,o=r?100:a?120:140,l=r?30:a?34:40,i=r?6:a?8:16,p=r?6:a?8:12,d=r?4:a?5:6,g=r?4:a?5:8,x=r?12:a?16:24,h=r?10:a?14:20,u=r?9:a?10.5:12,m=r?10:a?13:16,c=Math.max(400,s)-x*2-h*2,j=Math.max(4,Math.floor((c+i)/(o+i)));return{nodeWidth:o,nodeHeight:l,nodeGap:i,layerGap:p,layerPadY:d,subRowGap:g,padding:x,layerSidePadding:h,fontSize:u,labelMaxChars:m,maxPerRow:j}}function Zi(t,s){const a=new Set(t.map(p=>p.id)),r=new Map;for(const p of s)!a.has(p.from)||!a.has(p.to)||(r.has(p.from)||r.set(p.from,[]),r.get(p.from).push(p.to));const o=new Map,l=new Set;function i(p){if(o.has(p))return o.get(p);if(l.has(p))return 0;l.add(p);const d=r.get(p);if(!d||d.length===0)return o.set(p,0),l.delete(p),0;const g=1+Math.max(...d.map(i));return o.set(p,g),l.delete(p),g}return t.forEach(p=>i(p.id)),o}function Xi(t,s){return Math.ceil(t/s)}function ec(t,s,a){const r=Zi(t,s),o=new Map;for(const m of t){const c=r.get(m.id)??0;o.has(c)||o.set(c,[]),o.get(c).push(m.id)}const l=[...new Set(r.values())].sort((m,c)=>m-c),i=[...l].reverse(),p=new Map,d=new Map,g=Math.min(a.maxPerRow,Math.max(...l.map(m=>(o.get(m)??[]).length),1)),x=g*a.nodeWidth+(g-1)*a.nodeGap+a.layerSidePadding*2,h=a.padding+x/2;let u=a.padding;return i.forEach((m,c)=>{const j=o.get(m)??[],S=Xi(j.length,a.maxPerRow);let D=0;for(let w=0;w<S;w++){const G=j.slice(w*a.maxPerRow,(w+1)*a.maxPerRow),_=G.length*a.nodeWidth+(G.length-1)*a.nodeGap;D=Math.max(D,_)}const I=D+a.layerSidePadding*2,P=u;u+=a.layerPadY;for(let w=0;w<S;w++){const G=j.slice(w*a.maxPerRow,(w+1)*a.maxPerRow),_=G.length*a.nodeWidth+(G.length-1)*a.nodeGap;G.forEach((N,E)=>{const L=h-_/2+E*(a.nodeWidth+a.nodeGap)+a.nodeWidth/2,$=u+a.nodeHeight/2;p.set(N,{x:L,y:$})}),u+=a.nodeHeight+(w<S-1?a.subRowGap:0)}u+=a.layerPadY;const Y=u-P;d.set(m,{y:P,h:Y,contentW:I}),c<i.length-1&&(u+=a.layerGap)}),{positions:p,tiers:r,tierOrder:l,tierYRanges:d,totalWidth:x}}const tc=()=>{const{t}=Ae(),{isDark:s}=Ns(),[a,r]=n.useState(null),[o,l]=n.useState(!0),[i,p]=n.useState(null),[d,g]=n.useState(null),[x,h]=n.useState("package"),[u,m]=n.useState("all"),[c,j]=n.useState(1),S=n.useRef(null),[D,I]=n.useState(900);n.useEffect(()=>{const M=S.current;if(!M)return;const Ce=new ResizeObserver(F=>{for(const Se of F)I(Se.contentRect.width)});return Ce.observe(M),I(M.clientWidth),()=>Ce.disconnect()},[]);const P=n.useCallback(()=>j(M=>Math.min(M+.2,3)),[]),Y=n.useCallback(()=>j(M=>Math.max(M-.2,.3)),[]),w=n.useCallback(()=>j(1),[]),G=async()=>{l(!0),p(null);try{const M=await Z.getDepGraph(x);r({nodes:Array.isArray(M?.nodes)?M.nodes:[],edges:Array.isArray(M?.edges)?M.edges:[],projectRoot:M?.projectRoot??null,generatedAt:M?.generatedAt})}catch(M){p(ke(M,"Failed to load dependency graph"))}finally{l(!1)}};n.useEffect(()=>{G()},[x]);const _=Array.isArray(a?.nodes)?a.nodes:[],N=Array.isArray(a?.edges)?a.edges:[],E=_.some(M=>M.type==="internal"||M.type==="external"),L=n.useMemo(()=>!E||u==="all"?_:u==="internal"?_.filter(M=>M.type!=="external"):_.filter(M=>M.type!=="internal"),[_,u,E]),$=n.useMemo(()=>new Set(L.map(M=>M.id)),[L]),U=n.useMemo(()=>N.filter(M=>$.has(M.from)||$.has(M.to)),[N,$]),q=n.useMemo(()=>Qi(L.length,D),[L.length,D]),{positions:A,tiers:y,tierOrder:W,tierYRanges:re,totalWidth:he}=n.useMemo(()=>ec(L,U,q),[L,U,q]),ue=n.useMemo(()=>{const M=new Map;return L.forEach(Ce=>{const F=y.get(Ce.id)??0;M.has(F)||M.set(F,[]),M.get(F).push(Ce.id)}),M},[L,y]),V=n.useMemo(()=>[...W].reverse(),[W]),{dependsOn:B,dependedBy:oe}=n.useMemo(()=>{const M=new Map,Ce=new Map;return U.forEach(F=>{M.has(F.from)||M.set(F.from,[]),M.get(F.from).push(F.to),Ce.has(F.to)||Ce.set(F.to,[]),Ce.get(F.to).push(F.from)}),{dependsOn:M,dependedBy:Ce}},[U]);Math.min(q.maxPerRow,Math.max(...W.map(M=>(ue.get(M)??[]).length),1));const me=q.padding*2+he,R=Math.max(...[...A.values()].map(M=>M.y),0),T=Math.max(320,R+q.nodeHeight/2+q.padding),ee=n.useMemo(()=>{if(D<=0||me<=0)return 1;const M=D/me;return M<1?M:1},[D,me]),ie=c*ee,xe=s?[{bg:"rgba(59, 130, 246, 0.14)",border:"rgba(59, 130, 246, 0.40)",text:"rgb(147 197 253)"},{bg:"rgba(34, 197, 94, 0.14)",border:"rgba(34, 197, 94, 0.40)",text:"rgb(134 239 172)"},{bg:"rgba(234, 179, 8, 0.14)",border:"rgba(234, 179, 8, 0.40)",text:"rgb(253 224 71)"},{bg:"rgba(249, 115, 22, 0.14)",border:"rgba(249, 115, 22, 0.40)",text:"rgb(253 186 116)"},{bg:"rgba(139, 92, 246, 0.14)",border:"rgba(139, 92, 246, 0.40)",text:"rgb(196 181 253)"}]:[{bg:"rgb(239 246 255)",border:"rgb(147 197 253)",text:"rgb(30 64 175)"},{bg:"rgb(240 253 244)",border:"rgb(134 239 172)",text:"rgb(22 101 52)"},{bg:"rgb(254 249 195)",border:"rgb(253 224 71)",text:"rgb(113 63 18)"},{bg:"rgb(254 243 199)",border:"rgb(253 186 116)",text:"rgb(154 52 18)"},{bg:"rgb(243 232 255)",border:"rgb(216 180 254)",text:"rgb(91 33 182)"}],pe=M=>xe[Math.min(M,xe.length-1)]??xe[0];return o?e.jsx("div",{className:"flex items-center justify-center min-h-[320px]",children:e.jsx("div",{className:"animate-spin rounded-full h-10 w-10 border-2 border-blue-600 border-t-transparent"})}):i?e.jsxs("div",{className:"rounded-xl border border-red-200 bg-red-50 p-6 text-red-700 shadow-sm",children:[e.jsx("p",{children:i}),e.jsx("button",{type:"button",onClick:G,className:"mt-4 px-4 py-2 rounded-lg bg-red-100 hover:bg-red-200 text-red-800 font-medium text-sm transition-colors",children:t("depGraph.retry")})]}):!a||_.length===0?e.jsxs("div",{className:"rounded-xl border border-[var(--border-default)] bg-[var(--bg-subtle)] p-8 text-[var(--fg-secondary)] shadow-sm",children:[e.jsx("p",{className:"font-medium text-[var(--fg-primary)]",children:t("depGraph.noDataTitle")}),e.jsx("p",{className:"mt-2 text-sm",children:t("depGraph.noDataDesc")})]}):e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2 flex-shrink-0",children:[e.jsx("div",{className:"flex items-center gap-4 text-xs text-[var(--fg-secondary)]",children:E&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded border-2 border-[var(--border-emphasis)] bg-[var(--bg-surface)]"})," ",t("depGraph.projectRoot")]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded border-2 border-green-400 bg-green-50"})," ",t("depGraph.filterInternal")]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded border-2 border-amber-400 bg-amber-50 border-dashed"})," ",t("depGraph.filterExternal")]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded border-2 border-amber-400 bg-amber-50 border-dashed opacity-50"})," ",t("depGraph.labelIndirect")]})]})}),e.jsxs("div",{className:"flex items-center gap-1 ml-2 flex-shrink-0",children:[e.jsx("button",{type:"button",onClick:P,className:"p-1 rounded-md transition-colors bg-[var(--bg-subtle)] hover:bg-[var(--border-default)] text-[var(--fg-secondary)]",title:t("depGraph.zoomIn")||"Zoom in",children:e.jsx(Sr,{size:H.sm})}),e.jsx("button",{type:"button",onClick:Y,className:"p-1 rounded-md transition-colors bg-[var(--bg-subtle)] hover:bg-[var(--border-default)] text-[var(--fg-secondary)]",title:t("depGraph.zoomOut")||"Zoom out",children:e.jsx(Ar,{size:H.sm})}),e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)] min-w-[3em] text-center tabular-nums",children:[Math.round(ie*100),"%"]}),e.jsx("button",{type:"button",onClick:w,className:"p-1 rounded-md transition-colors bg-[var(--bg-subtle)] hover:bg-[var(--border-default)] text-[var(--fg-secondary)]",title:t("depGraph.resetZoom")||"Reset zoom",children:e.jsx(ea,{size:H.sm})}),e.jsx("button",{type:"button",onClick:()=>G(),className:"p-1 rounded-md transition-colors bg-[var(--bg-subtle)] hover:bg-[var(--border-default)] text-[var(--fg-secondary)]",title:t("depGraph.refresh")||"Refresh",children:e.jsx(at,{size:H.sm})})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto pr-1 pb-6",children:[e.jsxs("div",{ref:S,className:"rounded-xl border border-[var(--border-default)] bg-[var(--bg-subtle)] overflow-auto shadow-sm relative",style:{minHeight:320,maxHeight:"75vh"},children:[e.jsxs("svg",{width:me*ie,height:T*ie,viewBox:`0 0 ${me} ${T}`,className:"block mx-auto",children:[e.jsx("defs",{children:e.jsx("filter",{id:"nodeShadow",x:"-20%",y:"-20%",width:"140%",height:"140%",children:e.jsx("feDropShadow",{dx:"0",dy:"2",stdDeviation:"2",floodOpacity:"0.12"})})}),V.map((M,Ce)=>{const F=pe(Ce),Se=re.get(M);return Se?e.jsx("rect",{x:q.padding,y:Se.y,width:he,height:Se.h,rx:8,fill:F.bg,stroke:F.border,strokeWidth:s?1.5:1,opacity:s?1:.6},M):null}),L.map(M=>{const Ce=A.get(M.id);if(!Ce)return null;const F=y.get(M.id)??0,Se=pe(V.indexOf(F)),Te=M.label.length>q.labelMaxChars?M.label.slice(0,q.labelMaxChars-1)+"…":M.label,_e=d===M.id,Me=d?(B.get(d)??[]).includes(M.id):!1,te=d?(oe.get(d)??[]).includes(M.id):!1,de=d&&!_e&&!Me&&!te,f=M.type==="external"?s?{fill:"rgba(234, 179, 8, 0.1)",stroke:"rgb(202 138 4)",text:"rgb(253 224 71)",badge:"EXT"}:{fill:"rgb(254 252 232)",stroke:"rgb(234 179 8)",text:"rgb(113 63 18)",badge:"EXT"}:M.type==="internal"?s?{fill:"rgba(34, 197, 94, 0.1)",stroke:"rgb(22 163 74)",text:"rgb(134 239 172)",badge:""}:{fill:"rgb(240 253 244)",stroke:"rgb(74 222 128)",text:"rgb(22 101 52)",badge:""}:s?{fill:"#1e2433",stroke:Se.border,text:Se.text,badge:""}:{fill:"white",stroke:Se.border,text:Se.text,badge:""},J=d?_e?s?{fill:"#283040",stroke:"rgb(59 130 246)",text:"rgb(147 197 253)",strokeWidth:3,opacity:1}:{fill:"white",stroke:"rgb(59 130 246)",text:"rgb(30 64 175)",strokeWidth:3,opacity:1}:Me?s?{fill:"rgba(34, 197, 94, 0.12)",stroke:"rgb(34 197 94)",text:"rgb(134 239 172)",strokeWidth:2,opacity:1}:{fill:"rgb(240 253 244)",stroke:"rgb(34 197 94)",text:"rgb(22 101 52)",strokeWidth:2,opacity:1}:te?s?{fill:"rgba(139, 92, 246, 0.12)",stroke:"rgb(139 92 246)",text:"rgb(196 181 253)",strokeWidth:2,opacity:1}:{fill:"rgb(245 243 255)",stroke:"rgb(139 92 246)",text:"rgb(91 33 182)",strokeWidth:2,opacity:1}:s?{fill:"#1a1b23",stroke:"rgb(51 65 85)",text:"rgb(100 116 139)",strokeWidth:1,opacity:.6}:{fill:"rgb(248 250 252)",stroke:"rgb(203 213 225)",text:"rgb(148 163 184)",strokeWidth:1,opacity:.6}:{fill:f.fill,stroke:f.stroke,text:f.text,strokeWidth:2,opacity:M.indirect?.55:1};return e.jsxs("g",{style:{cursor:"pointer",opacity:J.opacity},onClick:()=>g(_e?null:M.id),children:[e.jsx("title",{children:M.label}),e.jsx("rect",{x:Ce.x-q.nodeWidth/2,y:Ce.y-q.nodeHeight/2,width:q.nodeWidth,height:q.nodeHeight,rx:10,ry:10,fill:J.fill,stroke:J.stroke,strokeWidth:J.strokeWidth,filter:de?void 0:"url(#nodeShadow)",strokeDasharray:M.type==="external"?"4 2":void 0}),e.jsx("text",{x:Ce.x,y:Ce.y+(f.badge?-2:0),textAnchor:"middle",dominantBaseline:"middle",fontSize:q.fontSize,fontWeight:"600",fill:J.text,pointerEvents:"none",children:Te}),f.badge&&q.nodeHeight>=32&&e.jsx("text",{x:Ce.x,y:Ce.y+12,textAnchor:"middle",dominantBaseline:"middle",fontSize:Math.max(7,q.fontSize-3),fontWeight:"500",fill:f.text,opacity:.6,pointerEvents:"none",children:f.badge})]},M.id)})]}),d&&e.jsxs("div",{className:"absolute top-4 right-4 w-72 rounded-xl border border-[var(--border-default)] bg-[var(--bg-surface)] shadow-lg z-10 p-4",role:"dialog","aria-label":t("depGraph.dependencies"),children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 pb-2 border-b border-[var(--border-default)]",children:[e.jsx("span",{className:"font-bold text-[var(--fg-primary)]",children:d}),e.jsx("button",{type:"button",onClick:()=>g(null),className:"text-[var(--fg-muted)] hover:text-[var(--fg-secondary)] text-lg leading-none","aria-label":t("depGraph.close"),children:"×"})]}),e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-[var(--fg-secondary)] mb-1",children:t("depGraph.dependencies")}),e.jsx("ul",{className:"text-[var(--fg-primary)] space-y-0.5",children:(B.get(d)??[]).length===0?e.jsx("li",{className:"text-[var(--fg-muted)]",children:t("depGraph.none")}):(B.get(d)??[]).map(M=>e.jsxs("li",{children:["→ ",M]},M))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-[var(--fg-secondary)] mb-1",children:t("depGraph.dependents")}),e.jsx("ul",{className:"text-[var(--fg-primary)] space-y-0.5",children:(oe.get(d)??[]).length===0?e.jsx("li",{className:"text-[var(--fg-muted)]",children:t("depGraph.none")}):(oe.get(d)??[]).map(M=>e.jsxs("li",{children:["← ",M]},M))})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"rounded-xl border border-[var(--border-default)] bg-[var(--bg-surface)] p-5 shadow-sm",children:[e.jsxs("h3",{className:"text-sm font-bold text-[var(--fg-primary)] mb-3 pb-2 border-b border-[var(--border-default)]",children:[t("depGraph.packageList")," (",L.length,")"]}),e.jsx("ul",{className:"text-sm space-y-3 max-h-[280px] overflow-y-auto pr-1",children:L.map(M=>e.jsxs("li",{className:"pb-3 border-b border-[var(--border-default)] last:border-0 last:pb-0",children:[e.jsxs("div",{className:"flex items-baseline gap-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-[var(--fg-primary)]",children:M.label||M.id}),M.type==="external"&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-amber-50 text-amber-700 border border-amber-200 font-medium",children:t("depGraph.labelExternal")}),M.type==="internal"&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-emerald-50 text-emerald-700 border border-emerald-200 font-medium",children:t("depGraph.labelInternal")}),M.indirect&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-[var(--bg-subtle)] text-[var(--fg-secondary)] border border-[var(--border-default)] font-medium",children:t("depGraph.labelIndirect")}),M.packageDir&&e.jsxs("span",{className:"text-[var(--fg-secondary)] text-xs",children:["· ",M.packageDir]})]}),M.fullPath&&e.jsx("div",{className:"mt-1 text-[var(--fg-muted)] text-xs truncate",children:M.fullPath}),M.targets&&M.targets.length>0&&e.jsxs("div",{className:"mt-1.5 text-[var(--fg-secondary)] text-xs pl-0",children:["Targets: ",e.jsx("span",{className:"text-[var(--fg-secondary)]",children:M.targets.join(", ")})]})]},M.id))})]}),e.jsxs("div",{className:"rounded-xl border border-[var(--border-default)] bg-[var(--bg-surface)] p-5 shadow-sm",children:[e.jsxs("h3",{className:"text-sm font-bold text-[var(--fg-primary)] mb-3 pb-2 border-b border-[var(--border-default)]",children:[t("depGraph.depRelations")," (",U.length,")"]}),e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] mb-2",children:t("depGraph.depRelationsDesc")}),e.jsx("ul",{className:"text-sm space-y-2 max-h-[280px] overflow-y-auto pr-1",children:U.map((M,Ce)=>e.jsxs("li",{className:"flex items-center gap-2 text-[var(--fg-primary)]",children:[e.jsx("span",{className:"font-semibold text-[var(--fg-primary)]",children:M.from}),e.jsx("span",{className:"text-[var(--fg-muted)] shrink-0",children:"→"}),e.jsx("span",{className:"font-semibold text-[var(--fg-primary)]",children:M.to})]},`${M.from}-${M.to}-${Ce}`))})]}),x==="target"&&e.jsxs("p",{className:"text-xs text-[var(--fg-secondary)] mt-2",children:[t("depGraph.targetHint"),e.jsx("span",{className:"font-mono",children:"Package::Target"})]})]})]})]})},sc=28,ac=22,rc=50,nc=11,lc=10,dt={depends_on:"#3b82f6",requires:"#3b82f6",extends:"#10b981",implements:"#10b981",inherits:"#10b981",enforces:"#f59e0b",related:"#8b5cf6",conflicts:"#ef4444",calls:"#06b6d4",prerequisite:"#f97316",data_flow_to:"#14b8a6",references:"#6b7280",alternative:"#a855f7",deprecated_by:"#dc2626",solves:"#22c55e"},oc={depends_on:"依赖",requires:"需要",extends:"扩展",implements:"实现",inherits:"继承",enforces:"约束",related:"关联",conflicts:"冲突",calls:"调用",prerequisite:"前置",data_flow_to:"数据流",references:"引用",alternative:"替代",deprecated_by:"废弃",solves:"解决"},zs=[{bg:"#eff6ff",border:"#bfdbfe",text:"#1d4ed8"},{bg:"#f0fdf4",border:"#bbf7d0",text:"#15803d"},{bg:"#fef3c7",border:"#fde68a",text:"#b45309"},{bg:"#fdf2f8",border:"#fbcfe8",text:"#be185d"},{bg:"#f5f3ff",border:"#ddd6fe",text:"#7c3aed"},{bg:"#ecfeff",border:"#a5f3fc",text:"#0e7490"},{bg:"#fff7ed",border:"#fed7aa",text:"#c2410c"},{bg:"#f0f9ff",border:"#bae6fd",text:"#0369a1"},{bg:"#fefce8",border:"#fef08a",text:"#a16207"},{bg:"#f1f5f9",border:"#cbd5e1",text:"#475569"}],ic=[{bg:"rgba(59,130,246,0.08)",border:"rgba(59,130,246,0.25)",text:"#60a5fa"},{bg:"rgba(34,197,94,0.08)",border:"rgba(34,197,94,0.25)",text:"#4ade80"},{bg:"rgba(245,158,11,0.08)",border:"rgba(245,158,11,0.25)",text:"#fbbf24"},{bg:"rgba(236,72,153,0.08)",border:"rgba(236,72,153,0.25)",text:"#f472b6"},{bg:"rgba(139,92,246,0.08)",border:"rgba(139,92,246,0.25)",text:"#a78bfa"},{bg:"rgba(6,182,212,0.08)",border:"rgba(6,182,212,0.25)",text:"#22d3ee"},{bg:"rgba(249,115,22,0.08)",border:"rgba(249,115,22,0.25)",text:"#fb923c"},{bg:"rgba(14,165,233,0.08)",border:"rgba(14,165,233,0.25)",text:"#38bdf8"},{bg:"rgba(234,179,8,0.08)",border:"rgba(234,179,8,0.25)",text:"#facc15"},{bg:"rgba(148,163,184,0.08)",border:"rgba(148,163,184,0.25)",text:"#94a3b8"}];function jt(t){return Math.min(rc,Math.max(ac,sc+t*2))}function _a(t,s){return t.length<=s?t:t.substring(0,s-1)+"…"}function cc(t,s,a,r){const o=new Map;for(const x of t)o.set(x.fromId,(o.get(x.fromId)||0)+1),o.set(x.toId,(o.get(x.toId)||0)+1);const l=[...o.keys()],i=[...new Set(l.map(x=>r[x]||"general"))].sort(),p=new Map,d=Math.ceil(Math.sqrt(i.length)),g=400;return i.forEach((x,h)=>{const u=h%d,m=Math.floor(h/d);p.set(x,{x:450+(u-(d-1)/2)*g,y:350+(m-(Math.ceil(i.length/d)-1)/2)*g})}),l.map(x=>{const h=r[x]||"general",u=p.get(h)||{x:450,y:350},m=Math.random()*2*Math.PI,c=40+Math.random()*80;return{id:x,label:s[x]||x,type:a[x]||"recipe",group:h,x:u.x+c*Math.cos(m),y:u.y+c*Math.sin(m),vx:0,vy:0,degree:o.get(x)||1}})}function dc(t,s,a=200){const r=t.map(i=>({...i})),o=new Map(r.map(i=>[i.id,i]));function l(){const i=new Map;for(const p of r){const d=i.get(p.group);d?(d.x+=p.x,d.y+=p.y,d.count++):i.set(p.group,{x:p.x,y:p.y,count:1})}for(const[,p]of i)p.x/=p.count,p.y/=p.count;return i}for(let i=0;i<a;i++){const p=1-i/a,d=18e3*p,g=.015,x=.8,h=l();for(let m=0;m<r.length;m++)for(let c=m+1;c<r.length;c++){const j=r[m],S=r[c];let D=S.x-j.x,I=S.y-j.y,P=Math.sqrt(D*D+I*I)||1;const Y=jt(j.degree)+jt(S.degree)+60,w=Math.max(P,1),G=j.group===S.group?.6:1.4,_=d*G/(w*w),N=P<Y?(Y-P)*.5:0,E=_+N,L=D/w*E,$=I/w*E;j.vx-=L,j.vy-=$,S.vx+=L,S.vy+=$}for(const m of s){const c=o.get(m.fromId),j=o.get(m.toId);if(!c||!j)continue;let S=j.x-c.x,D=j.y-c.y,I=Math.sqrt(S*S+D*D)||1;const P=c.group===j.group?140:280,Y=g*(I-P),w=S/I*Y,G=D/I*Y;c.vx+=w,c.vy+=G,j.vx-=w,j.vy-=G}const u=.008*p;for(const m of r){const c=h.get(m.group);c&&(m.vx+=(c.x-m.x)*u,m.vy+=(c.y-m.y)*u)}for(const m of r)m.vx*=x,m.vy*=x,m.x+=m.vx,m.y+=m.vy}return r}function uc(t,s,a,r,o,l,i=0){const p=a-t,d=r-s,g=Math.sqrt(p*p+d*d)||1,x=p/g,h=d/g,u=t+x*o,m=s+h*o,c=a-x*l,j=r-h*l;if(i===0)return`M${u},${m}L${c},${j}`;const S=(u+c)/2+-h*i,D=(m+j)/2+x*i;return`M${u},${m}Q${S},${D},${c},${j}`}const mc=()=>{const{t}=Ae(),{isDark:s}=Ns(),a=s?ic:zs,r=b=>{const z={depends_on:"knowledgeGraph.relationDependsOn",requires:"knowledgeGraph.relationRequires",extends:"knowledgeGraph.relationExtends",implements:"knowledgeGraph.relationImplements",inherits:"knowledgeGraph.relationInherits",enforces:"knowledgeGraph.relationEnforces",related:"knowledgeGraph.relationAssociates",conflicts:"knowledgeGraph.relationConflicts",calls:"knowledgeGraph.relationCalls",prerequisite:"knowledgeGraph.relationPrerequisite",data_flow_to:"knowledgeGraph.relationDataFlow",references:"knowledgeGraph.relationReferences",alternative:"knowledgeGraph.relationAlternative",deprecated_by:"knowledgeGraph.relationDeprecatedBy",solves:"knowledgeGraph.relationSolves"};return z[b]?t(z[b]):oc[b]||b},[o,l]=n.useState([]),[i,p]=n.useState({}),[d,g]=n.useState({}),[x,h]=n.useState({}),[u,m]=n.useState(null),[c,j]=n.useState(!0),[S,D]=n.useState(null),[I,P]=n.useState(null),[Y,w]=n.useState(null),[G,_]=n.useState(null),[N,E]=n.useState(!1),[L,$]=n.useState(null),[U,q]=n.useState(!1),[A,y]=n.useState(1),[W,re]=n.useState({x:0,y:0}),he=n.useRef(null),ue=n.useRef(null),V=n.useRef(!1),B=n.useRef({x:0,y:0}),oe=async()=>{j(!0),D(null);try{const[b,z]=await Promise.all([Z.getKnowledgeGraph(),Z.getGraphStats()]);l(b.edges||[]),p(b.nodeLabels||{}),g(b.nodeTypes||{}),h(b.nodeCategories||{}),m(z)}catch(b){D(ke(b,t("knowledgeGraph.loadFailed")))}finally{j(!1)}};n.useEffect(()=>{oe()},[]),n.useEffect(()=>{Z.getDiscoverRelationsStatus().then(b=>{b.status==="running"&&(E(!0),$(t("knowledgeGraph.discoverAnalyzing",{elapsed:b.elapsed??0})))}).catch(()=>{})},[]),n.useEffect(()=>{if(!N)return;let b=0;const z=240,le=setInterval(async()=>{if(b++,b>z){clearInterval(le),E(!1),q(!0),$(t("knowledgeGraph.discoverPollTimeout"));return}try{const O=await Z.getDiscoverRelationsStatus();if(O.status==="done"){E(!1);const v=O.discovered??0,se=O.totalPairs??0,be=O.batchErrors??0;if(v===0&&be===0)q(!1),$(t("knowledgeGraph.discoverNoResults",{pairs:se}));else if(v===0&&be>0)q(!0),$(t("knowledgeGraph.discoverBatchErrors",{errors:be}));else{q(!1);const fe=be>0?t("knowledgeGraph.discoverBatchFailed",{count:be}):"";$(t("knowledgeGraph.discoverSuccess",{count:v,pairs:se,failMsg:fe}))}oe()}else if(O.status==="error"){E(!1),q(!0);const v=O.error||t("knowledgeGraph.unknownError");v.includes("AI Provider")||v.includes("API Key")?$(t("knowledgeGraph.discoverAiNotConfigured",{error:v})):v.includes("超时")||v.includes("timeout")?$(t("knowledgeGraph.discoverTimeout",{error:v})):$(t("knowledgeGraph.discoverFailed",{error:v}))}else O.status==="running"&&$(t("knowledgeGraph.discoverAnalyzing",{elapsed:O.elapsed??0}))}catch{}},3e3);return()=>clearInterval(le)},[N]);const me=n.useCallback(async()=>{$(null),q(!1);try{const b=await Z.discoverRelations();if(b.status==="empty"){$(b.message||t("knowledgeGraph.discoverInsufficientRecipes"));return}if(b.status==="timeout"){q(!0),$(b.error||t("knowledgeGraph.discoverPreviousTimeout"));return}if(b.status==="running"){E(!0),$(t("knowledgeGraph.discoverRunning"));return}E(!0),$(t("knowledgeGraph.discoverStarted"))}catch(b){q(!0);const z=ke(b,t("knowledgeGraph.unknownError"));z.includes("ChatAgent")||z.includes("AI Provider")?$(t("knowledgeGraph.discoverAiUnavailable",{error:z})):$(t("knowledgeGraph.discoverStartFailed",{error:z}))}},[t]),R=n.useMemo(()=>{if(o.length===0)return[];const b=cc(o,i,d,x);return dc(b,o)},[o,i,d,x]),T=n.useMemo(()=>{const b=new Map;for(const O of R){const v=b.get(O.group)||[];v.push(O),b.set(O.group,v)}const z=[],le=[...b.keys()].sort();for(const O of le){const v=b.get(O);if(v.length===0)continue;let se=0,be=0;for(const ae of v)se+=ae.x,be+=ae.y;se/=v.length,be/=v.length;let fe=0,De=0;for(const ae of v){const we=jt(ae.degree);fe=Math.max(fe,Math.abs(ae.x-se)+we+35),De=Math.max(De,Math.abs(ae.y-be)+we+35)}z.push({group:O,cx:se,cy:be,rx:Math.max(fe,60),ry:Math.max(De,60),count:v.length})}return z},[R]),ee=n.useMemo(()=>{const b=[...new Set(R.map(le=>le.group))].sort(),z={};return b.forEach((le,O)=>{z[le]=a[O%a.length]}),z},[R,a]),ie=n.useMemo(()=>{if(R.length===0)return{x:0,y:0,w:900,h:700};let b=1/0,z=1/0,le=-1/0,O=-1/0;for(const v of R){const se=jt(v.degree);b=Math.min(b,v.x-se-80),z=Math.min(z,v.y-se-40),le=Math.max(le,v.x+se+80),O=Math.max(O,v.y+se+40)}return{x:b,y:z,w:le-b,h:O-z}},[R]),xe=n.useMemo(()=>new Map(R.map(b=>[b.id,b])),[R]),{connectedEdgeIds:pe,connectedNodeIds:M}=n.useMemo(()=>{const b=I||Y;if(!b)return{connectedEdgeIds:new Set,connectedNodeIds:new Set};const z=new Set,le=new Set([b]);for(const O of o)(O.fromId===b||O.toId===b)&&(z.add(O.id),le.add(O.fromId),le.add(O.toId));return{connectedEdgeIds:z,connectedNodeIds:le}},[I,Y,o]),Ce=n.useMemo(()=>{const b=new Map,z=new Map;for(const O of o){const v=[O.fromId,O.toId].sort().join("|"),se=b.get(v)||0;z.set(O.id,se),b.set(v,se+1)}const le=new Map;for(const O of o){const v=[O.fromId,O.toId].sort().join("|"),se=b.get(v)||1;if(se<=1){le.set(O.id,0);continue}const be=z.get(O.id)||0;le.set(O.id,(be-(se-1)/2)*40)}return le},[o]),[F,Se]=n.useState(new Set);n.useEffect(()=>{Se(new Set(o.map(b=>b.relation)))},[o]);const Te=n.useMemo(()=>o.filter(b=>F.has(b.relation)),[o,F]),_e=b=>{Se(z=>{const le=new Set(z);return le.has(b)?le.delete(b):le.add(b),le})},Me=n.useCallback(b=>{b.button===0&&(V.current=!0,B.current={x:b.clientX,y:b.clientY})},[]),te=n.useCallback(b=>{if(!V.current)return;const z=b.clientX-B.current.x,le=b.clientY-B.current.y;B.current={x:b.clientX,y:b.clientY},re(O=>({x:O.x+z,y:O.y+le}))},[]),de=n.useCallback(()=>{V.current=!1},[]),f=n.useCallback(b=>{b.preventDefault();const z=b.deltaY>0?-.1:.1;y(le=>Math.min(3,Math.max(.2,le+z)))},[]),J=b=>`kg-arrow-${b.replace(/[^a-z_]/g,"")}`;if(c)return e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"})});if(S)return e.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4",children:[e.jsx("p",{className:"text-red-500",children:S}),e.jsx("button",{onClick:oe,className:"px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors",children:t("knowledgeGraph.retry")})]});if(o.length===0)return e.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-[var(--fg-secondary)]",children:[e.jsx(Dr,{size:48,className:"text-[var(--fg-muted)]"}),e.jsx("p",{className:"text-lg font-medium",children:t("knowledgeGraph.empty")}),e.jsx("p",{className:"text-sm text-center max-w-xl",children:t("knowledgeGraph.emptyDesc")}),L&&e.jsx("p",{className:`text-sm ${U?"text-red-500":"text-green-600"}`,children:L}),e.jsx("button",{onClick:me,disabled:N,className:"px-4 py-2 rounded-lg flex items-center gap-2 text-sm font-medium transition-colors disabled:opacity-50 bg-[var(--accent-subtle)] text-[var(--accent)] border border-[var(--accent-emphasis)] hover:opacity-90",children:N?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-[var(--accent)]"})," ",t("knowledgeGraph.discovering")]}):e.jsxs(e.Fragment,{children:[e.jsx(Le,{size:H.sm})," ",t("knowledgeGraph.discoverRelations")]})})]});const ge=[...new Set(o.map(b=>b.relation))].sort(),k=!!(I||Y);return e.jsxs("div",{className:"h-full flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0 overflow-x-auto scrollbar-none",children:[u&&e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full whitespace-nowrap text-[var(--fg-secondary)] bg-[var(--bg-subtle)]",children:t("knowledgeGraph.statsLabel",{nodes:R.length,edges:u.totalEdges})}),ge.map(b=>e.jsxs("button",{onClick:()=>_e(b),className:`flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-medium transition-all border whitespace-nowrap ${F.has(b)?"border-transparent shadow-sm":"border-[var(--border-default)] bg-[var(--bg-surface)] text-[var(--fg-muted)] opacity-40"}`,style:F.has(b)?{backgroundColor:(dt[b]||"#6b7280")+"18",color:dt[b]||"#6b7280"}:{},children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:dt[b]||"#6b7280"}}),r(b),u?.byRelation?.[b]!=null&&e.jsxs("span",{className:"opacity-60",children:["(",u.byRelation[b],")"]})]},b))]}),e.jsxs("div",{className:"flex items-center gap-1 ml-2 flex-shrink-0",children:[e.jsx("button",{onClick:()=>y(b=>Math.min(b+.2,3)),className:"p-1 rounded-md transition-colors bg-[var(--bg-subtle)] hover:bg-[var(--border-default)] text-[var(--fg-secondary)]",title:t("knowledgeGraph.zoomIn"),children:e.jsx(Sr,{size:H.sm})}),e.jsx("button",{onClick:()=>y(b=>Math.max(b-.2,.2)),className:"p-1 rounded-md transition-colors bg-[var(--bg-subtle)] hover:bg-[var(--border-default)] text-[var(--fg-secondary)]",title:t("knowledgeGraph.zoomOut"),children:e.jsx(Ar,{size:H.sm})}),e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)] min-w-[3em] text-center tabular-nums",children:[Math.round(A*100),"%"]}),e.jsx("button",{onClick:()=>{y(1),re({x:0,y:0})},className:"p-1 rounded-md transition-colors bg-[var(--bg-subtle)] hover:bg-[var(--border-default)] text-[var(--fg-secondary)]",title:t("knowledgeGraph.resetView"),children:e.jsx(ea,{size:H.sm})}),e.jsx("button",{onClick:oe,className:"p-1 rounded-md transition-colors bg-[var(--bg-subtle)] hover:bg-[var(--border-default)] text-[var(--fg-secondary)]",title:t("knowledgeGraph.refresh"),children:e.jsx(at,{size:H.sm})}),e.jsx("button",{onClick:me,disabled:N,className:"flex items-center gap-1 px-2 py-1 rounded-md text-xs font-medium transition-colors disabled:opacity-50 bg-[var(--accent-subtle)] text-[var(--accent)] border border-[var(--accent-emphasis)] hover:opacity-90",title:t("knowledgeGraph.discoverTooltip"),children:N?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"animate-spin rounded-full h-3 w-3 border-b-2 border-[var(--accent)]"})," ",t("knowledgeGraph.discovering")]}):e.jsxs(e.Fragment,{children:[e.jsx(Le,{size:H.sm})," ",t("knowledgeGraph.discoverRelations")]})})]})]}),e.jsxs("div",{ref:ue,className:"flex-1 rounded-xl border overflow-hidden relative min-h-0 border-[var(--border-default)] bg-[var(--bg-subtle)]",style:{cursor:V.current?"grabbing":"grab"},onWheel:f,children:[e.jsxs("svg",{ref:he,width:"100%",height:"100%",viewBox:`${ie.x} ${ie.y} ${ie.w} ${ie.h}`,onMouseDown:Me,onMouseMove:te,onMouseUp:de,onMouseLeave:de,style:{transform:`scale(${A}) translate(${W.x/A}px, ${W.y/A}px)`},children:[e.jsxs("defs",{children:[ge.map(b=>e.jsx("marker",{id:J(b),viewBox:"0 0 10 8",refX:"10",refY:"4",markerWidth:"7",markerHeight:"5",orient:"auto-start-reverse",children:e.jsx("path",{d:"M0,0 L10,4 L0,8 Z",fill:dt[b]||"#6b7280"})},b)),e.jsxs("filter",{id:"kg-glow",x:"-50%",y:"-50%",width:"200%",height:"200%",children:[e.jsx("feGaussianBlur",{in:"SourceAlpha",stdDeviation:"4",result:"blur"}),e.jsx("feFlood",{floodColor:"#3b82f6",floodOpacity:"0.3",result:"color"}),e.jsx("feComposite",{in:"color",in2:"blur",operator:"in",result:"shadow"}),e.jsxs("feMerge",{children:[e.jsx("feMergeNode",{in:"shadow"}),e.jsx("feMergeNode",{in:"SourceGraphic"})]})]})]}),e.jsx("g",{children:T.map(b=>{const z=ee[b.group]||zs[0];return e.jsxs("g",{children:[e.jsx("ellipse",{cx:b.cx,cy:b.cy,rx:b.rx,ry:b.ry,fill:z.bg,stroke:z.border,strokeWidth:1.5,strokeDasharray:"6,4",opacity:.6}),e.jsxs("text",{x:b.cx,y:b.cy-b.ry+14,textAnchor:"middle",fontSize:11,fontWeight:600,fill:z.text,opacity:.8,style:{pointerEvents:"none",userSelect:"none"},children:[b.group||"general"," (",b.count,")"]})]},b.group)})}),e.jsx("g",{children:Te.map(b=>{const z=xe.get(b.fromId),le=xe.get(b.toId);if(!z||!le)return null;const O=k?pe.has(b.id):!1,v=G===b.id,se=k?O?.85:.06:v?.9:.35,be=jt(z.degree),fe=jt(le.degree),De=Ce.get(b.id)||0,ae=uc(z.x,z.y,le.x,le.y,be,fe,De);return e.jsxs("g",{children:[e.jsx("path",{d:ae,fill:"none",stroke:"transparent",strokeWidth:12,onMouseEnter:()=>_(b.id),onMouseLeave:()=>_(null),style:{cursor:"pointer"}}),e.jsx("path",{d:ae,fill:"none",stroke:dt[b.relation]||"#6b7280",strokeWidth:v||O?2:1.2,opacity:se,markerEnd:`url(#${J(b.relation)})`,strokeDasharray:b.relation==="related"?"6,3":void 0,style:{transition:"opacity 0.25s, stroke-width 0.15s",pointerEvents:"none"}}),v&&(()=>{const we=(z.x+le.x)/2,Oe=(z.y+le.y)/2;return e.jsxs("g",{children:[e.jsx("rect",{x:we-24,y:Oe-16,width:48,height:18,rx:4,fill:"var(--bg-surface)",stroke:dt[b.relation]||"#6b7280",strokeWidth:.8,opacity:.95}),e.jsx("text",{x:we,y:Oe-4,textAnchor:"middle",fontSize:9,fontWeight:600,fill:dt[b.relation]||"#6b7280",children:r(b.relation)})]})})()]},b.id)})}),e.jsx("g",{children:R.map(b=>{const z=jt(b.degree),le=I===b.id,O=k&&M.has(b.id),v=le||b.id===Y,se=k&&!O,be=se?.12:1,fe=ee[b.group]||zs[0],De=v?fe.border:fe.bg,ae=v?fe.text:fe.border,we=v?"#ffffff":fe.text,Oe=v?fe.text:"var(--fg-muted)";return e.jsxs("g",{onClick:rt=>{rt.stopPropagation(),P(le?null:b.id)},onMouseEnter:()=>w(b.id),onMouseLeave:()=>w(null),style:{cursor:"pointer",transition:"opacity 0.25s"},opacity:be,filter:v?"url(#kg-glow)":void 0,children:[e.jsx("circle",{cx:b.x,cy:b.y,r:z,fill:De,stroke:ae,strokeWidth:v?2.5:1.5}),e.jsx("text",{x:b.x,y:b.y+4,textAnchor:"middle",fontSize:Math.min(nc,z*.7),fill:we,fontWeight:700,style:{pointerEvents:"none",userSelect:"none"},children:_a(b.label,4).toUpperCase()}),e.jsx("text",{x:b.x,y:b.y+z+14,textAnchor:"middle",fontSize:lc,fill:Oe,fontWeight:v?600:400,style:{pointerEvents:"none",userSelect:"none"},children:_a(b.label,18)}),b.degree>=3&&!se&&e.jsxs("g",{children:[e.jsx("circle",{cx:b.x+z*.7,cy:b.y-z*.7,r:8,fill:"#3b82f6",stroke:"var(--bg-surface)",strokeWidth:1.5}),e.jsx("text",{x:b.x+z*.7,y:b.y-z*.7+3.5,textAnchor:"middle",fontSize:8,fill:"white",fontWeight:700,style:{pointerEvents:"none"},children:b.degree})]})]},b.id)})})]}),I&&e.jsx("button",{className:"absolute top-2 right-2 text-xs px-2 py-1 rounded-md shadow-sm border text-[var(--fg-muted)] hover:text-[var(--fg-secondary)] bg-[var(--bg-surface)] border-[var(--border-default)]",onClick:()=>P(null),children:t("knowledgeGraph.cancelSelection")}),L&&e.jsx("div",{className:`absolute bottom-3 left-1/2 -translate-x-1/2 max-w-md px-3 py-1.5 rounded-lg text-xs shadow-md border ${U?"bg-red-50 border-red-200 text-red-700 dark:bg-red-950/60 dark:border-red-800 dark:text-red-300":"bg-green-50 border-green-200 text-green-700 dark:bg-green-950/60 dark:border-green-800 dark:text-green-300"}`,children:L})]}),I&&e.jsxs("div",{className:"mt-3 p-4 rounded-xl border shadow-sm flex-shrink-0 max-h-48 overflow-y-auto scrollbar-light bg-[var(--bg-surface)] border-[var(--border-default)]",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3 pb-2 border-b border-[var(--border-default)]",children:[e.jsx(Hs,{size:14,className:"text-blue-500"}),e.jsx("h3",{className:"font-semibold text-sm text-[var(--fg-primary)]",children:i[I]||I}),e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)] ml-auto",children:["ID: ",I]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-xs",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-[var(--fg-secondary)] font-medium",children:t("knowledgeGraph.outEdges")}),e.jsxs("ul",{className:"mt-1.5 space-y-1",children:[o.filter(b=>b.fromId===I&&F.has(b.relation)).map(b=>e.jsxs("li",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:dt[b.relation]||"#6b7280"}}),e.jsx("span",{className:"text-[var(--fg-secondary)]",children:r(b.relation)}),e.jsx("span",{className:"text-[var(--fg-muted)]",children:"→"}),e.jsx("button",{className:"text-blue-600 hover:underline truncate",onClick:()=>P(b.toId),children:i[b.toId]||b.toId.substring(0,16)})]},b.id)),o.filter(b=>b.fromId===I&&F.has(b.relation)).length===0&&e.jsx("li",{className:"text-[var(--fg-muted)]",children:t("knowledgeGraph.none")})]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[var(--fg-secondary)] font-medium",children:t("knowledgeGraph.inEdges")}),e.jsxs("ul",{className:"mt-1.5 space-y-1",children:[o.filter(b=>b.toId===I&&F.has(b.relation)).map(b=>e.jsxs("li",{className:"flex items-center gap-1.5",children:[e.jsx("button",{className:"text-blue-600 hover:underline truncate",onClick:()=>P(b.fromId),children:i[b.fromId]||b.fromId.substring(0,16)}),e.jsx("span",{className:"text-[var(--fg-muted)]",children:"→"}),e.jsx("span",{className:"text-[var(--fg-secondary)]",children:r(b.relation)}),e.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:dt[b.relation]||"#6b7280"}})]},b.id)),o.filter(b=>b.toId===I&&F.has(b.relation)).length===0&&e.jsx("li",{className:"text-[var(--fg-muted)]",children:t("knowledgeGraph.none")})]})]})]})]})]})},pc=[{key:"overview",icon:Ge,labelKey:"panorama.overview"},{key:"dependencies",icon:Wt,labelKey:"sidebar.depGraph"},{key:"graph",icon:Dr,labelKey:"sidebar.knowledgeGraph"},{key:"gaps",icon:st,labelKey:"panorama.gaps"}],xc=()=>{const{t}=Ae(),[s,a]=n.useState("overview"),[r,o]=n.useState(null),[l,i]=n.useState(null),[p,d]=n.useState([]),[g,x]=n.useState(!0),[h,u]=n.useState(null),m=n.useCallback(async(j=!1)=>{x(!0),u(null);const S=await Promise.allSettled([Z.getPanoramaOverview(j),Z.getPanoramaHealth(j),Z.getPanoramaGaps(j)]),[D,I,P]=S;if(D.status==="fulfilled"&&o(D.value),I.status==="fulfilled"&&i(I.value),P.status==="fulfilled"&&d(P.value??[]),S.every(w=>w.status==="rejected")){const w=S[0].reason;u(ke(w,"Failed to load panorama data"))}x(!1)},[]);n.useEffect(()=>{m()},[m]);const c=s==="dependencies"||s==="graph";return!c&&g?e.jsxs("div",{className:"flex items-center justify-center h-64 text-[var(--text-secondary)]",children:[e.jsx(at,{className:"w-5 h-5 animate-spin mr-2"}),t("panorama.loading")]}):!c&&h&&!r&&!l?e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fa,{t,stale:!1,onRefresh:()=>m(!0)}),e.jsx(za,{tab:s,setTab:a,t}),e.jsxs("div",{className:"flex items-center justify-center h-48 text-red-500",children:[e.jsx(st,{className:"w-5 h-5 mr-2"}),h]})]}):e.jsxs("div",{className:"space-y-5 h-full flex flex-col",children:[e.jsx(Fa,{t,stale:r?.stale,onRefresh:()=>m(!0)}),e.jsx(za,{tab:s,setTab:a,t}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto",children:[s==="overview"&&e.jsx(gc,{overview:r,health:l,gaps:p,t}),s==="dependencies"&&e.jsx(tc,{}),s==="graph"&&e.jsx(mc,{}),s==="gaps"&&e.jsx(jc,{gaps:p,t})]})]})},Fa=({t,stale:s,onRefresh:a})=>e.jsxs("div",{className:"flex items-center justify-between shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ge,{className:"w-5 h-5 text-[var(--accent)]"}),e.jsx("h2",{className:"text-lg font-semibold text-[var(--text-primary)]",children:t("panorama.title")}),s&&e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400",children:t("panorama.stale")})]}),e.jsx("button",{onClick:a,className:"p-2 rounded-lg hover:bg-[var(--bg-elevated)] text-[var(--text-secondary)] transition-colors",children:e.jsx(at,{className:"w-4 h-4"})})]}),za=({tab:t,setTab:s,t:a})=>e.jsx("div",{className:"flex items-center gap-1.5 shrink-0",children:pc.map(({key:r,icon:o,labelKey:l})=>e.jsxs("button",{onClick:()=>s(r),className:`flex items-center gap-1.5 px-4 py-1.5 rounded-md text-xs font-medium transition-colors ${t===r?"bg-[var(--accent-subtle)] text-[var(--accent)] border border-[var(--accent-emphasis)]":"text-[var(--fg-muted)] hover:bg-[var(--bg-subtle)] border border-transparent"}`,children:[e.jsx(o,{className:"w-3.5 h-3.5"}),a(l)]},r))}),gc=({overview:t,health:s,gaps:a,t:r})=>!t&&!s?e.jsx("div",{className:"flex items-center justify-center h-32 text-[var(--text-secondary)]",children:r("panorama.noData")||"No panorama data available"}):e.jsxs("div",{className:"space-y-6",children:[e.jsx(hc,{overview:t,health:s,t:r}),t&&t.layers.length>0&&e.jsx(fc,{layers:t.layers,t:r}),s&&e.jsx(vc,{health:s,t:r}),a.length>0&&e.jsx(yc,{gaps:a,t:r})]}),hc=({overview:t,health:s,t:a})=>{const r=n.useMemo(()=>{const o=[];if(t&&o.push({label:a("panorama.modules"),value:t.moduleCount,icon:gl,color:"text-blue-500"},{label:a("panorama.layers"),value:t.layerCount,icon:Ge,color:"text-violet-500"},{label:a("panorama.files"),value:t.totalFiles,icon:hl,color:"text-cyan-500"},{label:a("panorama.recipes"),value:t.totalRecipes,icon:js,color:"text-emerald-500"}),s){const l=s.healthRadar?.dimensionCoverage??0,i=`${Math.round(l*100)}%`;o.push({label:a("panorama.coverage"),value:i,icon:Tt,color:wc(l/100)},{label:a("panorama.cycles"),value:t?.cycleCount??s.cycleCount,icon:Wt,color:(t?.cycleCount??s.cycleCount)>0?"text-red-500":"text-green-500"})}else if(t){const l=t.totalFiles>0?`${Math.round(t.totalRecipes/t.totalFiles*100)}%`:"0%";o.push({label:a("panorama.coverage"),value:l,icon:Tt,color:"text-gray-500"},{label:a("panorama.cycles"),value:t.cycleCount,icon:Wt,color:t.cycleCount>0?"text-red-500":"text-green-500"})}return o},[t,s,a]);return e.jsx("div",{className:"grid grid-cols-3 md:grid-cols-6 gap-3",children:r.map(o=>e.jsxs("div",{className:"p-3 rounded-xl glass-surface border border-[var(--border-muted)] hover:border-[var(--border-hover)] transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[e.jsx(o.icon,{className:`w-3.5 h-3.5 ${o.color}`}),e.jsx("span",{className:"text-[11px] text-[var(--text-tertiary)] truncate",children:o.label})]}),e.jsx("span",{className:"text-xl font-bold text-[var(--text-primary)]",children:o.value})]},o.label))})},Ba=["from-violet-600 to-violet-500","from-indigo-600 to-indigo-500","from-blue-600 to-blue-500","from-cyan-600 to-cyan-500","from-teal-600 to-teal-500","from-emerald-600 to-emerald-500","from-sky-600 to-sky-500","from-fuchsia-600 to-fuchsia-500"],bc=["border-violet-500","border-indigo-500","border-blue-500","border-cyan-500","border-teal-500","border-emerald-500","border-sky-500","border-fuchsia-500"],Ga={app:{label:"App",color:"bg-rose-500/20 text-rose-700 dark:text-rose-300"},core:{label:"Core",color:"bg-violet-500/20 text-violet-700 dark:text-violet-300"},foundation:{label:"Foundation",color:"bg-indigo-500/20 text-indigo-700 dark:text-indigo-300"},service:{label:"Service",color:"bg-blue-500/20 text-blue-700 dark:text-blue-300"},networking:{label:"Network",color:"bg-cyan-500/20 text-cyan-700 dark:text-cyan-300"},storage:{label:"Storage",color:"bg-teal-500/20 text-teal-700 dark:text-teal-300"},model:{label:"Model",color:"bg-emerald-500/20 text-emerald-700 dark:text-emerald-300"},ui:{label:"UI",color:"bg-orange-500/20 text-orange-700 dark:text-orange-300"},routing:{label:"Routing",color:"bg-amber-500/20 text-amber-700 dark:text-amber-300"},utility:{label:"Utility",color:"bg-slate-500/20 text-slate-700 dark:text-slate-300"},auth:{label:"Auth",color:"bg-red-500/20 text-red-700 dark:text-red-300"},feature:{label:"Feature",color:"bg-gray-500/20 text-gray-700 dark:text-gray-300"},config:{label:"Config",color:"bg-yellow-500/20 text-yellow-700 dark:text-yellow-300"},test:{label:"Test",color:"bg-pink-500/20 text-pink-700 dark:text-pink-300"}},fc=({layers:t,t:s})=>{const[a,r]=n.useState(null),o=n.useMemo(()=>[...t].sort((l,i)=>i.level-l.level),[t]);return e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-[var(--text-secondary)] mb-3 flex items-center gap-2",children:[e.jsx(Ge,{className:"w-4 h-4"}),s("panorama.layers")]}),e.jsx("div",{className:"flex flex-col gap-2",children:o.map((l,i)=>{const p=i%Ba.length,d=Ba[p],g=bc[p],x=a===l.level,h=l.modules.length,u=l.modules.reduce((c,j)=>c+j.fileCount,0),m=l.modules.reduce((c,j)=>c+j.recipeCount,0);return e.jsxs("div",{className:"w-full",children:[e.jsxs("button",{type:"button",onClick:()=>r(x?null:l.level),className:`w-full rounded-lg border-l-4 ${g} bg-[var(--bg-elevated)] hover:bg-[var(--bg-hover)] px-4 py-2.5 flex items-center justify-between transition-all cursor-pointer`,children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[x?e.jsx(gt,{className:"w-3.5 h-3.5 text-[var(--text-tertiary)]"}):e.jsx(Ke,{className:"w-3.5 h-3.5 text-[var(--text-tertiary)]"}),e.jsxs("span",{className:`text-xs font-bold px-1.5 py-0.5 rounded bg-gradient-to-r ${d} text-white`,children:["L",l.level]}),e.jsx("span",{className:"font-semibold text-sm text-[var(--text-primary)]",children:l.name})]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-[var(--text-secondary)] shrink-0 ml-3",children:[e.jsxs("span",{children:[h," ",s("panorama.modules").toLowerCase()]}),u>0&&e.jsxs("span",{children:[u," ",s("panorama.files").toLowerCase()]}),m>0&&e.jsxs("span",{className:"bg-emerald-500/15 text-emerald-400 rounded-full px-2 py-0.5 font-medium",children:[m," recipes"]})]})]}),x&&l.modules.length>0&&e.jsx("div",{className:"mt-1.5 ml-5 grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-1.5",children:l.modules.map(c=>{const j=Ga[c.role]??Ga.feature,S=c.fileCount>0?Math.round(c.recipeCount/c.fileCount*100):0;return e.jsxs("div",{className:"p-2 rounded-lg glass-surface border border-[var(--border-muted)] hover:border-[var(--border-hover)] transition-colors",children:[e.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)] truncate",title:c.name,children:c.name}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[e.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded ${j.color}`,children:j.label}),c.fileCount>0&&e.jsxs("span",{className:"text-[10px] text-[var(--text-tertiary)]",children:[c.fileCount,"f"]}),S>0&&e.jsxs("span",{className:`text-[10px] font-medium ${Nc(S)}`,children:[S,"%"]})]})]},c.name)})})]},l.level)})})]})},vc=({health:t,t:s})=>{const a=t.healthScore,r=a>=80?"bg-green-500":a>=50?"bg-yellow-500":"bg-red-500",o=a>=80?"text-green-500":a>=50?"text-yellow-500":"text-red-500";return e.jsxs("div",{className:"p-4 rounded-xl glass-surface border border-[var(--border-muted)]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ve,{className:"w-4 h-4 text-[var(--text-tertiary)]"}),e.jsx("span",{className:"text-sm font-semibold text-[var(--text-secondary)]",children:s("panorama.healthScore")})]}),e.jsxs("span",{className:`text-2xl font-bold ${o}`,children:[a,e.jsx("span",{className:"text-sm text-[var(--text-tertiary)] font-normal",children:"/100"})]})]}),e.jsx("div",{className:"w-full h-2 rounded-full bg-[var(--bg-elevated)] overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full ${r} transition-all`,style:{width:`${a}%`}})}),e.jsxs("div",{className:"flex gap-4 mt-2 text-xs text-[var(--text-tertiary)]",children:[e.jsxs("span",{children:[s("panorama.avgCoupling"),": ",t.avgCoupling.toFixed(1)]}),e.jsxs("span",{children:[s("panorama.cycles"),": ",t.cycleCount]}),e.jsxs("span",{children:[s("panorama.gaps"),": ",t.gapCount]}),t.highPriorityGaps>0&&e.jsxs("span",{className:"text-red-500",children:[s("panorama.highPriorityGaps"),": ",t.highPriorityGaps]})]})]})},yc=({gaps:t,t:s})=>{const r=[...t].sort((o,l)=>(Pt[o.priority]?.order??2)-(Pt[l.priority]?.order??2)).slice(0,5);return e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-[var(--text-secondary)] mb-2 flex items-center gap-2",children:[e.jsx(st,{className:"w-4 h-4 text-yellow-500"}),s("panorama.gaps"),e.jsxs("span",{className:"text-xs font-normal text-[var(--text-tertiary)]",children:["(",t.length,")"]})]}),e.jsx("div",{className:"space-y-1",children:r.map((o,l)=>e.jsx(en,{gap:o},`${o.dimension}-${l}`))})]})},Pt={high:{color:"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400",order:0},medium:{color:"bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400",order:1},low:{color:"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400",order:2}},jc=({gaps:t,t:s})=>{if(t.length===0)return e.jsx("div",{className:"flex items-center justify-center h-32 text-[var(--text-secondary)]",children:s("panorama.noGaps")});const a=n.useMemo(()=>[...t].sort((r,o)=>(Pt[r.priority]?.order??2)-(Pt[o.priority]?.order??2)),[t]);return e.jsx("div",{className:"space-y-1.5",children:a.map((r,o)=>e.jsx(en,{gap:r,detailed:!0},`${r.dimension}-${o}`))})},en=({gap:t,detailed:s})=>{const a=Pt[t.priority]??Pt.low;return e.jsxs("div",{className:"flex items-center justify-between p-2.5 rounded-lg glass-surface border border-[var(--border-muted)] hover:border-[var(--border-hover)] transition-colors",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-[var(--text-primary)] truncate",children:t.dimensionName}),e.jsxs("span",{className:"text-[11px] text-[var(--text-tertiary)] shrink-0",children:[t.recipeCount,"r · ",t.status]})]}),s&&t.suggestedTopics&&t.suggestedTopics.length>0&&e.jsx("div",{className:"flex gap-1 mt-1 flex-wrap",children:t.suggestedTopics.map(r=>e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-[var(--bg-elevated)] text-[var(--text-tertiary)]",children:r},r))}),s&&t.affectedRoles&&t.affectedRoles.length>0&&e.jsxs("p",{className:"text-xs text-[var(--text-secondary)] mt-0.5",children:["Affected: ",t.affectedRoles.join(", ")]})]}),e.jsx("span",{className:`text-[11px] px-2 py-0.5 rounded-full shrink-0 ml-2 ${a.color}`,children:t.priority})]})};function wc(t){const s=t*100;return s>=80?"text-green-500":s>=50?"text-yellow-500":"text-red-500"}function Nc(t){return t>=80?"text-green-500":t>=50?"text-yellow-500":t>0?"text-red-500":"text-[var(--text-tertiary)]"}const $a=()=>Math.random().toString(36).substring(2,10),kc=({d:t})=>{const{t:s}=Ae();return e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-2.5 py-1 bg-[var(--bg-subtle)] border-b border-[var(--border-default)] flex items-center gap-1.5",children:[e.jsx(jr,{size:10,className:"text-emerald-500"}),e.jsx("span",{className:"text-[10px] font-bold text-[var(--fg-secondary)]",children:t.label})]}),e.jsxs("div",{className:"p-2.5 bg-red-50/30 border-b border-[var(--border-default)]",children:[e.jsx("div",{className:"text-[9px] font-bold text-red-400 mb-0.5 uppercase",children:s("aiChat.diffBefore")}),e.jsx("pre",{className:"text-[11px] text-[var(--fg-secondary)] whitespace-pre-wrap break-words max-h-48 overflow-auto font-mono leading-relaxed scrollbar-light",children:t.before||e.jsx("span",{className:"italic text-[var(--fg-muted)]",children:s("aiChat.diffEmpty")})})]}),e.jsxs("div",{className:"p-2.5 bg-emerald-50/30",children:[e.jsx("div",{className:"text-[9px] font-bold text-emerald-500 mb-0.5 uppercase",children:s("aiChat.diffAfter")}),e.jsx("pre",{className:"text-[11px] text-[var(--fg-primary)] whitespace-pre-wrap break-words max-h-48 overflow-auto font-mono leading-relaxed scrollbar-light",children:t.after})]})]})};function Cc(t,s){const a=new Date(t),o=new Date().getTime()-a.getTime(),l=Math.floor(o/6e4);if(l<1)return s("aiChat.timeJustNow");if(l<60)return s("aiChat.timeMinutesAgo",{n:l});const i=Math.floor(l/60);if(i<24)return s("aiChat.timeHoursAgo",{n:i});const p=Math.floor(i/24);return p<7?s("aiChat.timeDaysAgo",{n:p}):a.toLocaleDateString("zh-CN",{month:"short",day:"numeric"})}const Sc=()=>{const{t,lang:s}=Ae(),{close:a,isOpen:r}=Zt(),[o,l]=n.useState([]),[i,p]=n.useState(!1),d=n.useRef([]),g=n.useRef(null),x=zr(),{topics:h,activeTopicId:u,activeTopic:m,createTopic:c,deleteTopic:j,saveTopic:S,switchTopic:D}=x,I=n.useRef(null),P=n.useRef(null),[Y,w]=n.useState(""),[G,_]=n.useState(!1),N=n.useRef(!1);n.useEffect(()=>{r&&a()},[]),n.useEffect(()=>{I.current?.scrollIntoView({behavior:"smooth"})},[o,i]),n.useEffect(()=>{setTimeout(()=>P.current?.focus(),200)},[]),n.useEffect(()=>{N.current||u&&o.length>0&&S(u,o)},[o,u,S]);const E=n.useCallback(()=>{N.current=!0,c(),l([]),d.current=[],setTimeout(()=>{N.current=!1},50)},[c,l,d]),L=n.useCallback(A=>{if(A===u)return;N.current=!0,D(A);const y=x.getTopic(A);y?(l(y.messages),d.current=y.messages.filter(W=>W.role==="user"||W.role==="assistant").map(W=>({role:W.role==="assistant"?"model":W.role,content:W.content}))):(l([]),d.current=[]),setTimeout(()=>{N.current=!1},50)},[u,D,x,l,d]),$=n.useCallback((A,y)=>{A.stopPropagation(),j(y),y===u&&(N.current=!0,l([]),d.current=[],setTimeout(()=>{N.current=!1},50))},[j,u,l,d]),U=n.useCallback(async()=>{const A=Y.trim();if(!A||i)return;let y=u;y||(N.current=!0,y=c(),setTimeout(()=>{N.current=!1},50)),w(""),l(he=>[...he,{id:$a(),role:"user",content:A,timestamp:Date.now()}]),p(!0);const W=$a();l(he=>[...he,{id:W,role:"assistant",content:`🔄 ${t("aiChat.thinking")}`,timestamp:Date.now()}]),d.current.push({role:"user",content:A});const re=new AbortController;g.current=re;try{const{onEvent:he,getState:ue}=Br(W,l,t),B=(await Z.chatStream(A,d.current,R=>{he(R)},re.signal,s)).text||ue().answerText,oe=ue().toolLogs.length>0?ue().toolLogs.join(`
`)+`

---

`+t("aiChat.noReplyFallback",{defaultValue:"> AI 未能生成文字回复,以上是执行过程记录。"}):"",me=B||oe||t("aiChat.requestFailed",{error:"Empty response"});d.current.push({role:"model",content:me}),l(R=>R.map(T=>T.id===W?{...T,content:me}:T))}catch(he){if(fs(he)){const ue=t("aiChat.cancelled");l(V=>V.map(B=>B.id===W?{...B,content:ue}:B))}else l(ue=>ue.map(V=>V.id===W?{...V,content:t("aiChat.requestFailed",{error:ke(he)})}:V))}finally{g.current=null}p(!1)},[Y,i,u,c,t,s]),q=n.useCallback(A=>{A.key==="Enter"&&!A.shiftKey&&(A.preventDefault(),U())},[U]);return e.jsxs("div",{className:"flex-1 flex h-full bg-[var(--bg-subtle)]",children:[e.jsx("div",{className:`${G?"w-10":"w-64"} shrink-0 bg-[var(--bg-surface)] border-r border-[var(--border-default)] flex flex-col transition-all duration-200`,children:G?e.jsxs("div",{className:"flex flex-col items-center py-3 gap-2",children:[e.jsx("button",{onClick:()=>_(!1),className:"p-1.5 hover:bg-[var(--bg-subtle)] rounded-lg transition-colors text-[var(--fg-muted)] hover:text-[var(--fg-secondary)]",title:t("aiChat.expandTopics"),children:e.jsx(Ke,{size:16})}),e.jsx("button",{onClick:E,className:"p-1.5 hover:bg-[var(--accent-subtle)] rounded-lg transition-colors text-blue-500",title:t("aiChat.newTopic"),children:e.jsx(mt,{size:16})})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"px-3 py-2.5 border-b border-[var(--border-default)] flex items-center justify-between shrink-0",children:[e.jsx("span",{className:"text-xs font-bold text-[var(--fg-secondary)] uppercase tracking-wider",children:t("aiChat.topicRecords")}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx("button",{onClick:E,className:"p-1.5 hover:bg-[var(--accent-subtle)] rounded-lg transition-colors text-[var(--fg-muted)] hover:text-blue-600",title:t("aiChat.newTopic"),children:e.jsx(mt,{size:14})}),e.jsx("button",{onClick:()=>_(!0),className:"p-1.5 hover:bg-[var(--bg-subtle)] rounded-lg transition-colors text-[var(--fg-muted)] hover:text-[var(--fg-secondary)]",title:t("common.collapse"),children:e.jsx(Xs,{size:14})})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto scrollbar-light",children:h.length===0?e.jsxs("div",{className:"px-4 py-8 text-center",children:[e.jsx(ut,{size:24,className:"text-[var(--fg-muted)] mx-auto mb-2"}),e.jsx("p",{className:"text-xs text-[var(--fg-muted)]",children:t("aiChat.noHistory")}),e.jsx("p",{className:"text-[10px] text-[var(--fg-muted)] mt-1",children:t("aiChat.autoSaveHint")})]}):e.jsx("div",{className:"py-1",children:h.map(A=>{const y=A.id===u,W=A.messages.filter(re=>re.role==="user").length;return e.jsx("div",{onClick:()=>L(A.id),className:`group mx-1.5 mb-0.5 px-3 py-2 rounded-lg cursor-pointer transition-colors ${y?"bg-[var(--accent-subtle)] border border-blue-200":"hover:bg-[var(--bg-subtle)] border border-transparent"}`,children:e.jsxs("div",{className:"flex items-start justify-between gap-1.5",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`text-xs font-medium truncate leading-snug ${y?"text-blue-700":"text-[var(--fg-primary)]"}`,children:A.title}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)] flex items-center gap-0.5",children:[e.jsx(Ye,{size:9}),Cc(A.updatedAt,t)]}),W>0&&e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)]",children:t("aiChat.messageCount",{n:W})})]})]}),e.jsx("button",{onClick:re=>$(re,A.id),className:`p-1 rounded transition-colors shrink-0 ${y?"text-blue-400 hover:text-red-500 hover:bg-red-50":"text-transparent group-hover:text-[var(--fg-muted)] hover:!text-red-500 hover:!bg-red-50"}`,title:t("aiChat.deleteTopic"),children:e.jsx(qe,{size:12})})]})},A.id)})})}),h.length>0&&e.jsx("div",{className:"px-3 py-2 border-t border-[var(--border-default)] shrink-0",children:e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)]",children:t("aiChat.topicCount",{count:h.length})})})]})}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsxs("div",{className:"px-6 py-3 border-b border-[var(--border-default)] bg-[var(--bg-surface)] flex items-center justify-between shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-xl bg-gradient-to-br from-blue-50 to-indigo-50 border border-blue-100 flex items-center justify-center",children:e.jsx(ut,{className:"text-blue-600",size:18})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm font-bold text-[var(--fg-primary)]",children:m?m.title:"AI Chat"}),e.jsx("p",{className:"text-[11px] text-[var(--fg-muted)]",children:t("aiChat.askAnything")})]})]}),o.length>0&&e.jsxs("button",{onClick:E,className:"flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-[var(--fg-secondary)] hover:text-blue-600 hover:bg-[var(--accent-subtle)] rounded-lg transition-colors border border-[var(--border-default)] hover:border-blue-200",children:[e.jsx(mt,{size:14}),t("aiChat.newTopic")]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto min-h-0 scrollbar-light",children:e.jsxs("div",{className:"max-w-3xl mx-auto p-6 space-y-4",children:[o.length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-50 border border-blue-100 flex items-center justify-center mb-4",children:e.jsx(ut,{className:"text-blue-500",size:28})}),e.jsx("h3",{className:"text-base font-bold text-[var(--fg-primary)] mb-2",children:t("aiChat.startChat")}),e.jsx("p",{className:"text-sm text-[var(--fg-muted)] max-w-md leading-relaxed mb-5",children:t("aiChat.emptyDescLong")}),e.jsx("div",{className:"flex flex-wrap gap-2 justify-center",children:[{key:"analyzeArch",label:t("aiChat.quickPrompts.analyzeArch")},{key:"findDuplicates",label:t("aiChat.quickPrompts.findDuplicates")},{key:"suggestOptimize",label:t("aiChat.quickPrompts.suggestOptimize")},{key:"summarize",label:t("aiChat.quickPromptSummarize")}].map(A=>e.jsx("button",{onClick:()=>{w(A.label),P.current?.focus()},className:"text-xs px-3.5 py-2 rounded-lg bg-[var(--bg-surface)] border border-[var(--border-default)] text-[var(--fg-secondary)] hover:bg-[var(--accent-subtle)] hover:text-blue-700 hover:border-blue-200 transition-colors shadow-sm",children:A.label},A.key))})]}),o.map(A=>e.jsx("div",{className:`flex ${A.role==="user"?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[80%] ${A.role==="user"?"bg-[var(--accent-subtle)] text-[var(--fg-primary)] rounded-2xl rounded-tr-md px-4 py-2.5":A.role==="system"?"bg-[var(--bg-subtle)] border border-[var(--border-default)] text-[var(--fg-secondary)] rounded-2xl px-4 py-2.5 w-full":"bg-[var(--bg-surface)] border border-[var(--border-default)] rounded-2xl rounded-tl-md px-4 py-3 shadow-sm w-full"}`,children:[A.role==="assistant"&&e.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[e.jsx(Mt,{size:13,className:"text-blue-500"}),e.jsx("span",{className:"text-[11px] font-bold text-blue-600",children:t("aiChat.aiAssistant")})]}),A.role==="assistant"&&!A.diff?e.jsx(Qt,{content:A.content,className:"text-sm text-[var(--fg-primary)]"}):e.jsx("p",{className:`text-sm leading-relaxed whitespace-pre-wrap ${A.role==="user"?"":"text-[var(--fg-secondary)]"}`,children:A.content}),A.diff&&A.diff.length>0&&e.jsx("div",{className:"space-y-2 mt-2",children:A.diff.map(y=>e.jsx(kc,{d:y},y.field))})]})},A.id)),i&&e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"bg-[var(--bg-surface)] border border-[var(--border-default)] rounded-2xl rounded-tl-md px-4 py-3 shadow-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{size:14,className:"animate-spin text-blue-500"}),e.jsx("span",{className:"text-sm text-[var(--fg-secondary)]",children:t("aiChat.thinking")}),g.current&&e.jsx("button",{onClick:()=>g.current?.abort(),className:"ml-1 px-1.5 py-0.5 text-[10px] font-bold text-red-500 border border-red-200 rounded hover:bg-red-50 transition-colors",children:t("common.stop")})]})})}),e.jsx("div",{ref:I})]})}),e.jsx("div",{className:"border-t border-[var(--border-default)] bg-[var(--bg-surface)] shrink-0",children:e.jsxs("div",{className:"max-w-3xl mx-auto px-6 py-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx("textarea",{ref:P,value:Y,onChange:A=>w(A.target.value),onKeyDown:q,placeholder:t("aiChat.inputPlaceholder"),rows:2,className:"flex-1 px-4 py-2.5 text-sm border border-[var(--border-default)] rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-200 focus:border-blue-400 resize-none placeholder:text-[var(--fg-muted)]",disabled:i}),e.jsx("button",{onClick:U,disabled:!Y.trim()||i,className:"self-stretch w-10 flex items-center justify-center rounded-xl bg-gradient-to-r from-blue-500 to-indigo-600 hover:from-blue-600 hover:to-indigo-700 text-white disabled:opacity-40 disabled:cursor-not-allowed transition-all shadow-sm shrink-0",children:e.jsx(Zs,{size:16})})]}),e.jsx("p",{className:"text-[10px] text-[var(--fg-muted)] mt-1.5",children:t("aiChat.inputHint")})]})})]})]})};function Ac(){return e.jsxs("div",{className:"space-y-0",children:[e.jsxs("div",{className:"flex items-center gap-4 px-4 py-3 border-b border-[var(--border-default)]",children:[e.jsx(Xe,{className:"h-4 w-4 rounded-sm"}),e.jsx(Xe,{className:"h-3.5 w-[30%]"}),e.jsx(Xe,{className:"h-3.5 w-[12%]"}),e.jsx(Xe,{className:"h-3.5 w-[12%]"}),e.jsx(Xe,{className:"h-3.5 w-[15%]"}),e.jsx(Xe,{className:"h-3.5 w-6"})]}),Array.from({length:8}).map((t,s)=>e.jsxs("div",{className:"flex items-center gap-4 px-4 py-3 border-b border-[var(--border-default)]",children:[e.jsx(Xe,{className:"h-4 w-4 rounded-sm"}),e.jsx(Xe,{className:"h-3.5 w-[28%]",style:{width:`${24+s%3*8}%`}}),e.jsx(Xe,{className:"h-5 w-14 rounded-full"}),e.jsx(Xe,{className:"h-5 w-16 rounded-full"}),e.jsx(Xe,{className:"h-3.5 w-[12%]"}),e.jsx(Xe,{className:"h-5 w-5 rounded"})]},s))]})}const lt={pending:{labelKey:"lifecycle.pending",color:"text-gray-600 dark:text-gray-400",bg:"bg-gray-500/8 dark:bg-gray-500/15",border:"border-gray-300 dark:border-gray-600",hoverBorder:"hover:border-gray-400 dark:hover:border-gray-500",badgeBg:"bg-gray-500/15 dark:bg-gray-500/25",badgeColor:"text-gray-600 dark:text-gray-300",icon:Ye},staging:{labelKey:"lifecycle.staging",color:"text-blue-600 dark:text-blue-400",bg:"bg-blue-500/8 dark:bg-blue-500/15",border:"border-blue-300 dark:border-blue-600",hoverBorder:"hover:border-blue-400 dark:hover:border-blue-500",badgeBg:"bg-blue-500/15 dark:bg-blue-500/25",badgeColor:"text-blue-600 dark:text-blue-300",icon:Rr},active:{labelKey:"lifecycle.active",color:"text-green-600 dark:text-green-400",bg:"bg-green-500/8 dark:bg-green-500/15",border:"border-green-300 dark:border-green-600",hoverBorder:"hover:border-green-400 dark:hover:border-green-500",badgeBg:"bg-green-500/15 dark:bg-green-500/25",badgeColor:"text-green-600 dark:text-green-300",icon:bt},evolving:{labelKey:"lifecycle.evolving",color:"text-purple-600 dark:text-purple-400",bg:"bg-purple-500/8 dark:bg-purple-500/15",border:"border-purple-300 dark:border-purple-600",hoverBorder:"hover:border-purple-400 dark:hover:border-purple-500",badgeBg:"bg-purple-500/15 dark:bg-purple-500/25",badgeColor:"text-purple-600 dark:text-purple-300",icon:Le},decaying:{labelKey:"lifecycle.decaying",color:"text-orange-600 dark:text-orange-400",bg:"bg-orange-500/8 dark:bg-orange-500/15",border:"border-orange-300 dark:border-orange-600",hoverBorder:"hover:border-orange-400 dark:hover:border-orange-500",badgeBg:"bg-orange-500/15 dark:bg-orange-500/25",badgeColor:"text-orange-600 dark:text-orange-300",icon:qs},deprecated:{labelKey:"lifecycle.deprecated",color:"text-red-600 dark:text-red-400",bg:"bg-red-500/8 dark:bg-red-500/15",border:"border-red-300 dark:border-red-600",hoverBorder:"hover:border-red-400 dark:hover:border-red-500",badgeBg:"bg-red-500/15 dark:bg-red-500/25",badgeColor:"text-red-600 dark:text-red-300",icon:qt}},$t={rule:{labelKey:"kind.rule",color:"text-red-700",bg:"bg-red-50",border:"border-red-200",icon:Ve},pattern:{labelKey:"kind.pattern",color:"text-violet-700",bg:"bg-violet-50",border:"border-violet-200",icon:St},fact:{labelKey:"kind.fact",color:"text-cyan-700",bg:"bg-cyan-50",border:"border-cyan-200",icon:Ue}},Dc={pending:[{action:"publish",labelKey:"knowledge.actionPublish",color:"text-green-700",bg:"bg-green-50 hover:bg-green-100",icon:bt},{action:"stage",labelKey:"knowledge.actionStage",color:"text-blue-700",bg:"bg-blue-50 hover:bg-blue-100",icon:Rr},{action:"deprecate",labelKey:"knowledge.actionDeprecate",color:"text-red-700",bg:"bg-red-50 hover:bg-red-100",icon:qt,needsReason:!0}],staging:[{action:"publish",labelKey:"knowledge.actionPublish",color:"text-green-700",bg:"bg-green-50 hover:bg-green-100",icon:bt},{action:"reactivate",labelKey:"knowledge.actionUnstage",color:"text-gray-700",bg:"bg-gray-50 hover:bg-gray-100",icon:$s}],active:[{action:"evolve",labelKey:"knowledge.actionEvolve",color:"text-purple-700",bg:"bg-purple-50 hover:bg-purple-100",icon:Le},{action:"decay",labelKey:"knowledge.actionDecay",color:"text-orange-700",bg:"bg-orange-50 hover:bg-orange-100",icon:qs,needsReason:!0},{action:"deprecate",labelKey:"knowledge.actionDeprecate",color:"text-red-700",bg:"bg-red-50 hover:bg-red-100",icon:qt,needsReason:!0}],evolving:[{action:"restore",labelKey:"knowledge.actionRestore",color:"text-green-700",bg:"bg-green-50 hover:bg-green-100",icon:bt},{action:"decay",labelKey:"knowledge.actionDecay",color:"text-orange-700",bg:"bg-orange-50 hover:bg-orange-100",icon:qs,needsReason:!0}],decaying:[{action:"restore",labelKey:"knowledge.actionRestore",color:"text-green-700",bg:"bg-green-50 hover:bg-green-100",icon:bt},{action:"deprecate",labelKey:"knowledge.actionDeprecate",color:"text-red-700",bg:"bg-red-50 hover:bg-red-100",icon:qt,needsReason:!0}],deprecated:[{action:"reactivate",labelKey:"knowledge.actionReactivate",color:"text-green-700",bg:"bg-green-50 hover:bg-green-100",icon:$s}]};function Ot(t,s){if(!t)return"";const a=t<1e12?t*1e3:t,r=new Date(a);if(isNaN(r.getTime())||r.getFullYear()<2e3)return"";const l=Date.now()-a;if(l<0)return r.toLocaleDateString();const i=Math.floor(l/6e4);if(i<1)return s("candidates.timeJustNow");if(i<60)return s("candidates.timeMinutesAgo",{n:i});const p=Math.floor(i/60);if(p<24)return s("candidates.timeHoursAgo",{n:p});const d=Math.floor(p/24);return d<7?s("candidates.timeDaysAgo",{n:d}):r.toLocaleDateString()}function Rc(t){return t==null?{ring:"stroke-[var(--border-default)]",text:"text-[var(--fg-muted)]",bg:"bg-[var(--bg-subtle)]",labelKey:""}:t>=.8?{ring:"stroke-emerald-500",text:"text-emerald-700",bg:"bg-emerald-50",labelKey:"candidates.confidenceHighLabel"}:t>=.6?{ring:"stroke-blue-500",text:"text-blue-700",bg:"bg-blue-50",labelKey:"candidates.confidenceMediumLabel"}:t>=.4?{ring:"stroke-amber-500",text:"text-amber-700",bg:"bg-amber-50",labelKey:"candidates.confidenceMediumLowLabel"}:{ring:"stroke-red-500",text:"text-red-700",bg:"bg-red-50",labelKey:"candidates.confidenceLowLabel"}}function Ic(t,s=4){return t?la(t).split(`
`).slice(0,s).join(`
`):""}const Oa={"bootstrap-scan":{labelKey:"knowledge.sourceBootstrap",color:"text-violet-600 bg-violet-50 border-violet-200"},mcp:{labelKey:"knowledge.sourceMcp",color:"text-blue-600 bg-blue-50 border-blue-200"},manual:{labelKey:"knowledge.sourceManual",color:"text-emerald-600 bg-emerald-50 border-emerald-200"},"file-watcher":{labelKey:"knowledge.sourceFileWatcher",color:"text-orange-600 bg-orange-50 border-orange-200"},clipboard:{labelKey:"knowledge.sourceClipboard",color:"text-pink-600 bg-pink-50 border-pink-200"},cli:{labelKey:"knowledge.sourceCli",color:"text-[var(--fg-secondary)] bg-[var(--bg-subtle)] border-[var(--border-default)]"},agent:{labelKey:"knowledge.sourceAgent",color:"text-violet-600 bg-violet-50 border-violet-200"},submit_with_check:{labelKey:"knowledge.sourceSubmitCheck",color:"text-teal-600 bg-teal-50 border-teal-200"}},Tc={"source file deleted (orphan)":"源文件已删除(孤儿条目)"};function Ec(t){return Tc[t]??t}const Pc=({onRefresh:t,idTitleMap:s})=>{const{t:a}=Ae(),r=f=>({pending:a("knowledge.lifecyclePending"),staging:a("knowledge.lifecycleStaging"),active:a("knowledge.lifecycleActive"),evolving:a("knowledge.lifecycleEvolving"),decaying:a("knowledge.lifecycleDecaying"),deprecated:a("knowledge.lifecycleDeprecated")})[f]||f,o=f=>({publish:a("knowledge.actionPublish"),stage:a("knowledge.actionStage"),deprecate:a("knowledge.actionDeprecate"),reactivate:a("knowledge.actionReactivate"),evolve:a("knowledge.actionEvolve"),decay:a("knowledge.actionDecay")})[f]||f,[l,i]=n.useState([]),[p,d]=n.useState(null),[g,x]=n.useState({}),[h,u]=n.useState(!0),[m,c]=n.useState(1),[j,S]=n.useState(12),[D,I]=n.useState(0),[P,Y]=n.useState(""),[w,G]=n.useState(""),[_,N]=n.useState(""),[E,L]=n.useState(""),[$,U]=n.useState(""),{isWide:q,toggle:A}=ia(),[y,W]=n.useState(null),[re,he]=n.useState(!1),[ue,V]=n.useState(new Set),[B,oe]=n.useState(!1),me=n.useRef(!0);n.useEffect(()=>(me.current=!0,()=>{me.current=!1}),[]);const R=n.useCallback(async()=>{u(!0);try{const f=await Z.knowledgeList({page:m,limit:j,lifecycle:P||void 0,kind:w||void 0,category:_||void 0,keyword:E||void 0});me.current&&(i(f.data||[]),I(f.pagination?.total||0))}catch(f){ne(ke(f,a("knowledge.loadFailed")),{title:a("common.loadFailed"),type:"error"})}finally{me.current&&u(!1)}},[m,j,P,w,_,E]),T=n.useCallback(async()=>{try{const f=await Z.knowledgeStats();me.current&&d(f)}catch{}},[]),ee=n.useCallback(async()=>{try{const f=await Z.getKnowledgeLifecycle();me.current&&x(f.counts||{})}catch{}},[]);n.useEffect(()=>{R()},[R]),n.useEffect(()=>{T()},[T]),n.useEffect(()=>{ee()},[ee]),n.useEffect(()=>{const f=setTimeout(()=>{L($),c(1)},300);return()=>clearTimeout(f)},[$]),n.useEffect(()=>{c(1)},[P,w,_]);const ie=n.useCallback(()=>{R(),T(),ee(),t?.()},[R,T,ee,t]),xe=n.useMemo(()=>{const f=new Map;if(s)for(const[J,ge]of Object.entries(s))f.set(J,ge);for(const J of l)J.id&&J.title&&f.set(J.id,J.title);return f},[l,s]),pe=async(f,J,ge)=>{he(!0);try{const ve=await Z.knowledgeLifecycle(f.id,J,ge);ne(`${f.title} → ${a(lt[ve.lifecycle]?.labelKey||"")||ve.lifecycle}`,{title:a("knowledge.operationSuccess")}),i(k=>k.map(b=>b.id===f.id?ve:b)),y?.id===f.id&&W(ve),T()}catch(ve){ne(ke(ve,a("common.operationFailed")),{title:a("common.operationFailed"),type:"error"})}finally{me.current&&he(!1)}},M=async f=>{if(confirm(a("knowledge.deleteConfirmMsg",{title:f.title})))try{await Z.knowledgeDelete(f.id),ne(a("knowledge.deleteSuccess",{title:f.title}),{title:a("common.delete")}),i(J=>J.filter(ge=>ge.id!==f.id)),y?.id===f.id&&W(null),T()}catch(J){ne(ke(J,a("knowledge.deleteFailed")),{title:a("knowledge.deleteFailed"),type:"error"})}},Ce=["pending","staging"],F=async()=>{if(ue.size===0)return;const f=l.filter(J=>ue.has(J.id)&&Ce.includes(J.lifecycle)).map(J=>J.id);if(f.length===0){ne(a("knowledge.noPublishable"),{title:a("knowledge.batchPublish"),type:"info"});return}oe(!0);try{const J=await Z.knowledgeBatchPublish(f);ne(a("knowledge.batchPublishResult",{success:J.successCount,fail:J.failureCount}),{title:a("knowledge.batchPublish")}),V(new Set),ie()}catch(J){ne(ke(J,a("knowledge.batchPublishFailed")),{title:a("common.operationFailed"),type:"error"})}finally{oe(!1)}},Se=async()=>{oe(!0);try{const J=((await Z.knowledgeList({lifecycle:"pending",limit:500})).data||[]).filter(ve=>ve.autoApprovable).map(ve=>ve.id);if(J.length===0){ne(a("knowledge.noAutoApprovable"),{title:a("knowledge.noPublishable")});return}const ge=await Z.knowledgeBatchPublish(J);ne(a("knowledge.autoPublishResult",{count:ge.successCount}),{title:a("knowledge.batchPublishComplete")}),ie()}catch(f){ne(ke(f,a("knowledge.batchPublishFailed")),{title:a("common.operationFailed"),type:"error"})}finally{oe(!1)}},Te=async()=>{if(ue.size===0)return;const f=l.filter(J=>ue.has(J.id)&&(J.lifecycle==="active"||J.lifecycle==="evolving")).map(J=>J.id);if(f.length===0){ne(a("knowledge.noDeprecatable"),{title:a("knowledge.batchDeprecate"),type:"info"});return}oe(!0);try{const J=await Z.knowledgeBatchDeprecate(f);ne(a("knowledge.batchDeprecateResult",{success:J.successCount,fail:J.failureCount}),{title:a("knowledge.batchDeprecate")}),V(new Set),ie()}catch(J){ne(ke(J,a("knowledge.batchDeprecateFailed")),{title:a("common.operationFailed"),type:"error"})}finally{oe(!1)}},_e=async()=>{if(ue.size!==0&&confirm(a("knowledge.batchDeleteConfirm",{count:ue.size}))){oe(!0);try{const f=await Z.knowledgeBatchDelete([...ue]);ne(a("knowledge.batchDeleteResult",{success:f.deletedCount,fail:f.failureCount}),{title:a("knowledge.batchDelete")}),V(new Set),ie()}catch(f){ne(ke(f,a("knowledge.batchDeleteFailed")),{title:a("common.operationFailed"),type:"error"})}finally{oe(!1)}}},Me=f=>{V(J=>{const ge=new Set(J);return ge.has(f)?ge.delete(f):ge.add(f),ge})},te=()=>{ue.size===l.length?V(new Set):V(new Set(l.map(f=>f.id)))},de=(f,J)=>{const ge=prompt(a("knowledge.deprecateReasonPrompt"));ge&&pe(f,J,ge)};return e.jsxs("div",{className:"space-y-4 pb-6",children:[(()=>{const f=g;if(!Object.values(f).some(z=>z>0)&&!p)return null;const ge=z=>f[z]??p?.[z]??0,ve=({stateKey:z,onClick:le})=>{const O=lt[z];if(!O)return null;const v=O.icon,se=ge(z),be=P===z;return e.jsxs("button",{onClick:le,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors whitespace-nowrap ${be?`${O.bg} ${O.border} ${O.color} shadow-sm`:`border-transparent ${O.hoverBorder} text-[var(--fg-secondary)]`}`,children:[e.jsx(v,{size:14,className:be?"":"opacity-60"}),e.jsx("span",{children:r(z)}),e.jsx("span",{className:`ml-0.5 inline-flex items-center justify-center min-w-[20px] h-5 px-1.5 rounded text-[11px] font-bold ${O.badgeBg} ${O.badgeColor}`,children:se})]})},k=()=>e.jsx("span",{className:"text-[var(--fg-muted)] text-xs opacity-40 select-none",children:"→"}),b=z=>Y(P===z?"":z);return e.jsxs("div",{className:"flex items-center gap-x-1.5 gap-y-2 flex-wrap text-[var(--fg-secondary)]",children:[e.jsx(ve,{stateKey:"pending",onClick:()=>b("pending")}),e.jsx(k,{}),e.jsx(ve,{stateKey:"staging",onClick:()=>b("staging")}),e.jsx(k,{}),e.jsx(ve,{stateKey:"active",onClick:()=>b("active")}),e.jsx(k,{}),e.jsx(ve,{stateKey:"evolving",onClick:()=>b("evolving")}),e.jsx("span",{className:"mx-1.5 h-4 border-l border-[var(--border-default)]"}),e.jsx(ve,{stateKey:"decaying",onClick:()=>b("decaying")}),e.jsx(k,{}),e.jsx(ve,{stateKey:"deprecated",onClick:()=>b("deprecated")})]})})(),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-md",children:[e.jsx(xt,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-[var(--fg-muted)]",size:16}),e.jsx("input",{type:"text",placeholder:a("knowledge.searchPlaceholder"),value:$,onChange:f=>U(f.target.value),className:"w-full pl-9 pr-3 py-2 rounded-lg border border-[var(--border-default)] text-sm focus:outline-none focus:ring-2 focus:ring-blue-300"})]}),e.jsx("div",{className:"flex gap-1",children:Object.entries($t).map(([f,J])=>{const ge=J.icon;return e.jsxs("button",{onClick:()=>G(w===f?"":f),className:`flex items-center gap-1 px-2.5 py-1.5 rounded-md text-xs font-medium border transition-all ${w===f?`${J.bg} ${J.border} ${J.color}`:"bg-[var(--bg-surface)] border-[var(--border-default)] text-[var(--fg-secondary)] hover:bg-[var(--bg-subtle)]"}`,children:[e.jsx(ge,{size:12}),a(J.labelKey)]},f)})}),e.jsx(tt,{value:_,onChange:f=>N(f),options:[{value:"",label:a("knowledge.allCategories")},...["View","Service","Tool","Model","Network","Storage","UI","Utility"].map(f=>({value:f,label:f}))],size:"sm",className:"text-xs"}),e.jsx("button",{onClick:ie,className:"p-2 rounded-md text-[var(--fg-muted)] hover:bg-[var(--bg-subtle)]",title:a("common.refresh"),children:e.jsx(at,{size:16})}),ue.size>0&&(()=>{const f=l.filter(ge=>ue.has(ge.id)&&Ce.includes(ge.lifecycle)).length,J=l.filter(ge=>ue.has(ge.id)&&(ge.lifecycle==="active"||ge.lifecycle==="evolving")).length;return e.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[e.jsx("span",{className:"text-xs text-[var(--fg-secondary)]",children:a("knowledge.selectedCount",{count:ue.size})}),f>0&&e.jsxs("button",{onClick:F,disabled:B,className:"px-2.5 py-1 text-xs font-medium text-green-700 bg-green-50 border border-green-200 rounded-md hover:bg-green-100 disabled:opacity-50",children:[B?e.jsx(Ne,{size:12,className:"animate-spin"}):a("knowledge.batchPublish")," (",f,")"]}),J>0&&e.jsxs("button",{onClick:Te,disabled:B,className:"px-2.5 py-1 text-xs font-medium text-amber-700 bg-amber-50 border border-amber-200 rounded-md hover:bg-amber-100 disabled:opacity-50 flex items-center gap-1",children:[B?e.jsx(Ne,{size:12,className:"animate-spin"}):e.jsx(qt,{size:12}),a("knowledge.batchDeprecate")," (",J,")"]}),e.jsxs("button",{onClick:_e,disabled:B,className:"px-2.5 py-1 text-xs font-medium text-red-700 bg-red-50 border border-red-200 rounded-md hover:bg-red-100 disabled:opacity-50 flex items-center gap-1",children:[B?e.jsx(Ne,{size:12,className:"animate-spin"}):e.jsx(qe,{size:12}),a("knowledge.batchDelete")," (",ue.size,")"]}),e.jsx("button",{onClick:()=>V(new Set),className:"p-1 text-[var(--fg-muted)] hover:text-[var(--fg-primary)]",children:e.jsx(ze,{size:14})})]})})(),ue.size===0&&l.some(f=>f.lifecycle==="pending")&&e.jsxs("button",{onClick:Se,disabled:B,className:"ml-auto px-3 py-1.5 text-xs font-medium text-cyan-700 bg-cyan-50 border border-cyan-200 rounded-md hover:bg-cyan-100 disabled:opacity-50 flex items-center gap-1.5",children:[B?e.jsx(Ne,{size:12,className:"animate-spin"}):e.jsx(Be,{size:12}),a("knowledge.quickBatchPublish")]})]}),h?e.jsx(Ac,{}):l.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-[var(--fg-muted)]",children:[e.jsx(Qs,{size:48,className:"mb-4 opacity-30"}),e.jsx("p",{className:"text-sm",children:a("knowledge.noResults")}),(E||P||w||_)&&e.jsx("button",{onClick:()=>{U(""),Y(""),G(""),N("")},className:"mt-2 text-xs text-blue-500 hover:text-blue-700",children:a("knowledge.clearFilters")})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 px-1",children:[e.jsx("input",{type:"checkbox",checked:ue.size===l.length&&l.length>0,onChange:te,className:"rounded border-[var(--border-default)]"}),e.jsx("span",{className:"text-xs text-[var(--fg-muted)]",children:a("knowledge.selectAll")}),e.jsx("span",{className:"text-xs text-[var(--fg-muted)] ml-auto",children:a("knowledge.totalCount",{count:D})})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 items-start",children:l.map(f=>{const J=lt[f.lifecycle]||lt.pending,ge=$t[f.kind]||$t.pattern,ve=J.icon,k=ge.icon,b=Rc(f.reasoning?.confidence);return e.jsxs("div",{onClick:()=>W(f),className:`group bg-[var(--bg-surface)] rounded-xl border shadow-sm hover:shadow-md cursor-pointer transition-all overflow-hidden ${y?.id===f.id?"ring-2 ring-blue-300 border-blue-200":"border-[var(--border-default)]"}`,children:[e.jsxs("div",{className:"px-4 pt-3 pb-2",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[e.jsx("input",{type:"checkbox",checked:ue.has(f.id),onChange:z=>{z.stopPropagation(),Me(f.id)},onClick:z=>z.stopPropagation(),className:"rounded border-[var(--border-default)]"}),e.jsxs("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium ${J.bg} ${J.color} ${J.border} border`,children:[e.jsx(ve,{size:10}),r(f.lifecycle)]}),e.jsxs("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium ${ge.bg} ${ge.color} ${ge.border} border`,children:[e.jsx(k,{size:10}),a(ge.labelKey)]}),f.category&&e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)]",children:f.category}),e.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded ${b.bg} ${b.text}`,children:f.reasoning?.confidence!=null?`${Math.round(f.reasoning.confidence*100)}%`:"—"}),f.autoApprovable&&f.lifecycle==="pending"&&e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-[10px] px-1.5 py-0.5 rounded bg-cyan-50 text-cyan-600 border border-cyan-200",children:[e.jsx(Be,{size:9}),a("knowledge.autoApprovable")]})]}),e.jsx("h3",{className:"text-sm font-bold text-[var(--fg-primary)] mb-1 break-words leading-snug",children:f.title}),(f.description||f.content?.rationale)&&e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] line-clamp-2 leading-relaxed",children:f.description||f.content?.rationale||""}),f.content?.pattern&&e.jsx("pre",{className:"mt-1.5 text-[10px] text-[var(--fg-secondary)] bg-[var(--bg-subtle)] rounded p-1.5 line-clamp-3 font-mono overflow-hidden",children:Ic(f.content.pattern,3)})]}),e.jsxs("div",{className:"px-4 py-2 bg-[var(--bg-subtle)] border-t border-[var(--border-default)] flex items-center gap-2",children:[f.tags?.slice(0,3).map(z=>e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100",children:z},z)),f.tags&&f.tags.length>3&&e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)]",children:["+",f.tags.length-3]}),e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)] ml-auto",children:[f.trigger&&e.jsx("span",{className:"text-blue-400 mr-2",children:f.trigger}),f.source&&e.jsx("span",{className:"mr-2",children:f.source}),Ot(f.updatedAt,a)]})]})]},f.id)})}),e.jsx(ca,{currentPage:m,totalPages:Math.ceil(D/j),onPageChange:c,pageSize:j,onPageSizeChange:f=>{S(f),c(1)},totalItems:D})]}),y&&(()=>{const f=lt[y.lifecycle]||lt.pending,J=$t[y.kind]||$t.pattern,ge=et[y.category||""]||et.All||{},ve=y.reasoning,k=l.findIndex(v=>v.id===y.id),b=k>0,z=k<l.length-1,le=()=>{b&&W(l[k-1])},O=()=>{z&&W(l[k+1])};return e.jsxs(Ie,{open:!!y,onClose:()=>W(null),size:q?"lg":"md",children:[e.jsxs(Ie.Header,{title:y.title,leading:e.jsx("button",{onClick:()=>{M(y),W(null)},title:a("common.delete"),className:"p-1.5 text-[var(--fg-muted)] hover:text-red-500 rounded-md transition-colors opacity-30 hover:opacity-100 shrink-0",children:e.jsx(qe,{size:14})}),children:[e.jsx(Ie.Nav,{currentIndex:k,total:l.length,onPrev:le,onNext:O,hasPrev:b,hasNext:z}),e.jsxs(Ie.HeaderActions,{children:[e.jsx(Ie.WidthToggle,{isWide:q,onToggle:A,title:a(q?"knowledge.narrow":"knowledge.widen")}),e.jsx(Ie.CloseButton,{onClose:()=>W(null)})]})]}),e.jsxs(Ie.Body,{children:[y.rejectionReason&&e.jsxs("div",{className:"px-6 py-3 border-b border-[var(--border-default)] bg-red-500/10",children:[e.jsx("label",{className:"text-[10px] font-bold text-red-400 uppercase mb-1.5 block",children:a("knowledge.rejectionReason")}),e.jsx("p",{className:"text-xs text-red-500 dark:text-red-400",children:Ec(y.rejectionReason)})]}),e.jsx(da,{badges:(()=>{const v=[];return v.push({label:r(y.lifecycle),className:`${f.bg} ${f.color} ${f.border}`,icon:f.icon}),v.push({label:a(J.labelKey),className:`${J.bg} ${J.color} ${J.border}`,icon:J.icon}),v.push({label:y.category||"general",className:`font-bold uppercase ${ge?.bg||"bg-[var(--bg-subtle)]"} ${ge?.color||"text-[var(--fg-muted)]"} ${ge?.border||"border-[var(--border-default)]"}`}),y.knowledgeType&&v.push({label:y.knowledgeType,className:"bg-purple-50 text-purple-700 border-purple-200"}),y.language&&v.push({label:y.language,className:"uppercase font-bold text-[var(--fg-secondary)] bg-[var(--bg-subtle)] border-[var(--border-default)]"}),y.trigger&&v.push({label:y.trigger,className:"font-mono font-bold bg-amber-50 text-amber-700 border-amber-200"}),v})(),metadata:(()=>{const v=[];return y.scope&&v.push({icon:Ct,iconClass:"text-teal-400",label:a("knowledge.scope"),value:y.scope==="universal"?a("knowledge.scopeUniversal"):y.scope==="project-specific"?a("knowledge.scopeProject"):y.scope==="module-level"?a("knowledge.scopeModule"):y.scope}),y.complexity&&v.push({icon:Ge,iconClass:"text-orange-400",label:a("knowledge.complexity"),value:y.complexity==="advanced"?a("knowledge.complexityAdvanced"):y.complexity==="intermediate"?a("knowledge.complexityIntermediate"):y.complexity==="beginner"?a("knowledge.complexityBeginner"):y.complexity}),y.source&&y.source!=="unknown"&&v.push({icon:Ct,iconClass:"text-violet-400",label:a("knowledge.source"),value:Oa[y.source||""]?a(Oa[y.source||""].labelKey):y.source||"-"}),y.createdAt&&v.push({icon:Ye,iconClass:"text-[var(--fg-muted)]",label:a("knowledge.createdAt"),value:Ot(y.createdAt,a)}),y.updatedAt&&v.push({icon:Ye,iconClass:"text-[var(--fg-muted)]",label:a("knowledge.updatedAt"),value:Ot(y.updatedAt,a)}),y.publishedAt&&v.push({icon:bt,iconClass:"text-emerald-400",label:a("knowledge.published"),value:Ot(y.publishedAt,a)}),v})(),tags:y.tags,id:y.id,sourceFile:y.sourceFile??void 0,sourceFileLabel:a("knowledge.sourceFile")}),y.relations&&Object.entries(y.relations).some(([,v])=>Array.isArray(v)&&v.length>0)&&e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[e.jsx(ta,{size:12,className:"text-purple-400"}),e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase",children:a("knowledge.relatedKnowledge")}),(()=>{const v=Object.values(y.relations).flat().length;return v>0?e.jsx("span",{className:"text-[9px] bg-purple-100 text-purple-600 px-1.5 py-0.5 rounded-full font-bold",children:v}):null})()]}),e.jsx("div",{className:"space-y-1.5",children:Object.entries(y.relations).map(([v,se])=>!Array.isArray(se)||se.length===0?null:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-[10px] font-mono text-[var(--fg-secondary)] shrink-0 whitespace-nowrap pt-0.5 uppercase",children:v}),e.jsx("div",{className:"flex flex-wrap gap-1",children:se.map((be,fe)=>{const De=be.target||(typeof be=="string"?be:JSON.stringify(be)),ae=xe.get(De)||De;return e.jsx("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 border rounded text-[10px] font-mono bg-purple-50 border-purple-200 text-purple-700",title:De,children:ae},fe)})})]},v))})]}),y.stats&&Object.values(y.stats).some(v=>typeof v=="number"&&v>0)||y.quality&&y.quality.overall>0?e.jsxs("div",{className:"px-6 py-3 border-b border-[var(--border-default)]",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"bg-amber-50/60 rounded-xl p-3 text-center border border-amber-100",children:[e.jsx("div",{className:"text-lg font-bold text-amber-700",children:y.stats?.authority||Math.round((y.quality?.overall||0)*5)||"—"}),e.jsx("div",{className:"text-[10px] text-amber-500 font-medium",children:a("knowledge.authorityScore")})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-xl p-3 text-center border border-[var(--border-default)]",children:[e.jsx("div",{className:"text-lg font-bold text-[var(--fg-primary)]",children:y.stats?.guardHits??0}),e.jsx("div",{className:"text-[10px] text-[var(--fg-muted)] font-medium",children:a("knowledge.guardHits")})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-xl p-3 text-center border border-[var(--border-default)]",children:[e.jsx("div",{className:"text-lg font-bold text-[var(--fg-primary)]",children:y.stats?.adoptions??0}),e.jsx("div",{className:"text-[10px] text-[var(--fg-muted)] font-medium",children:a("knowledge.adoptions")})]}),e.jsxs("div",{className:"bg-blue-50/60 rounded-xl p-3 text-center border border-blue-100",children:[e.jsx("div",{className:"text-lg font-bold text-blue-700",children:y.stats?.searchHits??0}),e.jsx("div",{className:"text-[10px] text-blue-500 font-medium",children:a("knowledge.searchHits")})]})]}),y.stats&&(y.stats.views>0||y.stats.applications>0)&&e.jsxs("div",{className:"flex items-center gap-4 mt-2 text-[10px] text-[var(--fg-muted)]",children:[e.jsxs("span",{children:[a("knowledge.statViews"),": ",y.stats.views]}),e.jsxs("span",{children:[a("knowledge.statApplications"),": ",y.stats.applications]})]})]}):null,e.jsx(Ee.Reasoning,{reasoning:ve,labels:{section:a("knowledge.reasoning"),source:`${a("knowledge.source")}:`,confidence:`${a("knowledge.confidence")}:`,alternatives:`${a("knowledge.alternatives")}:`},filterSubmitted:!0}),e.jsx(Ee.Quality,{quality:y.quality,labels:{section:a("knowledge.qualityGrade"),completeness:a("knowledge.qualityCompletionLabel"),adaptation:a("knowledge.qualityAdaptation"),documentation:a("knowledge.qualityDocumentation")}}),e.jsx(Ee.Description,{label:a("knowledge.summary"),text:y.description}),e.jsx(Ee.MarkdownSection,{label:a("knowledge.markdownDoc"),content:y.content?.markdown}),e.jsx(Ee.Headers,{label:a("knowledge.importHeaders"),headers:y.headers}),e.jsx(Ee.CodePattern,{label:a("knowledge.codePattern"),code:y.content?.pattern,language:y.language}),e.jsx(Ee.Delivery,{delivery:{topicHint:y.topicHint,whenClause:y.whenClause,doClause:y.doClause,dontClause:y.dontClause,coreCode:y.coreCode},language:y.language}),e.jsx(Ee.Rationale,{label:a("knowledge.designRationale"),text:y.content?.rationale}),e.jsx(Ee.Steps,{label:a("knowledge.implementSteps"),steps:y.content?.steps}),e.jsx(Ee.Constraints,{label:a("knowledge.constraintsLabel"),constraints:y.constraints}),y.aiInsight&&e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(St,{size:11,className:"text-cyan-400"})," ",a("knowledge.aiInsight")]}),e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] leading-relaxed",children:y.aiInsight})]}),(()=>{const v=Array.isArray(y.lifecycleHistory)?y.lifecycleHistory:(()=>{try{const se=typeof y.lifecycleHistory=="string"?JSON.parse(y.lifecycleHistory):null;return Array.isArray(se)?se:[]}catch{return[]}})();return v.length>0?e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(Ye,{size:11,className:"text-[var(--fg-muted)]"})," ",a("knowledge.lifecycleHistoryLabel")]}),e.jsx("div",{className:"space-y-1",children:v.map((se,be)=>{const fe=lt[se.from]||lt.pending,De=lt[se.to]||lt.pending;return e.jsxs("div",{className:"flex items-center gap-2 text-[10px]",children:[e.jsx("span",{className:"text-[var(--fg-muted)] w-20 shrink-0",children:Ot(se.at,a)}),e.jsx("span",{className:`${fe.color}`,children:r(se.from)}),e.jsx("span",{className:"text-[var(--fg-muted)]",children:"→"}),e.jsx("span",{className:`${De.color} font-medium`,children:r(se.to)}),e.jsxs("span",{className:"text-[var(--fg-muted)] ml-auto",children:["by ",se.by]})]},be)})})]}):null})()]}),e.jsxs(Ie.Footer,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("button",{onClick:()=>{M(y),W(null)},className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium text-red-500 hover:bg-red-50 border border-red-200 transition-colors",children:[e.jsx(qe,{size:14})," ",a("common.delete")]})}),e.jsx("div",{className:"flex items-center gap-2",children:(Dc[y.lifecycle]||[]).map(v=>{const se=v.icon;return e.jsxs("button",{onClick:()=>v.needsReason?de(y,v.action):pe(y,v.action),disabled:re,className:`flex items-center gap-1.5 px-4 py-2 rounded-lg text-xs font-bold border transition-colors disabled:opacity-50 ${v.bg} ${v.color} border-current/20`,children:[re?e.jsx(Ne,{size:14,className:"animate-spin"}):e.jsx(se,{size:14}),o(v.action)]},v.action)})})]})]})})()]})},is={manual:{label:"manual",color:"bg-[var(--bg-subtle)] text-[var(--fg-secondary)]",icon:yr},"user-ai":{label:"user-ai",color:"bg-violet-100 text-violet-600",icon:Le},"system-ai":{label:"system-ai",color:"bg-amber-100 text-amber-600",icon:Jt},"external-ai":{label:"external-ai",color:"bg-cyan-100 text-cyan-600",icon:aa}},Mc=({onRefresh:t,signalSuggestionCount:s=0,onSuggestionCountChange:a})=>{const{t:r}=Ae(),[o,l]=n.useState([]),[i,p]=n.useState(!0),[d,g]=n.useState(null),[x,h]=n.useState(!1),[u,m]=n.useState(!1),[c,j]=n.useState("all"),[S,D]=n.useState(!1),[I,P]=n.useState([]),[Y,w]=n.useState(!1),[G,_]=n.useState(!1),[N,E]=n.useState(null),[L,$]=n.useState(!1),[U,q]=n.useState(""),[A,y]=n.useState(!1),[W,re]=n.useState(!1),[he,ue]=n.useState(!1),V=n.useCallback(async()=>{p(!0);try{const F=await Z.listSkills();l(F.skills||[])}catch(F){Vl(F)!==404&&ne(ke(F,""),{title:r("skills.fetchFailed"),type:"error"}),l([])}finally{p(!1)}},[]);n.useEffect(()=>{V()},[V]);const B=async F=>{if(d?.skillName===F){g(null);return}$(!1),re(!1),h(!0);try{const Se=await Z.loadSkill(F);g(Se)}catch{ne(`"${F}" ${r("skills.loadError")}`,{title:r("skills.loadSkillFailed"),type:"error"})}finally{h(!1)}},oe=()=>{d?.content&&(navigator.clipboard.writeText(d.content).catch(()=>{}),D(!0),setTimeout(()=>D(!1),2e3))},me=()=>{d&&(q(d.content),$(!0))},R=()=>{$(!1),q("")},T=async()=>{if(!(!d||!U.trim())){y(!0);try{await Z.updateSkill(d.skillName,{content:U}),ne(r("skills.saveSuccess"),{title:`Skill "${d.skillName}" ${r("skills.updateSuccess")}`}),$(!1);const F=await Z.loadSkill(d.skillName);g(F)}catch(F){ne(ke(F,""),{title:r("skills.updateFailed"),type:"error"})}finally{y(!1)}}},ee=async()=>{if(d){ue(!0);try{await Z.deleteSkill(d.skillName),ne(r("skills.deleteSuccess"),{title:`Skill "${d.skillName}" ${r("skills.deleteSuccess")}`}),g(null),re(!1),$(!1),V(),t?.()}catch(F){ne(ke(F,""),{title:r("skills.deleteFailed"),type:"error"})}finally{ue(!1)}}},ie=async()=>{w(!0),_(!0);try{const[F,Se]=await Promise.allSettled([Z.suggestSkills(),Z.getSignalStatus()]),Te=F.status==="fulfilled"?F.value.suggestions||[]:[],_e=Se.status==="fulfilled"?Se.value.suggestions||[]:[],Me=new Map;for(const de of Te)Me.set(de.name,de);for(const de of _e)Me.set(de.name,{...Me.get(de.name),...de});const te=[...Me.values()];P(te),a?.(te.length)}catch(F){ne(ke(F,""),{title:r("skills.aiRecommendFailed"),type:"error"}),P([]),a?.(0)}finally{w(!1)}};n.useEffect(()=>{s>0&&I.length===0&&!G&&ie()},[]);const xe=async F=>{E(F.name);try{const Se=F.description||F.rationale||F.name,Te=`${r("skillsView.aiPromptPrefix")}

名称:${F.name}
描述:${Se}
推荐原因:${F.rationale}

请直接生成 Skill 正文内容(Markdown 格式),不需要 frontmatter,不需要输出 JSON 元数据。内容应该详细、实用,包含具体的操作指南和示例。`;let Me=(await Z.aiGenerateSkill(Te)).reply||F.body||`# ${Se}

${F.rationale||""}`;Me=Me.replace(/^\s*\{["']name["']\s*:.*\}\s*\n?/,"").trim(),await Z.createSkill({name:F.name,description:Se,content:Me,createdBy:"user-ai"}),ne(r("skills.createAddedToKB"),{title:`Skill "${F.name}" ${r("skills.createSuccess")}`}),P(te=>{const de=te.filter(f=>f.name!==F.name);return a?.(de.length),de}),V()}catch(Se){ne(ke(Se,""),{title:r("skills.createFailed"),type:"error"})}finally{E(null)}},pe=o.filter(F=>c==="all"?!0:F.source===c).sort((F,Se)=>F.source===Se.source?F.name.localeCompare(Se.name):F.source==="project"?-1:1),M=o.filter(F=>F.source==="builtin").length,Ce=o.filter(F=>F.source==="project").length;return e.jsxs("div",{className:"h-full flex flex-col",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-violet-50 border border-violet-100 flex items-center justify-center shrink-0",children:e.jsx(ds,{size:20,className:"text-violet-600"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-lg xl:text-xl font-bold text-[var(--fg-primary)]",children:r("skills.title")}),e.jsx("p",{className:"text-xs text-[var(--fg-muted)] mt-0.5 truncate",children:r("skills.subtitle")})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("button",{onClick:V,className:"p-2 rounded-lg text-[var(--fg-muted)] hover:text-[var(--fg-secondary)] hover:bg-[var(--bg-subtle)] transition-colors",title:r("common.refresh"),children:e.jsx(at,{size:16})}),e.jsxs("button",{onClick:ie,disabled:Y,className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-all ${Y?"text-[var(--fg-muted)] bg-[var(--bg-subtle)] cursor-not-allowed":"text-amber-600 dark:text-amber-400 bg-amber-500/10 border border-amber-500/20 hover:bg-amber-500/20"}`,title:r("skills.aiRecommendTooltip"),children:[Y?e.jsx(Ne,{size:14,className:"animate-spin"}):e.jsx(St,{size:14}),r("skills.aiRecommend")]}),e.jsxs("button",{onClick:()=>m(!0),className:"flex items-center gap-1.5 px-3.5 py-2 rounded-lg text-xs font-bold text-violet-600 dark:text-violet-400 bg-violet-500/10 border border-violet-500/20 hover:bg-violet-500/20 transition-all",children:[e.jsx(Le,{size:14}),r("skills.addSkill")]})]})]}),e.jsx("div",{className:"flex items-center gap-1.5 mb-4",children:[{key:"all",label:r("common.all"),count:o.length},{key:"project",label:r("skills.filterProject"),count:Ce,icon:Lt},{key:"builtin",label:r("skills.filterBuiltin"),count:M,icon:bl}].map(F=>e.jsxs("button",{onClick:()=>j(F.key),className:`flex items-center gap-1.5 px-4 py-1.5 rounded-md text-xs font-medium transition-colors ${c===F.key?"bg-[var(--accent-subtle)] text-[var(--accent)] border border-[var(--accent-emphasis)]":"text-[var(--fg-muted)] hover:bg-[var(--bg-subtle)] border border-transparent"}`,children:[F.icon&&e.jsx(F.icon,{size:12}),F.label,e.jsx("span",{className:`ml-0.5 px-1.5 py-0.5 rounded-full text-[10px] ${c===F.key?"bg-[var(--accent-subtle)] text-[var(--accent)]":"bg-[var(--bg-subtle)] text-[var(--fg-secondary)]"}`,children:F.count})]},F.key))}),G&&e.jsxs("div",{className:"mb-4 border border-amber-200 bg-amber-50/50 rounded-xl p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(St,{size:16,className:"text-amber-600"}),e.jsx("span",{className:"text-sm font-semibold text-amber-800",children:r("skills.aiRecommendDesc")}),I.length>0&&e.jsx("span",{className:"px-1.5 py-0.5 bg-amber-200 text-amber-700 text-[10px] font-bold rounded-full",children:I.length})]}),e.jsx("button",{onClick:()=>_(!1),className:"p-1 text-amber-400 hover:text-amber-600",children:e.jsx(ze,{size:14})})]}),Y?e.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-xs py-2",children:[e.jsx(Ne,{size:14,className:"animate-spin"}),r("skills.aiRecommending")]}):I.length===0?e.jsx("p",{className:"text-xs text-amber-600/70",children:r("skills.noRecommendations")}):e.jsx("div",{className:"space-y-2",children:I.map(F=>e.jsxs("div",{className:"flex items-start gap-3 p-3 bg-[var(--bg-surface)] rounded-lg border border-amber-100",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-mono text-xs font-semibold text-[var(--fg-primary)]",children:F.name}),e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[9px] font-bold uppercase ${F.priority==="high"?"bg-red-100 text-red-600":F.priority==="medium"?"bg-amber-100 text-amber-600":"bg-[var(--bg-subtle)] text-[var(--fg-secondary)]"}`,children:F.priority}),e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)]",children:F.source})]}),e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] mb-1",children:F.description}),e.jsx("p",{className:"text-[11px] text-[var(--fg-muted)] line-clamp-2",children:F.rationale})]}),e.jsx("button",{onClick:()=>xe(F),disabled:N===F.name,className:"shrink-0 flex items-center gap-1.5 px-3 py-1.5 bg-amber-500 text-white rounded-lg hover:bg-amber-600 transition-colors text-xs font-medium disabled:opacity-50",children:N===F.name?e.jsxs(e.Fragment,{children:[e.jsx(Ne,{size:12,className:"animate-spin"})," ",r("skills.creating")]}):e.jsxs(e.Fragment,{children:[e.jsx(Be,{size:12})," ",r("skills.acceptRecommend")]})})]},F.name))})]}),e.jsxs("div",{className:"flex-1 flex gap-4 xl:gap-6 min-h-0 overflow-hidden",children:[e.jsx("div",{className:"w-1/2 overflow-y-auto pr-2 space-y-2",children:i?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx(Ne,{size:24,className:"animate-spin text-violet-400"})}):pe.length===0?e.jsxs("div",{className:"text-center py-20 text-[var(--fg-muted)]",children:[e.jsx(ds,{size:40,className:"mx-auto mb-3 opacity-40"}),e.jsx("p",{children:r("skills.noResults")})]}):pe.map(F=>e.jsx("button",{onClick:()=>B(F.name),className:`w-full text-left p-4 rounded-xl border transition-all ${d?.skillName===F.name?"border-violet-300 bg-violet-50 shadow-sm":"border-[var(--border-default)] bg-[var(--bg-surface)] hover:border-[var(--border-emphasis)] hover:shadow-sm"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`mt-0.5 shrink-0 ${d?.skillName===F.name?"text-violet-500":"text-[var(--fg-muted)]"}`,children:d?.skillName===F.name?e.jsx(gt,{size:16}):e.jsx(Ke,{size:16})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-mono text-sm font-semibold text-[var(--fg-primary)]",children:F.name}),e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider ${F.source==="builtin"?"bg-blue-100 text-blue-600":"bg-emerald-100 text-emerald-600"}`,children:F.source==="builtin"?r("skills.filterBuiltin"):r("skills.filterProject")}),F.createdBy&&is[F.createdBy]&&(()=>{const Se=is[F.createdBy],Te=Se.icon;return e.jsxs("span",{className:`flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[10px] font-medium ${Se.color}`,children:[e.jsx(Te,{size:10}),Se.label]})})()]}),e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] line-clamp-2",children:F.summary}),F.useCase&&e.jsxs("p",{className:"text-[11px] text-violet-500 mt-1 italic",children:[r("skills.useCase"),":",F.useCase]})]})]})},F.name))}),e.jsx("div",{className:"w-1/2 overflow-y-auto border border-[var(--border-default)] rounded-xl bg-[var(--bg-surface)]",children:x?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(Ne,{size:24,className:"animate-spin text-violet-400"})}):d?e.jsxs("div",{className:"h-full flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-[var(--border-default)]",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qe,{size:16,className:"text-violet-500"}),e.jsx("span",{className:"font-mono font-semibold text-sm",children:d.skillName}),e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-bold uppercase ${d.source==="builtin"?"bg-blue-100 text-blue-600":"bg-emerald-100 text-emerald-600"}`,children:d.source==="builtin"?r("skills.filterBuiltin"):r("skills.filterProject")}),d.createdBy&&is[d.createdBy]&&(()=>{const F=is[d.createdBy],Se=F.icon;return e.jsxs("span",{className:`flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[10px] font-medium ${F.color}`,children:[e.jsx(Se,{size:10}),r(`skills.createdBy.${d.createdBy}`)]})})()]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)]",children:[d.charCount," ",r("skills.chars")]}),e.jsx("button",{onClick:oe,className:"p-1.5 rounded-md hover:bg-[var(--bg-subtle)] transition-colors text-[var(--fg-muted)] hover:text-[var(--fg-secondary)]",title:r("common.copy"),children:S?e.jsx(ot,{size:14,className:"text-emerald-500"}):e.jsx(Ir,{size:14})}),d.source==="project"&&!L&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:me,className:"p-1.5 rounded-md hover:bg-blue-50 transition-colors text-[var(--fg-muted)] hover:text-blue-600",title:r("common.edit"),children:e.jsx(Os,{size:14})}),e.jsx("button",{onClick:()=>re(!0),className:"p-1.5 rounded-md hover:bg-red-50 transition-colors text-[var(--fg-muted)] hover:text-red-500",title:r("common.delete"),children:e.jsx(qe,{size:14})})]}),L&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:T,disabled:A,className:"flex items-center gap-1 px-2.5 py-1 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors text-xs font-medium disabled:opacity-50",children:[A?e.jsx(Ne,{size:12,className:"animate-spin"}):e.jsx(ws,{size:12}),r("common.save")]}),e.jsx("button",{onClick:R,className:"px-2.5 py-1 border border-[var(--border-default)] text-[var(--fg-secondary)] rounded-md hover:bg-[var(--bg-subtle)] transition-colors text-xs",children:r("common.cancel")})]})]})]}),d.relatedSkills.length>0&&e.jsxs("div",{className:"px-4 py-2 border-b border-[var(--border-default)] flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)] uppercase font-bold",children:[r("skills.related"),":"]}),d.relatedSkills.map(F=>e.jsx("button",{onClick:()=>B(F),className:"text-[11px] text-violet-600 hover:text-violet-800 bg-violet-50 px-2 py-0.5 rounded-full transition-colors",children:F},F))]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 relative",children:[L?e.jsx("textarea",{value:U,onChange:F=>q(F.target.value),className:"w-full h-full min-h-[300px] text-xs text-[var(--fg-primary)] font-mono leading-relaxed border border-blue-200 rounded-lg p-3 focus:outline-none focus:ring-2 focus:ring-blue-300 resize-none bg-blue-50/30",spellCheck:!1}):e.jsx("pre",{className:"whitespace-pre-wrap text-xs text-[var(--fg-primary)] font-mono leading-relaxed",children:d.content}),W&&e.jsx("div",{className:"absolute inset-0 bg-white/90 backdrop-blur-sm flex items-center justify-center z-10",children:e.jsxs("div",{className:"bg-[var(--bg-surface)] border border-red-200 rounded-xl shadow-lg p-6 max-w-sm text-center",children:[e.jsx(qe,{size:32,className:"mx-auto mb-3 text-red-400"}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:r("skills.deleteConfirm")}),e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] mb-4",children:r("skills.deleteSkillConfirmMsg",{name:d.skillName})}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsx("button",{onClick:()=>re(!1),className:"px-4 py-2 border border-[var(--border-default)] text-[var(--fg-secondary)] rounded-lg hover:bg-[var(--bg-subtle)] text-sm",children:r("common.cancel")}),e.jsxs("button",{onClick:ee,disabled:he,className:"flex items-center gap-1.5 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 text-sm font-medium disabled:opacity-50",children:[he?e.jsx(Ne,{size:14,className:"animate-spin"}):e.jsx(qe,{size:14}),r("skills.confirmDelete")]})]})]})})]})]}):e.jsx("div",{className:"flex items-center justify-center h-full text-[var(--fg-muted)]",children:e.jsxs("div",{className:"text-center",children:[e.jsx(ds,{size:40,className:"mx-auto mb-3 opacity-30"}),e.jsx("p",{className:"text-sm",children:r("skills.selectToView")})]})})})]}),u&&e.jsx(Lc,{onClose:()=>m(!1),onCreated:()=>{m(!1),V(),t?.()}})]})},Lc=({onClose:t,onCreated:s})=>{const{t:a}=Ae(),[r,o]=n.useState("ai"),[l,i]=n.useState(""),[p,d]=n.useState(!1),[g,x]=n.useState(""),[h,u]=n.useState(""),[m,c]=n.useState(""),[j,S]=n.useState(!1),[D,I]=n.useState(""),[P,Y]=n.useState(!1),w=async()=>{if(l.trim()){d(!0),I("");try{const N=(await Z.aiGenerateSkill(l)).reply||"";let E="",L="",$=N;const U=/```(?:json)?\s*\n?\s*(\{[^}]*"name"[^}]*\})\s*\n?\s*```/i,q=N.match(U);if(q)try{const A=JSON.parse(q[1]);E=A.name||"",L=A.description||"",$=N.replace(q[0],"").trim()}catch{}if(!E){const A=N.split(`
`);for(let y=0;y<Math.min(A.length,5);y++){const W=A[y].trim();if(!(!W||W.startsWith("```"))&&W.startsWith("{")&&W.endsWith("}"))try{const re=JSON.parse(W);if(re.name){E=re.name,L=re.description||"";let he=y+1;for(;he<A.length&&!A[he].trim();)he++;$=A.slice(he).join(`
`).trim();break}}catch{}}}if(!E){const A=/"name"\s*:\s*"([a-z][a-z0-9-]{1,62}[a-z0-9])"/,y=/"description"\s*:\s*"([^"]+)"/,W=N.match(A),re=N.match(y);W&&(E=W[1]),re&&(L=re[1])}$=$.replace(/```(?:json)?\s*\n?\s*\{[^}]*"name"[^}]*\}\s*\n?\s*```/gi,"").replace(/^\s*\{[^}]*"name"[^}]*\}\s*$/gm,"").trim(),E&&x(E),L&&u(L),c($||N.trim()),Y(!0),o("manual"),ne(a("skills.checkGenerated"),{title:a("skills.aiGenerated")})}catch(_){I(a("skills.aiGenFailed")+": "+ke(_,""))}finally{d(!1)}}},G=async()=>{if(!g.trim()||!h.trim()||!m.trim()){I(a("skills.fillRequired"));return}S(!0),I("");try{await Z.createSkill({name:g.trim(),description:h.trim(),content:m.trim(),createdBy:P?"user-ai":"manual"}),ne(a("skills.savedToKB"),{title:`Skill "${g}" ${a("skills.createSuccess")}`}),s()}catch(_){I(a("skills.createFailed")+": "+ke(_,""))}finally{S(!1)}};return e.jsxs($e,{className:"z-40 flex items-center justify-center",children:[e.jsx($e.Backdrop,{className:"bg-black/20 dark:bg-black/40 backdrop-blur-sm"}),e.jsxs("div",{className:"relative bg-[var(--bg-surface)] rounded-2xl shadow-2xl w-[720px] max-h-[85vh] flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 bg-violet-100 rounded-lg flex items-center justify-center",children:e.jsx(Le,{size:16,className:"text-violet-600"})}),e.jsx("h3",{className:"font-bold text-lg",children:a("skills.addSkill")})]}),e.jsx("button",{onClick:t,className:"p-1.5 rounded-lg hover:bg-[var(--bg-subtle)] transition-colors",children:e.jsx(ze,{size:18,className:"text-[var(--fg-muted)]"})})]}),e.jsx("div",{className:"px-6 pt-4",children:e.jsxs("div",{className:"inline-flex items-center gap-1 p-1 bg-[var(--bg-subtle)] rounded-lg",children:[e.jsxs("button",{onClick:()=>o("ai"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${r==="ai"?"bg-[var(--bg-surface)] text-violet-700 shadow-sm":"text-[var(--fg-secondary)] hover:text-[var(--fg-primary)]"}`,children:[e.jsx(Le,{size:12}),a("skills.aiGenMode")]}),e.jsxs("button",{onClick:()=>o("manual"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${r==="manual"?"bg-[var(--bg-surface)] text-violet-700 shadow-sm":"text-[var(--fg-secondary)] hover:text-[var(--fg-primary)]"}`,children:[e.jsx(Qe,{size:12}),a("skills.manualMode")]})]})}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-4 space-y-4",children:[r==="ai"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[var(--fg-primary)] mb-1.5",children:a("skills.describeSkill")}),e.jsx("div",{className:"relative",children:e.jsx("textarea",{value:l,onChange:_=>i(_.target.value),placeholder:a("skillsView.placeholderDesc"),className:"w-full h-32 px-4 py-3 border border-[var(--border-default)] rounded-xl text-sm resize-none focus:outline-none focus:ring-2 focus:ring-violet-300 focus:border-violet-400",disabled:p})})]}),e.jsx("button",{onClick:w,disabled:p||!l.trim(),className:"w-full flex items-center justify-center gap-2 px-4 py-3 bg-violet-600 text-white rounded-xl hover:bg-violet-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium",children:p?e.jsxs(e.Fragment,{children:[e.jsx(Ne,{size:16,className:"animate-spin"}),a("skills.aiGeneratingContent")]}):e.jsxs(e.Fragment,{children:[e.jsx(Zs,{size:16}),a("skills.generateSkill")]})})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-[var(--fg-primary)] mb-1.5",children:[a("skills.skillName")," ",e.jsx("span",{className:"text-[var(--fg-muted)] text-xs",children:"(kebab-case)"})]}),e.jsx("input",{type:"text",value:g,onChange:_=>x(_.target.value),placeholder:"my-custom-skill",className:"w-full px-3 py-2 border border-[var(--border-default)] rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-violet-300 focus:border-violet-400"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[var(--fg-primary)] mb-1.5",children:a("skills.skillDescription")}),e.jsx("input",{type:"text",value:h,onChange:_=>u(_.target.value),placeholder:a("skillsView.placeholderName"),className:"w-full px-3 py-2 border border-[var(--border-default)] rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-violet-300 focus:border-violet-400"})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-[var(--fg-primary)] mb-1.5",children:[a("skills.skillContent")," ",e.jsx("span",{className:"text-[var(--fg-muted)] text-xs",children:"(Markdown)"})]}),e.jsx("textarea",{value:m,onChange:_=>c(_.target.value),placeholder:a("skillsView.placeholderContent"),className:"w-full h-64 px-4 py-3 border border-[var(--border-default)] rounded-xl text-sm font-mono resize-none focus:outline-none focus:ring-2 focus:ring-violet-300 focus:border-violet-400 leading-relaxed"})]})]}),D&&e.jsxs("div",{className:"flex items-start gap-2 p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700",children:[e.jsx(Et,{size:16,className:"shrink-0 mt-0.5"}),e.jsx("span",{children:D})]})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-[var(--border-default)] flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:t,className:"px-4 py-2 text-sm text-[var(--fg-secondary)] hover:text-[var(--fg-primary)] transition-colors",children:a("common.cancel")}),r==="manual"&&e.jsx("button",{onClick:G,disabled:j||!g.trim()||!h.trim()||!m.trim(),className:"flex items-center gap-2 px-5 py-2 bg-violet-600 text-white rounded-lg hover:bg-violet-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors text-sm font-medium",children:j?e.jsxs(e.Fragment,{children:[e.jsx(Ne,{size:14,className:"animate-spin"}),a("common.saving")]}):e.jsxs(e.Fragment,{children:[e.jsx(mt,{size:14}),a("skills.addSkill")]})})]})]})]})},Ha=["architecture","swift-objc-idiom","ts-js-module","python-structure","jvm-annotation","go-module","rust-ownership","csharp-dotnet","react-patterns","vue-patterns","spring-patterns","swiftui-patterns","django-fastapi","coding-standards","design-patterns","ui-interaction","error-resilience","concurrency-async","data-event-flow","networking-api","testing-quality","security-auth","performance-optimization","observability-logging","agent-guidelines"],_c={architecture:e.jsx(Ge,{className:"w-5 h-5"}),"coding-standards":e.jsx(Ue,{className:"w-5 h-5"}),"design-patterns":e.jsx(At,{className:"w-5 h-5"}),"error-resilience":e.jsx(Le,{className:"w-5 h-5"}),"concurrency-async":e.jsx(Be,{className:"w-5 h-5"}),"data-event-flow":e.jsx(Be,{className:"w-5 h-5"}),"networking-api":e.jsx(Vt,{className:"w-5 h-5"}),"ui-interaction":e.jsx(Ge,{className:"w-5 h-5"}),"testing-quality":e.jsx(At,{className:"w-5 h-5"}),"security-auth":e.jsx(Vt,{className:"w-5 h-5"}),"performance-optimization":e.jsx(Le,{className:"w-5 h-5"}),"observability-logging":e.jsx(Ue,{className:"w-5 h-5"}),"agent-guidelines":e.jsx(aa,{className:"w-5 h-5"})};function Fc(t){return _c[t]||e.jsx(At,{className:"w-5 h-5"})}const zc=({task:t})=>{const{t:s}=Ae(),{status:a,meta:r}=t,o={skeleton:"bg-[var(--bg-subtle)] border-[var(--border-default)]",filling:"bg-blue-50 border-blue-300",completed:"bg-emerald-50 border-emerald-300",failed:"bg-red-50 border-red-300"},l={skeleton:e.jsxs("span",{className:"flex items-center gap-1 text-xs text-[var(--fg-muted)]",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-[var(--border-emphasis)]"}),s("bootstrap.statusLabels.skeleton")]}),filling:e.jsxs("span",{className:"flex items-center gap-1 text-xs text-blue-600",children:[e.jsx(Ne,{className:"w-3 h-3 animate-spin"}),s("bootstrap.statusLabels.filling")]}),completed:e.jsxs("span",{className:"flex items-center gap-1 text-xs text-emerald-600",children:[e.jsx(ot,{className:"w-3 h-3"}),s("bootstrap.statusLabels.completed")]}),failed:e.jsxs("span",{className:"flex items-center gap-1 text-xs text-red-600",children:[e.jsx(ze,{className:"w-3 h-3"}),s("bootstrap.statusLabels.failed")]})};return e.jsxs("div",{className:`relative rounded-xl border p-4 transition-all duration-300 ${o[a]||o.skeleton}`,children:[a==="skeleton"&&e.jsx("div",{className:"absolute inset-0 rounded-xl overflow-hidden",children:e.jsx("div",{className:"animate-pulse bg-gradient-to-r from-transparent via-[var(--border-default)]/40 to-transparent h-full w-full"})}),a==="filling"&&e.jsx("div",{className:"absolute inset-0 rounded-xl overflow-hidden",children:e.jsx("div",{className:"animate-pulse bg-gradient-to-r from-transparent via-blue-200/30 to-transparent h-full w-full"})}),e.jsxs("div",{className:"relative z-10 flex items-start justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`flex-shrink-0 p-2 rounded-lg ${a==="completed"?"bg-emerald-100 text-emerald-600":a==="filling"?"bg-blue-100 text-blue-600":a==="failed"?"bg-red-100 text-red-600":"bg-[var(--bg-subtle)] text-[var(--fg-muted)]"}`,children:Fc(t.id)}),e.jsxs("div",{children:[e.jsx("h3",{className:`font-medium text-sm ${a==="skeleton"?"text-[var(--fg-muted)]":"text-[var(--fg-primary)]"}`,children:(()=>{const i=`bootstrap.pipelineLabels.${r.dimId}`,p=s(i);return p!==i?p:r.label})()}),a==="completed"&&t.result&&e.jsx("p",{className:"text-xs text-emerald-600 mt-0.5",children:(()=>{const i=t.result,p=i.sourceCount??0,d=i.extracted??0;return i.type==="empty"?s("bootstrap.noMatch"):i.type==="skill"?i.empty?s("bootstrap.noMatch"):d>0?s("bootstrap.featuresAndCandidates",{sourceCount:p,extracted:d}):s("bootstrap.featuresOnly",{sourceCount:p}):d>0?s("bootstrap.candidatesOnly",{extracted:d}):s("bootstrap.noMatch")})()}),a==="failed"&&t.error&&e.jsx("p",{className:"text-xs text-red-500 mt-0.5 truncate max-w-[240px]",children:t.error})]})]}),e.jsx("div",{className:"flex-shrink-0",children:l[a]})]})]})},Bc=[{key:"round1",labelKey:"bootstrap.reviewRounds.round1Label",descKey:"bootstrap.reviewRounds.round1Desc",icon:e.jsx(sa,{className:"w-4 h-4"})},{key:"round2",labelKey:"bootstrap.reviewRounds.round2Label",descKey:"bootstrap.reviewRounds.round2Desc",icon:e.jsx(us,{className:"w-4 h-4"})},{key:"round3",labelKey:"bootstrap.reviewRounds.round3Label",descKey:"bootstrap.reviewRounds.round3Desc",icon:e.jsx(vl,{className:"w-4 h-4"})}],Gc=({review:t})=>{const{t:s}=Ae();return t.activeRound===0?null:e.jsxs("div",{className:"mt-5 border border-purple-200 rounded-xl bg-purple-50/50 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Mt,{className:"w-5 h-5 text-purple-600"}),e.jsx("h3",{className:"text-sm font-semibold text-purple-800",children:s("bootstrap.reviewPipeline")})]}),e.jsx("div",{className:"space-y-2.5",children:Bc.map(({key:a,labelKey:r,descKey:o,icon:l})=>{const i=t[a],p=i.status==="running",d=i.status==="completed",g=i.status==="idle";return e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg border transition-all duration-300 ${p?"border-purple-300 bg-purple-100/60":d?"border-emerald-300 bg-emerald-50/60":"border-[var(--border-default)] bg-[var(--bg-surface)]"}`,children:[e.jsx("div",{className:`flex-shrink-0 p-1.5 rounded-md ${p?"bg-purple-200 text-purple-700":d?"bg-emerald-100 text-emerald-600":"bg-[var(--bg-subtle)] text-[var(--fg-muted)]"}`,children:l}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-sm font-medium ${g?"text-[var(--fg-muted)]":"text-[var(--fg-primary)]"}`,children:s(r)}),e.jsx("span",{className:"text-xs text-[var(--fg-muted)]",children:s(o)})]}),a==="round1"&&d&&e.jsx("p",{className:"text-xs text-emerald-600 mt-0.5",children:s("bootstrap.round1Done",{kept:t.round1.kept??"?",merged:t.round1.merged??0,dropped:t.round1.dropped??0})}),a==="round2"&&p&&typeof t.round2.progress=="number"&&e.jsxs("div",{className:"mt-1.5",children:[e.jsx("div",{className:"w-full h-1.5 bg-purple-200 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-purple-500 rounded-full transition-all duration-300",style:{width:`${t.round2.progress}%`}})}),e.jsx("p",{className:"text-xs text-purple-600 mt-0.5",children:s("bootstrap.round2Progress",{current:t.round2.current??0,total:t.round2.total??"?"})})]}),a==="round2"&&d&&e.jsx("p",{className:"text-xs text-emerald-600 mt-0.5",children:s("bootstrap.round2Done",{refined:t.round2.refined??"?",total:t.round2.total??"?"})}),a==="round3"&&d&&e.jsx("p",{className:"text-xs text-emerald-600 mt-0.5",children:s("bootstrap.round3Done",{afterDedup:t.round3.afterDedup??"?",relationsFound:t.round3.relationsFound??0})})]}),e.jsxs("div",{className:"flex-shrink-0",children:[p&&e.jsx(Ne,{className:"w-4 h-4 text-purple-500 animate-spin"}),d&&e.jsx(ot,{className:"w-4 h-4 text-emerald-500"})]})]},a)})})]})};function Ka(t){if(t<0)return"--";const s=Math.floor(t/1e3),a=Math.floor(s/60),r=s%60;return a===0?`${r}s`:`${a}m ${r.toString().padStart(2,"0")}s`}const $c=({session:t,isAllDone:s,reviewState:a,onDismiss:r,onCancel:o,isCancelling:l=!1})=>{const{t:i}=Ae(),[p,d]=n.useState(Date.now());if(n.useEffect(()=>{if(!t||t.status!=="running")return;const S=setInterval(()=>d(Date.now()),1e3);return()=>clearInterval(S)},[t?.status]),!t)return null;const g=t.startedAt?p-t.startedAt:t.elapsedMs??0,x=t.completed+t.failed,h=t.total-x,u=t.elapsedMs??0,m=x>0&&u>0?Math.round(u/x*h):-1,c=t.totalToolCalls??0,j=t.status==="completed"?i("bootstrap.allCompleted"):t.status==="completed_with_errors"?i("bootstrap.completedWithErrors"):null;return e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-[var(--border-default)] shadow-sm p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-5",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold text-[var(--fg-primary)]",children:i("bootstrap.title")}),j&&e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] mt-0.5",children:j})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[t.status==="running"&&o&&e.jsxs("button",{onClick:o,disabled:l,className:"flex items-center gap-1.5 text-sm px-3 py-1.5 rounded-lg border border-red-200 bg-red-50 hover:bg-red-100 text-red-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[l?e.jsx(Ne,{size:14,className:"animate-spin"}):e.jsx(fl,{size:14}),i("bootstrap.cancel")]}),s&&r&&e.jsx("button",{onClick:r,className:"text-sm px-3 py-1.5 rounded-lg bg-[var(--bg-subtle)] hover:bg-[var(--bg-subtle)] text-[var(--fg-secondary)] transition-colors",children:i("bootstrap.close")})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-5 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[var(--fg-secondary)]",children:[e.jsx(Ye,{size:14,className:"text-[var(--fg-muted)]"}),e.jsxs("span",{children:[i("bootstrap.elapsed")," ",e.jsx("span",{className:"font-medium text-[var(--fg-primary)]",children:Ka(g)})]})]}),t.status==="running"&&h>0&&m>0&&e.jsxs("div",{className:"flex items-center gap-1.5 text-[var(--fg-secondary)]",children:[e.jsx(Ye,{size:14,className:"text-blue-400"}),e.jsxs("span",{children:[i("bootstrap.estimatedRemaining")," ",e.jsx("span",{className:"font-medium text-blue-600",children:Ka(m)})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-[var(--fg-secondary)]",children:[e.jsx(Ks,{size:14,className:"text-[var(--fg-muted)]"}),e.jsxs("span",{children:[i("bootstrap.toolCalls")," ",e.jsx("span",{className:"font-medium text-[var(--fg-primary)]",children:c})]})]}),e.jsx("div",{className:"text-[var(--fg-muted)] text-xs",children:i("bootstrap.dimensions",{done:x,total:t.total})})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3",children:[...t.tasks].sort((S,D)=>{const I=Ha.indexOf(S.meta?.dimId??S.id),P=Ha.indexOf(D.meta?.dimId??D.id);return(I===-1?999:I)-(P===-1?999:P)}).map(S=>e.jsx(zc,{task:S},S.id))}),a&&a.activeRound>0&&e.jsx(Gc,{review:a})]})},cs={index:{icon:Ue,color:"text-blue-600",label:"overview"},architecture:{icon:Ge,color:"text-violet-600",label:"architecture"},"getting-started":{icon:pt,color:"text-emerald-600",label:"getting-started"},protocols:{icon:Le,color:"text-amber-600",label:"protocols"},components:{icon:pt,color:"text-emerald-600",label:"components"},patterns:{icon:Le,color:"text-amber-600",label:"patterns"},module:{icon:Lt,color:"text-cyan-600",label:"module"},document:{icon:Qe,color:"text-orange-600",label:"document"},_index:{icon:Ys,color:"text-[var(--fg-secondary)]",label:"index"}};function Oc(t){const s=t.split("/").pop()?.replace(".md","")||"";return s==="_index"?cs._index:t.startsWith("modules/")?cs.module:t.startsWith("documents/")?cs.document:cs[s]||{icon:Qe,color:"text-[var(--fg-secondary)]",label:"doc"}}const Hc={"cursor-devdocs":{label:"Cursor Docs",color:"text-orange-700",bg:"bg-orange-50 border-orange-200"}},Kc={modules:"modules",documents:"documents"};function tn(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`}function qc(t){if(!t)return"";const s=new Date(t);if(isNaN(s.getTime()))return"";const r=Date.now()-s.getTime();return r<6e4?"just now":r<36e5?`${Math.floor(r/6e4)} min ago`:r<864e5?`${Math.floor(r/36e5)} hr ago`:r<6048e5?`${Math.floor(r/864e5)} d ago`:s.toLocaleDateString("zh-CN")}const Uc=({task:t,wiki:s})=>{const{t:a}=Ae();return t.status==="running"?null:t.status==="error"?e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-xl p-4 mb-6 flex items-center gap-3",children:[e.jsx("div",{className:"p-1.5 bg-red-100 rounded-lg",children:e.jsx(Et,{size:H.md,className:"text-red-600"})}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-red-800",children:a("wiki.genFailed")}),e.jsx("span",{className:"text-sm text-red-600 ml-3",children:t.error||a("common.operationFailed")})]})]}):s?.exists&&s.hasChanges?e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-xl p-4 mb-6 flex items-center gap-3",children:[e.jsx("div",{className:"p-1.5 bg-amber-100 rounded-lg",children:e.jsx(Et,{size:H.md,className:"text-amber-600"})}),e.jsx("span",{className:"text-sm text-amber-700",children:a("wiki.outOfDateHint")})]}):null};function Wc(t,s){const a=[],r=new Map(s?.map(g=>[g.path,g])||[]),o=[],l=new Map;for(const g of t){const x=g.path.split("/"),h=r.get(g.path);if(x.length===1)o.push({name:x[0],path:g.path,isDir:!1,file:g,metaInfo:h});else{const u=x[0];l.has(u)||l.set(u,[]),l.get(u).push({name:x.slice(1).join("/"),path:g.path,isDir:!1,file:g,metaInfo:h})}}const i=["index.md","architecture.md","getting-started.md","patterns.md","protocols.md","components.md"];o.sort((g,x)=>{const h=i.indexOf(g.name),u=i.indexOf(x.name);return h!==-1&&u!==-1?h-u:h!==-1?-1:u!==-1?1:g.name.localeCompare(x.name)}),a.push(...o);const p=["modules","patterns","documents"],d=[...l.entries()].sort(([g],[x])=>{const h=p.indexOf(g),u=p.indexOf(x);return h!==-1&&u!==-1?h-u:h!==-1?-1:u!==-1?1:g.localeCompare(x)});for(const[g,x]of d){const h=x.filter(u=>!u.name.startsWith("_index")).sort((u,m)=>u.name.localeCompare(m.name));a.push({name:g,path:g,isDir:!0,children:h})}return a}const Vc=({tree:t,selectedFile:s,onSelect:a,searchQuery:r})=>{const[o,l]=n.useState(new Set(["modules","documents"])),i=g=>{l(x=>{const h=new Set(x);return h.has(g)?h.delete(g):h.add(g),h})},d=(g=>{if(!r)return g;const x=r.toLowerCase();return g.filter(h=>h.isDir?h.children?.some(u=>u.name.toLowerCase().includes(x)||u.path.toLowerCase().includes(x)):h.name.toLowerCase().includes(x)||h.path.toLowerCase().includes(x))})(t);return e.jsx("div",{className:"space-y-0.5",children:d.map(g=>{if(g.isDir){const x=o.has(g.path),h=r.toLowerCase(),u=r?g.children?.filter(m=>m.name.toLowerCase().includes(h)||m.path.toLowerCase().includes(h)):g.children;return e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>i(g.path),className:"w-full flex items-center gap-2 px-3 py-2 text-sm text-[var(--fg-secondary)] hover:bg-[var(--bg-subtle)] rounded-lg transition-colors",children:[x?e.jsx(gt,{size:14,className:"text-[var(--fg-muted)] flex-shrink-0"}):e.jsx(Ke,{size:14,className:"text-[var(--fg-muted)] flex-shrink-0"}),e.jsx(Lt,{size:14,className:"text-amber-500 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:Kc[g.name]||g.name}),e.jsx("span",{className:"ml-auto text-xs text-[var(--fg-muted)]",children:u?.length||0})]}),x&&u&&e.jsx("div",{className:"ml-3",children:u.map(m=>e.jsx(qa,{node:m,isActive:s===m.path,onSelect:a},m.path))})]},g.path)}return e.jsx(qa,{node:g,isActive:s===g.path,onSelect:a},g.path)})})},qa=({node:t,isActive:s,onSelect:a})=>{const r=Oc(t.path),o=r.icon,l=t.metaInfo?.polished,i=t.metaInfo?.source;return e.jsxs("button",{onClick:()=>a(t.path),className:`w-full flex items-center gap-2 px-3 py-2 text-sm rounded-lg transition-all ${s?"bg-blue-50 text-blue-700 border border-blue-200 shadow-sm":"text-[var(--fg-secondary)] hover:bg-[var(--bg-subtle)]"}`,children:[e.jsx(o,{size:14,className:`flex-shrink-0 ${s?"text-blue-500":r.color}`}),e.jsx("span",{className:"truncate text-left",children:t.name.replace(".md","")}),e.jsxs("span",{className:"ml-auto flex items-center gap-1 flex-shrink-0",children:[l&&e.jsx("span",{title:"AI Enhanced",children:e.jsx(Le,{size:10,className:"text-violet-400"})}),i&&e.jsx("span",{title:`Source: ${i}`,children:e.jsx(jl,{size:10,className:"text-orange-400"})})]})]})},Jc=({filePath:t,content:s,loading:a,meta:r,onBack:o})=>{const{t:l}=Ae(),[i,p]=n.useState(!1),d=r?.files?.find(u=>u.path===t),g=()=>{navigator.clipboard.writeText(s).catch(()=>{}),p(!0),setTimeout(()=>p(!1),2e3)},x=t.split("/"),h=x.map((u,m)=>({label:m===x.length-1?u.replace(".md",""):u,isLast:m===x.length-1}));return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 bg-[var(--bg-subtle)] border-b border-[var(--border-default)] flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:o,className:"p-1.5 hover:bg-[var(--bg-subtle)] rounded-lg transition-colors lg:hidden",title:l("wiki.backToList"),children:e.jsx(yl,{size:H.md})}),e.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[e.jsx(Ue,{size:14,className:"text-[var(--fg-muted)]"}),e.jsx("span",{className:"text-[var(--fg-muted)]",children:"wiki"}),h.map((u,m)=>e.jsxs(it.Fragment,{children:[e.jsx(Ke,{size:12,className:"text-[var(--fg-muted)]"}),e.jsx("span",{className:u.isLast?"font-medium text-[var(--fg-primary)]":"text-[var(--fg-muted)]",children:u.label})]},m))]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[d?.polished&&e.jsxs("span",{className:"flex items-center gap-1 text-xs text-violet-700 bg-violet-50 border border-violet-200 px-2 py-0.5 rounded-full",children:[e.jsx(Le,{size:10}),l("wiki.aiBadge")]}),d?.source&&(()=>{const u=Hc[d.source];return e.jsx("span",{className:`flex items-center gap-1 text-xs border px-2 py-0.5 rounded-full ${u?.bg||"bg-[var(--bg-subtle)] border-[var(--border-default)]"} ${u?.color||"text-[var(--fg-secondary)]"}`,children:u?.label||d.source})})(),e.jsxs("button",{onClick:g,className:"flex items-center gap-1 px-2.5 py-1 text-xs text-[var(--fg-secondary)] hover:text-[var(--fg-primary)] hover:bg-[var(--bg-subtle)] rounded-md transition-colors",children:[i?e.jsx(ot,{size:12,className:"text-emerald-500"}):e.jsx(Ir,{size:12}),l(i?"wiki.copySuccess":"wiki.copyBtn")]})]})]}),e.jsx("div",{className:"flex-1 overflow-auto scrollbar-light",style:{scrollbarGutter:"stable"},children:a?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx(Ne,{size:H.xl,className:"text-blue-500 animate-spin"})}):e.jsx("div",{className:"px-4 xl:px-6 2xl:px-8 py-6 max-w-4xl mx-auto",children:e.jsx(Qt,{content:s,className:"wiki-reader"})})})]})},Yc=()=>{const{t}=Ae();return e.jsxs("div",{className:"h-72 flex flex-col items-center justify-center bg-[var(--bg-surface)] rounded-2xl border border-dashed border-[var(--border-default)] text-[var(--fg-muted)]",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-[var(--bg-subtle)] flex items-center justify-center mb-4",children:e.jsx(Ue,{size:32,className:"text-[var(--fg-muted)]"})}),e.jsx("p",{className:"text-sm font-medium text-[var(--fg-secondary)]",children:t("wiki.emptyTitle")}),e.jsx("p",{className:"mt-2 text-xs max-w-sm text-center leading-relaxed text-[var(--fg-muted)]",children:t("wiki.emptyDesc")}),e.jsx("p",{className:"mt-3 text-[11px] text-[var(--fg-muted)]",children:t("wiki.emptyHint")})]})},Qc=({meta:t,onSelectFile:s,isGenerating:a,progress:r,message:o})=>{const{t:l}=Ae(),i=[{path:"index.md",label:l("wiki.quickOverview"),desc:l("wiki.quickOverviewDesc"),icon:Ue,color:"bg-blue-50 text-blue-600 border-blue-200"},{path:"architecture.md",label:l("wiki.quickArch"),desc:l("wiki.quickArchDesc"),icon:Ge,color:"bg-violet-50 text-violet-600 border-violet-200"},{path:"getting-started.md",label:l("wiki.quickStart"),desc:l("wiki.quickStartDesc"),icon:pt,color:"bg-emerald-50 text-emerald-600 border-emerald-200"},{path:"protocols.md",label:l("wiki.quickProtocols"),desc:l("wiki.quickProtocolsDesc"),icon:Le,color:"bg-amber-50 text-amber-600 border-amber-200"}],p=new Set(t?.files?.map(g=>g.path||g.name)??[]),d=i.filter(g=>p.size===0||p.has(g.path));return e.jsxs("div",{className:"p-4 xl:p-6 2xl:p-8 overflow-y-auto flex-1",children:[a&&e.jsxs("div",{className:"mb-8 flex flex-col items-center",children:[e.jsxs("div",{className:"relative w-20 h-20 mb-5",children:[e.jsx("span",{className:"absolute inset-0 rounded-full bg-blue-100 animate-ping opacity-20"}),e.jsx("span",{className:"absolute inset-2 rounded-full bg-blue-50 animate-pulse"}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx(aa,{size:36,className:"text-blue-500 animate-pulse"})})]}),e.jsx("h3",{className:"text-lg font-semibold text-[var(--fg-primary)] mb-1",children:l("wiki.wikiGenerating")}),e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] max-w-md text-center leading-relaxed",children:o||l("wiki.generating")}),typeof r=="number"&&e.jsxs("div",{className:"mt-4 w-48",children:[e.jsx("div",{className:"w-full bg-[var(--bg-subtle)] rounded-full h-2",children:e.jsx("div",{className:"bg-gradient-to-r from-blue-500 to-indigo-500 h-2 rounded-full transition-all duration-700 ease-out",style:{width:`${Math.max(r,3)}%`}})}),e.jsxs("p",{className:"text-xs text-center text-blue-500 mt-1.5 font-mono",children:[r,"%"]})]})]}),!a&&e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"w-12 h-12 bg-[var(--bg-subtle)] rounded-xl flex items-center justify-center mx-auto mb-3",children:e.jsx(Qe,{size:24,className:"text-[var(--fg-muted)]"})}),e.jsx("h3",{className:"text-lg font-semibold text-[var(--fg-primary)]",children:l("wiki.selectFile")}),e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] mt-1",children:l("wiki.selectPlaceholder")})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 max-w-lg mx-auto",children:d.map(g=>{const x=g.icon;return e.jsxs("button",{onClick:()=>s(g.path),className:`text-left p-4 rounded-xl border ${g.color} hover:shadow-sm transition-all group`,children:[e.jsx(x,{size:20,className:"mb-2 opacity-70 group-hover:opacity-100"}),e.jsx("div",{className:"font-medium text-sm",children:g.label}),e.jsx("div",{className:"text-xs opacity-60 mt-0.5",children:g.desc})]},g.path)})}),t&&e.jsxs("div",{className:"mt-8 text-center text-xs text-[var(--fg-muted)]",children:[t.generatedAt&&`${l("wiki.lastGenerated")}: ${new Date(t.generatedAt).toLocaleString()}`,t.duration!=null&&` · ${l("wiki.duration")} ${tn(t.duration)}`,t.version&&` · v${t.version}`]})]})},Zc=()=>{const{t}=Ae(),[s,a]=n.useState({task:{status:"idle"}}),[r,o]=n.useState([]),[l,i]=n.useState(!1),[p,d]=n.useState(null),[g,x]=n.useState(""),[h,u]=n.useState(!1),[m,c]=n.useState(!0),[j,S]=n.useState(""),[D,I]=n.useState(null),P=n.useRef(null),Y=n.useCallback(async()=>{try{const q=await Z.wikiStatus();return a(q),q}catch{return null}},[]),w=n.useCallback(async()=>{try{const q=await Z.wikiFiles();o(q.files||[]),i(q.exists)}catch{}},[]),G=n.useCallback(async()=>{try{const q=await Z.wikiFileContent("meta.json");q?.content&&I(JSON.parse(q.content))}catch{}},[]);n.useEffect(()=>{(async()=>(c(!0),await Promise.all([Y(),w(),G()]),c(!1)))()},[Y,w,G]),n.useEffect(()=>{if(s.task.status==="running"){let q=0;P.current=setInterval(async()=>{const A=await Y();q++,q%3===0&&await w(),A&&A.task.status!=="running"&&(await Promise.all([w(),G()]),P.current&&clearInterval(P.current))},1500)}else P.current&&clearInterval(P.current);return()=>{P.current&&clearInterval(P.current)}},[s.task.status,Y,w,G]);const _=async()=>{try{await Z.wikiUpdate(),a(q=>({...q,task:{...q.task,status:"running",progress:0,message:t("wiki.incrementalUpdating")}}))}catch(q){console.error("Wiki update failed:",q)}},N=async q=>{if(q!=="meta.json"){d(q),u(!0);try{const A=await Z.wikiFileContent(q);x(A.content)}catch{x(`# ${t("wiki.loadFailed")}

${t("wiki.loadFailedDesc")}`)}finally{u(!1)}}},E=()=>{d(null),x("")},L=n.useMemo(()=>r.filter(q=>q.path!=="meta.json"),[r]),$=n.useMemo(()=>Wc(L,D?.files),[L,D]);if(m)return e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx(Ne,{size:H.xl,className:"text-blue-500 animate-spin"})});const U=!l&&L.length===0&&s.task.status!=="running";return e.jsxs("div",{className:"h-full flex flex-col overflow-hidden p-6 pt-4",children:[e.jsx(Uc,{task:s.task,wiki:s.wiki}),U?e.jsx(Yc,{}):e.jsxs(e.Fragment,{children:[s.task.status==="running"&&e.jsxs("div",{className:"mb-3 flex items-center gap-3 px-4 py-2.5 bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200/70 rounded-xl shrink-0",children:[e.jsxs("div",{className:"relative flex items-center justify-center w-6 h-6",children:[e.jsx("span",{className:"absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-30 animate-ping"}),e.jsx(Ne,{size:16,className:"text-blue-600 animate-spin relative"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium text-blue-800",children:t("wiki.wikiGenerating")}),s.task.message&&e.jsx("span",{className:"text-xs text-blue-500 ml-2 truncate",children:s.task.message})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("div",{className:"w-24 bg-blue-100 rounded-full h-1.5",children:e.jsx("div",{className:"bg-blue-500 h-1.5 rounded-full transition-all duration-700 ease-out",style:{width:`${Math.max(s.task.progress||0,3)}%`}})}),e.jsxs("span",{className:"text-xs font-mono text-blue-600 w-8 text-right",children:[s.task.progress||0,"%"]})]})]}),e.jsxs("div",{className:"flex gap-4 flex-1 min-h-0 overflow-hidden",children:[e.jsxs("div",{className:`w-64 flex-shrink-0 bg-[var(--bg-surface)] border border-[var(--border-default)] rounded-xl flex flex-col overflow-hidden ${p?"hidden lg:flex":""}`,children:[e.jsxs("div",{className:"px-3 pt-3 pb-2 border-b border-[var(--border-default)] shrink-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ue,{size:16,className:"text-blue-500"}),e.jsx("span",{className:"text-sm font-semibold text-[var(--fg-primary)]",children:"Wiki"}),D?.version&&e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)]",children:["v",D.version]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[l&&e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)]",children:t("wiki.fileCount",{count:L.length})}),s.task.status!=="running"&&l&&e.jsx("button",{onClick:_,title:t("wiki.incrementalUpdate"),className:"p-1 rounded-md text-blue-500 hover:bg-blue-50 transition-colors",children:e.jsx(at,{size:13})})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(xt,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-[var(--fg-muted)]"}),e.jsx("input",{type:"text",placeholder:t("wiki.searchPlaceholder"),value:j,onChange:q=>S(q.target.value),className:"w-full pl-8 pr-3 py-2 text-sm bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-200 focus:border-blue-300 transition-all"})]})]}),e.jsxs("div",{className:"p-2 overflow-y-auto flex-1 min-h-0 scrollbar-light",children:[e.jsx(Vc,{tree:$,selectedFile:p,onSelect:N,searchQuery:j}),s.task.status==="running"&&e.jsxs("div",{className:"mx-2 mt-3 mb-1 flex items-center gap-2 px-3 py-2 bg-blue-50 border border-blue-100 rounded-lg",children:[e.jsx(Ne,{size:12,className:"text-blue-500 animate-spin flex-shrink-0"}),e.jsx("span",{className:"text-[11px] text-blue-600 leading-tight",children:t("wiki.generating")})]})]}),D?.generatedAt&&e.jsx("div",{className:"px-3 py-2 border-t border-[var(--border-default)] shrink-0",children:e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] text-[var(--fg-muted)]",children:[e.jsx(Ye,{size:10}),e.jsx("span",{children:qc(D.generatedAt)}),D.duration!=null&&e.jsxs("span",{children:["· ",tn(D.duration)]})]})})]}),e.jsx("div",{className:`flex-1 bg-[var(--bg-surface)] border border-[var(--border-default)] rounded-xl overflow-hidden flex flex-col min-h-0 ${p?"":"hidden lg:flex"}`,children:p?e.jsx(Jc,{filePath:p,content:g,loading:h,meta:D,onBack:E}):e.jsx(Qc,{meta:D,onSelectFile:N,isGenerating:s.task.status==="running",progress:s.task.progress,message:s.task.message})})]})]})]})},Xc={guard:"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300",search:"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300",forge:"bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-300",usage:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300",lifecycle:"bg-cyan-100 text-cyan-700 dark:bg-cyan-900/30 dark:text-cyan-300",quality:"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300",decay:"bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-300",context:"bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-300",anomaly:"bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-300",intent:"bg-violet-100 text-violet-700 dark:bg-violet-900/30 dark:text-violet-300",exploration:"bg-teal-100 text-teal-700 dark:bg-teal-900/30 dark:text-teal-300",panorama:"bg-sky-100 text-sky-700 dark:bg-sky-900/30 dark:text-sky-300"},ed={governance:"bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300",compliance:"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300",metrics:"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300",analysis:"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300"},td=["time1h","time6h","time24h","time7d","timeAll"],sd=[36e5,216e5,864e5,6048e5,0];function sn(t){const s=new Date(t),a=r=>String(r).padStart(2,"0");return`${a(s.getMonth()+1)}-${a(s.getDate())} ${a(s.getHours())}:${a(s.getMinutes())}:${a(s.getSeconds())}`}function an(t,s){return s[t]??"bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-300"}function ad({signal:t}){const[s,a]=n.useState(!1);return e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-3 hover:bg-[var(--bg-muted)]/40 transition-colors cursor-pointer",onClick:()=>{a(!s)},children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:`px-1.5 py-0.5 rounded text-xs font-medium ${an(t.type,Xc)}`,children:t.type}),e.jsx("span",{className:"text-[var(--fg-default)] font-medium truncate",children:t.source}),t.target&&e.jsxs("span",{className:"text-[var(--fg-subtle)] truncate",children:["→ ",t.target]}),e.jsxs("span",{className:"ml-auto shrink-0 tabular-nums text-xs text-[var(--fg-subtle)]",children:[(t.value*100).toFixed(0),"%"]}),e.jsx("span",{className:"shrink-0 text-xs text-[var(--fg-subtle)] tabular-nums",children:sn(t.timestamp)})]}),s&&t.metadata&&(typeof t.metadata=="object"&&!Array.isArray(t.metadata)?e.jsx("div",{className:"mt-2 grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs bg-[var(--bg-muted)] rounded p-2.5",children:Object.entries(t.metadata).map(([r,o])=>e.jsxs(it.Fragment,{children:[e.jsx("span",{className:"text-[var(--fg-secondary)] font-medium",children:r}),e.jsx("span",{className:"text-[var(--fg-default)] tabular-nums",children:typeof o=="object"?JSON.stringify(o):String(o)})]},r))}):e.jsx("pre",{className:"mt-2 text-xs text-[var(--fg-secondary)] bg-[var(--bg-muted)] rounded p-2.5 overflow-x-auto whitespace-pre-wrap",children:JSON.stringify(t.metadata,null,2)}))]})}function rd({report:t}){const[s,a]=n.useState(!1);return e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-3 hover:bg-[var(--bg-muted)]/40 transition-colors cursor-pointer",onClick:()=>{a(!s)},children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:`px-1.5 py-0.5 rounded text-xs font-medium ${an(t.category,ed)}`,children:t.category}),e.jsx("span",{className:"text-[var(--fg-default)] font-medium truncate",children:t.type}),e.jsx("span",{className:"text-[var(--fg-subtle)] text-xs truncate",children:t.producer}),t.duration_ms!=null&&e.jsxs("span",{className:"text-xs text-[var(--fg-subtle)]",children:[t.duration_ms,"ms"]}),e.jsx("span",{className:"ml-auto shrink-0 text-xs text-[var(--fg-subtle)] tabular-nums",children:sn(t.timestamp)})]}),s&&(typeof t.data=="object"&&t.data&&!Array.isArray(t.data)?e.jsx("div",{className:"mt-2 grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs bg-[var(--bg-muted)] rounded p-2.5",children:Object.entries(t.data).map(([r,o])=>e.jsxs(it.Fragment,{children:[e.jsx("span",{className:"text-[var(--fg-secondary)] font-medium",children:r}),e.jsx("span",{className:"text-[var(--fg-default)] tabular-nums",children:typeof o=="object"?JSON.stringify(o):String(o)})]},r))}):e.jsx("pre",{className:"mt-2 text-xs text-[var(--fg-secondary)] bg-[var(--bg-muted)] rounded p-2.5 overflow-x-auto whitespace-pre-wrap",children:JSON.stringify(t.data,null,2)}))]})}function Ua({label:t,value:s,max:a}){const r=a>0?Math.round(s/a*100):0;return e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"w-24 truncate text-[var(--fg-subtle)]",children:t}),e.jsx("div",{className:"flex-1 h-2 rounded-full bg-[var(--bg-muted)] overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-[var(--accent)] transition-all duration-300",style:{width:`${r}%`}})}),e.jsx("span",{className:"w-12 text-right text-xs tabular-nums text-[var(--fg-subtle)]",children:s})]})}const nd=()=>{const{t}=Ae(),[s,a]=n.useState("signals"),[r,o]=n.useState(2),[l,i]=n.useState(""),[p,d]=n.useState(!1),[g,x]=n.useState(null),[h,u]=n.useState([]),[m,c]=n.useState(0),[j,S]=n.useState([]),[D,I]=n.useState(0),[P,Y]=n.useState(null),w=n.useMemo(()=>{const N=sd[r];return N===0?{}:{from:Date.now()-N}},[r]),G=n.useCallback(async()=>{d(!0),x(null);try{if(s==="signals"){const N=l?l.split(",").map(L=>L.trim()).filter(Boolean):void 0,E=await Z.getSignalTrace({...w,type:N,limit:100});u(E.signals),c(E.total)}else if(s==="reports"){const N=await Z.getReports({...w,limit:50});S(N.reports),I(N.total)}else{const N=await Z.getSignalStats(w);Y(N)}}catch(N){x(ke(N))}finally{d(!1)}},[s,w,l]);n.useEffect(()=>{G()},[G]);const _=n.useMemo(()=>{if(!P)return 1;const N=Object.values(P.byType);return Math.max(...N,1)},[P]);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yt,{size:20,className:"text-[var(--accent)]"}),e.jsx("h2",{className:"text-lg font-semibold text-[var(--fg-default)]",children:t("signals.title")})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s==="signals"&&e.jsxs("div",{className:"relative",children:[e.jsx(sa,{size:13,className:"absolute left-2 top-1/2 -translate-y-1/2 text-[var(--fg-subtle)]"}),e.jsx("input",{type:"text",placeholder:t("signals.filterPlaceholder"),value:l,onChange:N=>{i(N.target.value)},className:"pl-7 pr-2 py-1.5 text-xs rounded-lg border border-[var(--border-default)] bg-[var(--bg-surface)] text-[var(--fg-default)] w-40"})]}),e.jsx("div",{className:"flex items-center gap-1",children:[["signals",e.jsx(Be,{size:13},"s"),t("signals.tabSignals")],["reports",e.jsx(Qe,{size:13},"r"),t("signals.tabReports")],["stats",e.jsx(Tt,{size:13},"st"),t("signals.tabStats")]].map(([N,E,L])=>e.jsxs("button",{type:"button",onClick:()=>{a(N)},className:`flex items-center gap-1 px-4 py-1.5 rounded-md text-xs font-medium transition-colors ${s===N?"bg-[var(--accent-subtle)] text-[var(--accent)] border border-[var(--accent-emphasis)]":"text-[var(--fg-muted)] hover:bg-[var(--bg-subtle)] border border-transparent"}`,children:[E,L]},N))}),e.jsx("div",{className:"flex items-center gap-1",children:td.map((N,E)=>e.jsx("button",{type:"button",onClick:()=>{o(E)},className:`px-4 py-1.5 rounded-md text-xs font-medium transition-colors ${r===E?"bg-[var(--accent-subtle)] text-[var(--accent)] border border-[var(--accent-emphasis)]":"text-[var(--fg-muted)] hover:bg-[var(--bg-subtle)] border border-transparent"}`,children:t(`signals.${N}`)},N))}),e.jsxs("button",{type:"button",onClick:G,disabled:p,className:"flex items-center gap-1 px-2.5 py-1.5 text-xs rounded-lg border border-[var(--border-default)] text-[var(--fg-subtle)] hover:bg-[var(--bg-muted)] transition-colors disabled:opacity-50",children:[p?e.jsx(Ne,{size:13,className:"animate-spin"}):e.jsx(at,{size:13}),t("signals.refresh")]})]})]}),g&&e.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm rounded-lg bg-red-50 text-red-700 dark:bg-red-900/20 dark:text-red-300",children:[e.jsx(st,{size:16}),g]}),p&&!h.length&&!j.length&&!P?e.jsxs("div",{className:"flex items-center justify-center py-20 text-[var(--fg-subtle)]",children:[e.jsx(Ne,{size:24,className:"animate-spin mr-2"}),t("signals.loading")]}):s==="signals"?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs text-[var(--fg-subtle)]",children:t("signals.showingSignals",{shown:h.length,total:m})}),h.length===0?e.jsxs("div",{className:"text-center py-12 text-[var(--fg-subtle)]",children:[e.jsx(js,{size:32,className:"mx-auto mb-2 opacity-40"}),e.jsx("p",{children:t("signals.noSignals")})]}):e.jsx("div",{className:"space-y-1.5",children:h.map((N,E)=>e.jsx(ad,{signal:N},`${N.timestamp}-${E}`))})]}):s==="reports"?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs text-[var(--fg-subtle)]",children:t("signals.showingReports",{shown:j.length,total:D})}),j.length===0?e.jsxs("div",{className:"text-center py-12 text-[var(--fg-subtle)]",children:[e.jsx(Qe,{size:32,className:"mx-auto mb-2 opacity-40"}),e.jsx("p",{children:t("signals.noReports")})]}):e.jsx("div",{className:"space-y-1.5",children:j.map(N=>e.jsx(rd,{report:N},N.id))})]}):e.jsx("div",{className:"space-y-6",children:P?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-4",children:[e.jsx("div",{className:"text-xs text-[var(--fg-subtle)] mb-1",children:t("signals.totalSignals")}),e.jsx("div",{className:"text-2xl font-bold text-[var(--fg-default)] tabular-nums",children:P.total})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-4",children:[e.jsx("div",{className:"text-xs text-[var(--fg-subtle)] mb-1",children:t("signals.signalTypes")}),e.jsx("div",{className:"text-2xl font-bold text-[var(--fg-default)] tabular-nums",children:Object.keys(P.byType).length})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-4",children:[e.jsx("div",{className:"text-xs text-[var(--fg-subtle)] mb-1",children:t("signals.sources")}),e.jsx("div",{className:"text-2xl font-bold text-[var(--fg-default)] tabular-nums",children:Object.keys(P.bySource).length})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-4",children:[e.jsx("h3",{className:"text-sm font-medium text-[var(--fg-default)] mb-3",children:t("signals.byType")}),e.jsx("div",{className:"space-y-2",children:Object.entries(P.byType).sort((N,E)=>E[1]-N[1]).map(([N,E])=>e.jsx(Ua,{label:N,value:E,max:_},N))})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-4",children:[e.jsx("h3",{className:"text-sm font-medium text-[var(--fg-default)] mb-3",children:t("signals.bySource")}),e.jsx("div",{className:"space-y-2",children:Object.entries(P.bySource).sort((N,E)=>E[1]-N[1]).slice(0,15).map(([N,E])=>e.jsx(Ua,{label:N,value:E,max:_},N))})]})]}):e.jsxs("div",{className:"text-center py-12 text-[var(--fg-subtle)]",children:[e.jsx(Tt,{size:32,className:"mx-auto mb-2 opacity-40"}),e.jsx("p",{children:t("signals.noStats")})]})})]})},ld={authority:0,guardUsageCount:0,humanUsageCount:0,aiUsageCount:0,lastUsedAt:null,authorityScore:0},od=({editingRecipe:t,setEditingRecipe:s,handleSaveRecipe:a,closeRecipeEdit:r,isSavingRecipe:o=!1})=>{const{t:l}=Ae(),[i,p]=n.useState("preview"),d=n.useRef(!0);n.useEffect(()=>()=>{d.current=!1},[]);const g=(()=>{const u=(t.language||"").toLowerCase();return["objectivec","objc","objective-c","obj-c"].includes(u)?"objectivec":t.language||"text"})(),x=async u=>{try{if(await Z.setRecipeAuthority(t.name,u),d.current){const m=t.stats?{...t.stats,authority:u}:{...ld,authority:u};s({...t,stats:m})}}catch(m){console.warn(l("recipeEditor.authorityFailed"),ke(m))}},h=u=>{if(!u)return"";const m=typeof u=="string"?new Date(u).getTime():u;return isNaN(m)?"":new Date(m).toLocaleString("zh-CN",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"})};return e.jsxs($e,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx($e.Backdrop,{className:"bg-black/20 dark:bg-black/40 backdrop-blur-sm"}),e.jsxs("div",{className:"relative bg-[var(--bg-surface)] w-full max-w-6xl rounded-2xl shadow-2xl flex flex-col h-[85vh]",children:[e.jsxs("div",{className:"p-6 border-b border-[var(--border-default)] flex justify-between items-center flex-wrap gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h2",{className:"text-xl font-bold",children:l("recipeEditor.title")}),t.kind&&(()=>{const m={rule:{label:"Rule",color:"text-red-700",bg:"bg-red-50",border:"border-red-200",icon:Ve},pattern:{label:"Pattern",color:"text-violet-700",bg:"bg-violet-50",border:"border-violet-200",icon:St},fact:{label:"Fact",color:"text-cyan-700",bg:"bg-cyan-50",border:"border-cyan-200",icon:Ue}}[t.kind];if(!m)return null;const c=m.icon;return e.jsxs("span",{className:`text-[10px] font-bold px-2 py-1 rounded uppercase flex items-center gap-1 border ${m.bg} ${m.color} ${m.border}`,children:[e.jsx(c,{size:H.sm}),m.label]})})(),t.status&&t.status!=="active"&&t.status!=="published"&&e.jsx("span",{className:`text-[10px] font-bold px-2 py-1 rounded uppercase border ${t.status==="draft"?"bg-[var(--bg-subtle)] text-[var(--fg-muted)] border-[var(--border-default)]":t.status==="archived"?"bg-orange-50 text-orange-600 border-orange-200":"bg-[var(--bg-subtle)] text-[var(--fg-muted)] border-[var(--border-default)]"}`,children:t.status})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-medium text-[var(--fg-muted)]",children:l("recipeEditor.authorityScore")}),i==="preview"?e.jsx("span",{className:"text-sm text-[var(--fg-primary)]",children:t.stats?.authority??3}):e.jsx(tt,{value:String(t.stats?.authority??3),onChange:u=>x(parseInt(u)),options:[{value:"1",label:`1 - ${l("recipeEditor.qualityLevels.basic")}`,icon:"⭐"},{value:"2",label:`2 - ${l("recipeEditor.qualityLevels.good")}`,icon:"⭐⭐"},{value:"3",label:`3 - ${l("recipeEditor.qualityLevels.solid")}`,icon:"⭐⭐⭐"},{value:"4",label:`4 - ${l("recipeEditor.qualityLevels.great")}`,icon:"⭐⭐⭐⭐"},{value:"5",label:`5 - ${l("recipeEditor.qualityLevels.excellent")}`,icon:"⭐⭐⭐⭐⭐"}],size:"xs",className:"font-bold text-amber-600 bg-amber-50 border-amber-100"})]}),e.jsxs("div",{className:"flex bg-[var(--bg-subtle)] p-1 rounded-lg mr-4",children:[e.jsxs("button",{onClick:()=>p("preview"),className:`px-4 py-1.5 rounded-md text-xs font-bold transition-all flex items-center gap-2 ${i==="preview"?"bg-[var(--bg-surface)] shadow-sm text-[var(--accent)]":"text-[var(--fg-muted)]"}`,children:[e.jsx(Ut,{size:H.sm})," ",l("recipeEditor.preview")]}),e.jsxs("button",{onClick:()=>p("edit"),className:`px-4 py-1.5 rounded-md text-xs font-bold transition-all flex items-center gap-2 ${i==="edit"?"bg-[var(--bg-surface)] shadow-sm text-[var(--accent)]":"text-[var(--fg-muted)]"}`,children:[e.jsx(It,{size:H.sm})," ",l("recipeEditor.edit")]})]}),e.jsx("button",{onClick:r,className:"p-2 hover:bg-[var(--bg-subtle)] rounded-full",children:e.jsx(ze,{size:H.lg})})]})]}),e.jsx("div",{className:"p-6 space-y-4 flex-1 flex flex-col overflow-hidden",children:e.jsx("div",{className:"flex-1 flex flex-col min-h-0",children:i==="edit"?e.jsxs("div",{className:"flex-1 overflow-y-auto space-y-5 pr-1",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-[var(--fg-muted)] uppercase mb-1",children:l("recipeEditor.path")}),e.jsx("input",{className:"w-full p-2 bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-lg text-sm",value:t.name,onChange:u=>s({...t,name:u.target.value})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-[var(--fg-muted)] uppercase mb-1",children:l("recipeEditor.description")}),e.jsx("textarea",{className:"w-full px-3 py-2 text-sm border border-[var(--border-default)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)] resize-none",rows:2,value:t.description||"",onChange:u=>s({...t,description:u.target.value}),placeholder:l("recipeEditor.descPlaceholder")})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-bold text-[var(--fg-muted)] uppercase mb-1.5 flex items-center gap-1.5",children:[e.jsx(Qe,{size:11,className:"text-blue-400"})," ",l("recipeEditor.markdown")]}),e.jsx("div",{className:"border border-[var(--border-default)] rounded-lg overflow-hidden",style:{minHeight:180},children:e.jsx(ys,{value:t.content?.markdown||"",onChange:u=>s({...t,content:{...t.content,markdown:u}}),language:"markdown",height:"180px",showLineNumbers:!0})})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-bold text-[var(--fg-muted)] uppercase mb-1.5 flex items-center gap-1.5",children:[e.jsx(At,{size:11,className:"text-emerald-500"})," ",l("recipeEditor.code")]}),e.jsx("div",{className:"border border-[var(--border-default)] rounded-lg overflow-hidden",style:{minHeight:180},children:e.jsx(ys,{value:t.content?.pattern||"",onChange:u=>s({...t,content:{...t.content,pattern:u}}),language:g,height:"180px",showLineNumbers:!0})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-[var(--fg-muted)] uppercase mb-1",children:l("recipeEditor.rationale")}),e.jsx("textarea",{className:"w-full px-3 py-2 text-sm border border-[var(--border-default)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)] resize-y",rows:3,value:t.content?.rationale||"",onChange:u=>s({...t,content:{...t.content,rationale:u.target.value}}),placeholder:l("recipeEditor.rationalePlaceholder")})]})]}):e.jsxs("div",{className:"flex-1 overflow-y-auto space-y-6 scrollbar-light",children:[(()=>{const u=[["trigger",t.trigger],["language",t.language],["category",t.category],["kind",t.kind],["knowledgeType",t.knowledgeType],["status",t.status],["complexity",t.complexity],["scope",t.scope],["source",t.source],["updatedAt",t.updatedAt?h(t.updatedAt):void 0]].filter(([,m])=>!!m);return u.length===0?null:e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-2xl p-6",children:[e.jsx("h3",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase tracking-widest mb-4",children:"Recipe Metadata"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-y-4 gap-x-8",children:u.map(([m,c])=>e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] font-bold uppercase mb-1",children:m}),e.jsx("span",{className:"text-sm text-[var(--fg-primary)] break-all font-medium",children:c})]},m))})]})})(),t.description&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-[var(--border-default)] p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:l("recipeEditor.description")}),e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] leading-relaxed",children:t.description})]}),t.content?.markdown&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-blue-100 p-6",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-3 block flex items-center gap-1.5",children:[e.jsx(Qe,{size:11,className:"text-blue-400"})," ",l("recipeEditor.markdown")]}),e.jsx("div",{className:"bg-blue-50/30 border border-blue-100 rounded-xl p-4",children:e.jsx("div",{className:"markdown-body text-sm text-[var(--fg-primary)] leading-relaxed",children:e.jsx(Qt,{content:t.content.markdown})})})]}),t.content?.pattern&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-emerald-100 p-6",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-3 block flex items-center gap-1.5",children:[e.jsx(At,{size:11,className:"text-emerald-500"})," ",l("recipeEditor.code")]}),e.jsx(vt,{code:t.content.pattern,language:g,showLineNumbers:!0})]}),t.content?.rationale&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-[var(--border-default)] p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:l("recipeEditor.rationale")}),e.jsx("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-xl p-4",children:e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] leading-relaxed",children:t.content.rationale})})]}),t.content?.steps&&t.content.steps.length>0&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-[var(--border-default)] p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:l("recipeEditor.steps")}),e.jsx("div",{className:"space-y-2",children:t.content.steps.map((u,m)=>typeof u=="string"?e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-lg p-3 border border-[var(--border-default)] flex items-start gap-2.5",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0 mt-0.5",children:m+1}),e.jsx("p",{className:"text-xs text-[var(--fg-primary)] leading-relaxed",children:u})]},m):e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-lg p-3 border border-[var(--border-default)]",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0",children:m+1}),u.title&&e.jsx("span",{className:"text-xs font-bold text-[var(--fg-primary)]",children:u.title})]}),u.description&&e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] ml-7 leading-relaxed",children:u.description}),u.code&&e.jsx("pre",{className:"text-[11px] font-mono bg-slate-800 text-green-300 p-2.5 rounded-md mt-1.5 ml-7 overflow-x-auto whitespace-pre-wrap",children:u.code})]},m))})]}),t.content?.codeChanges&&t.content.codeChanges.length>0&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-[var(--border-default)] p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:l("recipeEditor.codeChanges")}),e.jsx("div",{className:"space-y-2",children:t.content.codeChanges.map((u,m)=>e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-3 py-1.5 bg-[var(--bg-subtle)] border-b border-[var(--border-default)] flex items-center gap-2",children:[e.jsx(pt,{size:11,className:"text-blue-400"}),e.jsx("code",{className:"text-[10px] font-mono text-[var(--fg-secondary)]",children:u.file})]}),u.explanation&&e.jsx("p",{className:"text-[11px] text-[var(--fg-muted)] px-3 py-1.5 border-b border-[var(--border-default)] bg-yellow-50/30",children:u.explanation}),e.jsxs("div",{className:"p-2 bg-red-50/20 border-b border-[var(--border-default)]",children:[e.jsx("div",{className:"text-[9px] font-bold text-red-400 mb-0.5 uppercase",children:"Before"}),e.jsx("pre",{className:"text-[11px] text-[var(--fg-secondary)] whitespace-pre-wrap break-words font-mono",children:u.before||l("recipes.emptyValue")})]}),e.jsxs("div",{className:"p-2 bg-emerald-50/20",children:[e.jsx("div",{className:"text-[9px] font-bold text-emerald-500 mb-0.5 uppercase",children:"After"}),e.jsx("pre",{className:"text-[11px] text-[var(--fg-primary)] whitespace-pre-wrap break-words font-mono",children:u.after})]})]},m))})]}),t.content?.verification&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-teal-100 p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:l("recipeEditor.validation")}),e.jsxs("div",{className:"bg-teal-50/50 border border-teal-100 rounded-xl p-4 space-y-1.5",children:[t.content.verification.method&&e.jsxs("p",{className:"text-xs text-[var(--fg-secondary)]",children:[e.jsx("span",{className:"font-bold text-teal-600",children:l("recipeEditor.validationMethod")})," ",t.content.verification.method]}),t.content.verification.expectedResult&&e.jsxs("p",{className:"text-xs text-[var(--fg-secondary)]",children:[e.jsx("span",{className:"font-bold text-teal-600",children:l("recipeEditor.validationExpected")})," ",t.content.verification.expectedResult]}),t.content.verification.testCode&&e.jsx("pre",{className:"text-[11px] font-mono bg-slate-800 text-green-300 p-2.5 rounded-md overflow-x-auto whitespace-pre-wrap mt-1",children:t.content.verification.testCode})]})]}),t.tags&&t.tags.length>0&&e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-2xl p-6",children:[e.jsxs("h3",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase tracking-widest mb-3 flex items-center gap-1.5",children:[e.jsx(wr,{size:11,className:"text-blue-400"})," ",l("recipeEditor.tags")]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.tags.map((u,m)=>e.jsx("span",{className:"px-2.5 py-1 bg-blue-50 text-blue-700 border border-blue-100 rounded-full text-xs font-medium",children:u},m))})]}),!!(t.constraints&&(t.constraints.guards?.length||t.constraints.boundaries?.length||t.constraints.preconditions?.length||t.constraints.sideEffects?.length))&&e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-2xl p-6 space-y-4",children:[e.jsxs("h3",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase tracking-widest flex items-center gap-1.5",children:[e.jsx(Ve,{size:11,className:"text-amber-500"})," ",l("recipeEditor.constraints")]}),t.constraints.guards&&t.constraints.guards.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-[var(--fg-muted)] block mb-1.5",children:l("recipeEditor.guardRules")}),e.jsx("ul",{className:"text-sm text-[var(--fg-secondary)] space-y-1",children:t.constraints.guards.map((u,m)=>e.jsxs("li",{className:"flex gap-2 items-start",children:[e.jsx("span",{className:`text-xs mt-0.5 ${u.severity==="error"?"text-red-500":"text-yellow-500"}`,children:"●"}),e.jsx("code",{className:"font-mono text-xs bg-[var(--bg-subtle)] px-1.5 py-0.5 rounded",children:u.pattern}),u.message&&e.jsxs("span",{className:"text-xs text-[var(--fg-muted)]",children:["— ",u.message]})]},m))})]}),t.constraints.boundaries&&t.constraints.boundaries.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-[var(--fg-muted)] block mb-1.5",children:l("recipeEditor.boundaryConstraints")}),e.jsx("ul",{className:"text-sm text-[var(--fg-secondary)] space-y-1",children:t.constraints.boundaries.map((u,m)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-orange-400",children:"●"}),u]},m))})]}),t.constraints.preconditions&&t.constraints.preconditions.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-[var(--fg-muted)] block mb-1.5",children:l("recipeEditor.preconditions")}),e.jsx("ul",{className:"text-sm text-[var(--fg-secondary)] space-y-1",children:t.constraints.preconditions.map((u,m)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-blue-400",children:"◆"}),u]},m))})]}),t.constraints.sideEffects&&t.constraints.sideEffects.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-[var(--fg-muted)] block mb-1.5",children:l("recipeEditor.sideEffects")}),e.jsx("ul",{className:"text-sm text-[var(--fg-secondary)] space-y-1",children:t.constraints.sideEffects.map((u,m)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-pink-400",children:"⚡"}),u]},m))})]})]}),t.relations&&Object.entries(t.relations).some(([,u])=>Array.isArray(u)&&u.length>0)&&e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-2xl p-6",children:[e.jsx("h3",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase tracking-widest mb-4",children:l("recipeEditor.relations")}),e.jsx("div",{className:"space-y-2",children:[{key:"inherits",label:l("recipeEditor.relationTypes.inherits"),color:"text-green-600",icon:"↑"},{key:"implements",label:l("recipeEditor.relationTypes.implements"),color:"text-blue-600",icon:"◇"},{key:"calls",label:l("recipeEditor.relationTypes.calls"),color:"text-cyan-600",icon:"→"},{key:"dependsOn",label:l("recipeEditor.relationTypes.dependsOn"),color:"text-yellow-600",icon:"⊕"},{key:"dataFlow",label:l("recipeEditor.relationTypes.dataFlow"),color:"text-purple-600",icon:"⇢"},{key:"conflicts",label:l("recipeEditor.relationTypes.conflicts"),color:"text-red-600",icon:"✕"},{key:"extends",label:l("recipeEditor.relationTypes.extends"),color:"text-teal-600",icon:"⊃"},{key:"related",label:l("recipeEditor.relationTypes.associates"),color:"text-[var(--fg-muted)]",icon:"∼"}].map(({key:u,label:m,color:c,icon:j})=>{const S=t.relations?.[u];return!S||!Array.isArray(S)||S.length===0?null:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("span",{className:`text-xs font-mono ${c} shrink-0 whitespace-nowrap pt-0.5`,children:[j," ",m]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:S.map((D,I)=>e.jsx("span",{className:"px-2 py-0.5 bg-[var(--bg-surface)] border border-[var(--border-default)] text-[var(--fg-secondary)] rounded-lg text-xs font-mono",children:typeof D=="string"?D:D.id||D.title||JSON.stringify(D)},I))})]},u)})})]}),!t.content?.markdown&&!t.content?.pattern&&!t.description&&e.jsx("div",{className:"bg-[var(--bg-surface)] p-8 rounded-2xl border border-[var(--border-default)] shadow-sm min-h-[200px] flex items-center justify-center",children:e.jsx("div",{className:"text-[var(--fg-muted)] italic",children:l("recipeEditor.noContent")})})]})})}),e.jsxs("div",{className:"p-6 border-t border-[var(--border-default)] flex justify-end gap-3",children:[e.jsx("button",{onClick:r,disabled:o,className:"px-4 py-2 text-[var(--fg-secondary)] font-medium disabled:opacity-50",children:l("recipeEditor.cancel")}),e.jsxs("button",{onClick:a,disabled:o,className:"px-6 py-2 bg-blue-600 text-white rounded-lg font-medium flex items-center gap-2 hover:bg-blue-700 disabled:opacity-60 disabled:cursor-not-allowed",children:[o?e.jsx(Ne,{size:H.lg,className:"animate-spin"}):e.jsx(ws,{size:H.lg}),l(o?"recipeEditor.saving":"recipeEditor.saveChanges")]})]})]})]})},id=({setShowCreateModal:t,createPath:s,setCreatePath:a,handleCreateFromPath:r,handleCreateFromClipboard:o,isExtracting:l})=>{const{t:i}=Ae();return e.jsxs($e,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx($e.Backdrop,{className:"bg-black/20 dark:bg-black/40 backdrop-blur-sm"}),e.jsxs("div",{className:"relative w-full max-w-lg rounded-2xl shadow-2xl overflow-hidden bg-[var(--bg-surface)]",children:[e.jsxs("div",{className:"p-6 border-b flex justify-between items-center bg-[var(--bg-subtle)] border-[var(--border-default)]",children:[e.jsxs("h2",{className:"text-xl font-bold flex items-center gap-2 text-[var(--fg-primary)]",children:[e.jsx(mt,{size:H.xl,className:"text-blue-600"})," ",i("createModal.title")]}),e.jsx("button",{onClick:()=>t(!1),className:"p-2 rounded-full transition-all duration-150 text-[var(--fg-muted)] hover:bg-[var(--bg-subtle)] hover:text-[var(--fg-primary)]",children:e.jsx(ze,{size:H.lg})})]}),e.jsxs("div",{className:"p-8 space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs font-bold uppercase tracking-widest text-[var(--fg-muted)]",children:[e.jsx(va,{size:H.sm})," ",i("createModal.importFromPath")]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:"flex-1 p-3 rounded-xl text-sm outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)] border bg-[var(--bg-subtle)] border-[var(--border-default)] text-[var(--fg-primary)]",placeholder:i("createModal.pathPlaceholder"),value:s,onChange:p=>a(p.target.value)}),e.jsxs("button",{onClick:r,disabled:!s||l,className:"px-5 py-2 rounded-xl text-sm font-bold whitespace-nowrap disabled:opacity-40 transition-all duration-150 bg-[var(--accent)] text-white hover:opacity-90 shadow-sm",children:[e.jsx(va,{size:14,className:"inline -mt-0.5 mr-1"}),i("createModal.scanFile")]})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("div",{className:"w-full border-t border-[var(--border-default)]"})}),e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"px-2 font-bold bg-[var(--bg-surface)] text-[var(--fg-muted)]",children:i("createModal.or")})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs font-bold uppercase tracking-widest text-[var(--fg-muted)]",children:[e.jsx(wl,{size:H.sm})," ",i("createModal.importFromClipboard")]}),e.jsxs("button",{onClick:()=>o(),disabled:l,className:"w-full flex items-center justify-center gap-3 p-4 rounded-xl font-bold transition-all duration-150 border bg-[var(--accent-subtle)] text-[var(--accent)] border-[var(--accent-emphasis)]/20 hover:bg-[var(--accent-emphasis)]/10",children:[e.jsx(Be,{size:H.lg})," ",i("createModal.useClipboard")]})]})]}),l&&e.jsxs("div",{className:"bg-blue-600 text-white p-4 flex items-center justify-center gap-3 animate-pulse",children:[e.jsx(Jt,{size:H.lg,className:"animate-spin"}),e.jsx("span",{className:"font-bold text-sm",children:i("createModal.aiThinking")})]})]})]})};function cd(t){if(!t)return"";if(typeof t=="object"){const o=t.code||t.pattern||t.markdown||t.snippet||t.body||"";if(o)return o}const a=(typeof t=="string"?t:JSON.stringify(t)).replace(/^---[\s\S]*?---\s*\n?/,"").trim(),r=a.match(/```[\w]*\n([\s\S]*?)```/);return r&&r[1]?r[1].trim():a.slice(0,8e3)}const dd=({searchQ:t,insertPath:s,onClose:a})=>{const{t:r}=Ae(),[o,l]=n.useState([]),[i,p]=n.useState(!0),[d,g]=n.useState(null),x=n.useRef(!0),h=n.useRef(null);n.useEffect(()=>(x.current=!0,h.current=new AbortController,Z.search(t||"",{mode:"auto",type:"recipe",signal:h.current.signal}).then(m=>{x.current&&l((m.items||[]).map(c=>({name:(c.title||c.name||"")+".md",path:"",content:c.content,qualityScore:(c.quality||{}).overall||c.qualityScore||0,recommendReason:""})))}).catch(m=>{m.name!=="AbortError"&&x.current&&l([])}).finally(()=>{x.current&&p(!1)}),()=>{x.current=!1,h.current&&h.current.abort()}),[t]);const u=async m=>{g(m.name);try{const c=cd(m.content);await Z.insertAtSearchMark({path:s,content:c}),x.current&&(alert(r("searchModal.insertSuccess")+" "+s),a())}catch{x.current&&alert(r("searchModal.insertFailed"))}finally{x.current&&g(null)}};return e.jsxs($e,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx($e.Backdrop,{className:"bg-black/20 dark:bg-black/40 backdrop-blur-sm"}),e.jsxs("div",{className:"relative bg-[var(--bg-surface)] w-full max-w-2xl rounded-2xl shadow-2xl overflow-hidden flex flex-col max-h-[85vh]",children:[e.jsxs("div",{className:"p-6 border-b border-[var(--border-default)] flex justify-between items-center bg-[var(--bg-subtle)]",children:[e.jsxs("h2",{className:"text-xl font-bold flex items-center gap-2 text-[var(--fg-primary)]",children:[e.jsx(xt,{size:H.xl,className:"text-blue-600"})," ",r("searchModal.title")]}),e.jsx("button",{onClick:a,className:"p-2 hover:bg-[var(--bg-surface)] rounded-full transition-colors",children:e.jsx(ze,{size:H.lg})})]}),e.jsxs("div",{className:"p-4 text-sm text-[var(--fg-muted)] border-b border-[var(--border-default)]",children:[r("searchModal.keyword")," ",t||r("searchModal.keywordAll")," · ",r("searchModal.insertTo")," ",s]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:i?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"})}):o.length===0?e.jsx("div",{className:"text-[var(--fg-muted)] text-center py-8",children:r("searchModal.noResults")}):e.jsx("ul",{className:"space-y-2",children:o.map(m=>e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>u(m),disabled:d!==null,className:"w-full flex items-center justify-between gap-3 p-4 rounded-xl border border-[var(--border-default)] hover:border-[var(--accent-emphasis)] hover:bg-[var(--accent-subtle)]/50 transition-all text-left disabled:opacity-50",children:[e.jsxs("div",{className:"flex-1 flex flex-col gap-1",children:[e.jsx("span",{className:"font-medium text-[var(--fg-primary)] truncate",children:m.name}),(m.qualityScore!==void 0||m.recommendReason)&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[m.qualityScore!==void 0&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-blue-100 rounded text-xs text-blue-700 font-medium",children:["🤖 ",r("searchModal.quality")," ",(m.qualityScore*100).toFixed(0),"%"]}),m.recommendReason&&e.jsx("span",{className:"text-xs text-[var(--fg-secondary)] italic truncate max-w-xs",children:m.recommendReason})]})]}),d===m.name?e.jsxs("span",{className:"text-blue-600 text-sm flex items-center gap-1",children:[e.jsx("span",{className:"animate-spin",children:"⏳"})," ",r("searchModal.inserting")]}):e.jsxs("span",{className:"text-blue-600 text-sm flex items-center gap-1",children:[e.jsx(Cr,{size:H.md})," ",r("searchModal.insertBtn")]})]})},m.name))})})]})]})},Bs=[{id:"google",labelKey:"llmConfig.providers.gemini",defaultModel:"gemini-3-flash-preview",keyEnv:"ASD_GOOGLE_API_KEY"},{id:"openai",labelKey:"llmConfig.providers.openai",defaultModel:"gpt-5.4",keyEnv:"ASD_OPENAI_API_KEY"},{id:"deepseek",labelKey:"llmConfig.providers.deepseek",defaultModel:"deepseek-chat",keyEnv:"ASD_DEEPSEEK_API_KEY"},{id:"claude",labelKey:"llmConfig.providers.claude",defaultModel:"claude-sonnet-4-20250514",keyEnv:"ASD_CLAUDE_API_KEY"},{id:"ollama",labelKey:"llmConfig.providers.ollama",defaultModel:"llama3",keyEnv:""}],Wa=[{id:"",labelKey:"llmConfig.embedProviders.followLlm",defaultModel:""},{id:"ollama",labelKey:"llmConfig.providers.ollama",defaultModel:"qwen3-embedding:0.6b"},{id:"google",labelKey:"llmConfig.providers.gemini",defaultModel:"gemini-embedding-001"},{id:"openai",labelKey:"llmConfig.providers.openai",defaultModel:"text-embedding-3-small"}],ud=({onClose:t,onSaved:s})=>{const{t:a}=Ae(),[r,o]=n.useState(!0),[l,i]=n.useState(!1),[p,d]=n.useState(!1),[g,x]=n.useState("google"),[h,u]=n.useState("gemini-3-flash-preview"),[m,c]=n.useState(""),[j,S]=n.useState(""),[D,I]=n.useState(!1),[P,Y]=n.useState({}),[w,G]=n.useState(!1),[_,N]=n.useState(!1),[E,L]=n.useState(""),[$,U]=n.useState("");n.useEffect(()=>{q()},[]);const q=async()=>{o(!0);try{const V=await Z.getLlmEnvConfig();d(V.hasEnvFile);const B=V.vars||{};B.ASD_AI_PROVIDER&&x(B.ASD_AI_PROVIDER),B.ASD_AI_MODEL&&u(B.ASD_AI_MODEL),B.ASD_AI_PROXY&&S(B.ASD_AI_PROXY),B.ASD_EMBED_PROVIDER&&(L(B.ASD_EMBED_PROVIDER),N(!0)),B.ASD_EMBED_MODEL&&U(B.ASD_EMBED_MODEL),Y(B)}catch{}finally{o(!1)}},A=Bs.find(V=>V.id===g),y=A?.keyEnv||"",W=y?!!P[y]:!0,re=V=>{x(V);const B=Bs.find(oe=>oe.id===V);B&&u(B.defaultModel),c("")},he=async()=>{if(g){if(y&&!W&&!m.trim()){alert(a("llmConfig.apiKeyRequired"));return}i(!0),G(!1);try{await Z.saveLlmEnvConfig({provider:g,model:h||void 0,apiKey:m.trim()||void 0,proxy:j.trim()||void 0,embedProvider:E||void 0,embedModel:$||void 0}),G(!0),setTimeout(()=>{s(),t()},800)}catch(V){alert(ke(V,a("llmConfig.saveFailed")))}finally{i(!1)}}},ue=V=>!V||V.length<10?V?"••••••":"":`${V.slice(0,6)}••••${V.slice(-4)}`;return e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-50",onClick:t,children:e.jsxs("div",{className:"rounded-2xl shadow-2xl w-full max-w-2xl mx-4 overflow-hidden bg-[var(--bg-surface)]",onClick:V=>V.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsx("h2",{className:"text-lg font-semibold text-[var(--fg-primary)]",children:a("llmConfig.title")}),e.jsx("button",{onClick:t,className:"p-1 rounded-lg transition-all duration-150 hover:bg-[var(--bg-subtle)] text-[var(--fg-muted)] hover:text-[var(--fg-primary)]",children:e.jsx(ze,{size:H.md})})]}),e.jsx("div",{className:"px-6 py-5 space-y-5 max-h-[70vh] overflow-y-auto",children:r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ne,{size:24,className:"animate-spin text-blue-500"})}):e.jsxs(e.Fragment,{children:[!p&&e.jsxs("div",{className:"flex items-start gap-2 p-3 bg-amber-50 border border-amber-200 rounded-lg text-sm text-amber-700",children:[e.jsx(st,{size:16,className:"mt-0.5 shrink-0"}),e.jsx("span",{children:a("llmConfig.envWarning")})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-2 text-[var(--fg-primary)]",children:a("llmConfig.provider")}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:Bs.map(V=>e.jsx("button",{type:"button",onClick:()=>re(V.id),className:`px-3 py-2 rounded-lg text-sm font-medium border transition-all ${g===V.id?"bg-[var(--accent-subtle)] border-[var(--accent-emphasis)] text-[var(--accent)] ring-1 ring-[var(--accent-emphasis)]/30":"bg-[var(--bg-surface)] border-[var(--border-default)] text-[var(--fg-secondary)] hover:border-[var(--border-emphasis)] hover:bg-[var(--bg-subtle)]"}`,children:a(V.labelKey)},V.id))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5 text-[var(--fg-primary)]",children:a("llmConfig.model")}),e.jsx("input",{type:"text",value:h,onChange:V=>u(V.target.value),placeholder:A?.defaultModel||"",className:"w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)]/20 focus:border-[var(--accent-emphasis)] border-[var(--border-default)] bg-[var(--bg-subtle)] text-[var(--fg-primary)]"})]}),y&&e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium mb-1.5 text-[var(--fg-primary)]",children:[a("llmConfig.apiKey"),W&&e.jsxs("span",{className:"ml-2 text-xs text-green-600 font-normal",children:["(",a("llmConfig.configured")," ",ue(P[y]),")"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:D?"text":"password",value:m,onChange:V=>c(V.target.value),placeholder:a(W?"llmConfig.apiKeyPlaceholderSet":"llmConfig.apiKeyPlaceholderEmpty"),className:"w-full px-3 py-2 pr-10 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)]/20 focus:border-[var(--accent-emphasis)] border-[var(--border-default)] bg-[var(--bg-subtle)] text-[var(--fg-primary)]"}),e.jsx("button",{type:"button",onClick:()=>I(V=>!V),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-[var(--fg-muted)] hover:text-[var(--fg-secondary)]",children:D?e.jsx(Nl,{size:16}):e.jsx(Ut,{size:16})})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium mb-1.5 text-[var(--fg-primary)]",children:[a("llmConfig.proxy")," ",e.jsx("span",{className:"text-xs font-normal text-[var(--fg-muted)]",children:a("llmConfig.optional")})]}),e.jsx("input",{type:"text",value:j,onChange:V=>S(V.target.value),placeholder:"http://127.0.0.1:7890",className:"w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)]/20 focus:border-[var(--accent-emphasis)] border-[var(--border-default)] bg-[var(--bg-subtle)] text-[var(--fg-primary)]"})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>N(V=>!V),className:"flex items-center justify-between w-full px-4 py-2.5 text-sm font-medium text-[var(--fg-primary)] hover:bg-[var(--bg-subtle)] transition-colors",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[a("llmConfig.embedTitle"),e.jsx("span",{className:"text-xs font-normal text-[var(--fg-muted)]",children:a("llmConfig.optional")}),!_&&E&&e.jsxs("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-blue-500/10 text-blue-600 font-medium",children:[E,$?` / ${$}`:""]})]}),_?e.jsx(gt,{size:14}):e.jsx(Ke,{size:14})]}),_&&e.jsxs("div",{className:"px-4 pb-3 pt-2 space-y-3 border-t border-[var(--border-default)]",children:[e.jsx("p",{className:"text-xs text-[var(--fg-muted)]",children:a("llmConfig.embedHint")}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium mb-1.5 text-[var(--fg-primary)]",children:a("llmConfig.provider")}),e.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Wa.map(V=>e.jsx("button",{type:"button",onClick:()=>{L(V.id),V.defaultModel?U(V.defaultModel):U("")},className:`px-2.5 py-1.5 rounded-lg text-xs font-medium border transition-all whitespace-nowrap ${E===V.id?"bg-[var(--accent-subtle)] border-[var(--accent-emphasis)] text-[var(--accent)] ring-1 ring-[var(--accent-emphasis)]/30":"bg-[var(--bg-surface)] border-[var(--border-default)] text-[var(--fg-secondary)] hover:border-[var(--border-emphasis)] hover:bg-[var(--bg-subtle)]"}`,children:a(V.labelKey)},V.id))})]}),E&&e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium mb-1.5 text-[var(--fg-primary)]",children:a("llmConfig.embedModel")}),e.jsx("input",{type:"text",value:$,onChange:V=>U(V.target.value),placeholder:Wa.find(V=>V.id===E)?.defaultModel||"",className:"w-full px-3 py-1.5 border rounded-lg text-xs focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)]/20 focus:border-[var(--accent-emphasis)] border-[var(--border-default)] bg-[var(--bg-subtle)] text-[var(--fg-primary)]"})]})]})]})]})}),e.jsxs("div",{className:"flex items-center justify-end gap-3 px-6 py-4 border-t border-[var(--border-default)] bg-[var(--bg-subtle)]",children:[e.jsx("button",{onClick:t,className:"px-4 py-2 text-sm font-medium transition-colors text-[var(--fg-secondary)] hover:text-[var(--fg-primary)]",children:a("llmConfig.cancel")}),e.jsxs("button",{onClick:he,disabled:l||r||w,className:`flex items-center gap-2 px-5 py-2 rounded-lg text-sm font-medium transition-all ${w?"bg-green-500 text-white":"bg-blue-600 text-white hover:bg-blue-700 shadow-sm"} disabled:opacity-60`,children:[l?e.jsx(Ne,{size:16,className:"animate-spin"}):w?e.jsx(bt,{size:16}):e.jsx(ws,{size:16}),a(w?"llmConfig.saved":"llmConfig.saveToEnv")]})]})]})})},Va=200,md=({open:t,onClose:s})=>{const{t:a}=Ae(),[r,o]=n.useState([]),[l,i]=n.useState(!1),[p,d]=n.useState(""),g=n.useRef(null);n.useEffect(()=>{if(!t)return;let D=!1;Z.getSignalTrace({limit:100}).then(Y=>{if(D)return;const w=Y.signals.map(G=>({type:G.type,source:G.source,target:G.target,value:G.value,metadata:G.metadata,timestamp:G.timestamp}));o(w)}).catch(()=>{});const I=Cs(),P=Y=>{l||o(w=>{const G=[Y,...w];return G.length>Va?G.slice(0,Va):G})};return I.on("signal:event",P),()=>{D=!0,I.off("signal:event",P)}},[t,l]);const x=p?r.filter(D=>D.type.toLowerCase().includes(p.toLowerCase())||D.source.toLowerCase().includes(p.toLowerCase())):r,h={guard:"text-red-500",search:"text-blue-500",usage:"text-green-500",lifecycle:"text-purple-500",exploration:"text-cyan-500",quality:"text-yellow-500",panorama:"text-indigo-500",decay:"text-orange-500",forge:"text-pink-500"},u={guard:"#ef4444",search:"#3b82f6",usage:"#22c55e",lifecycle:"#a855f7",decay:"#f97316"},m=["guard","search","usage","lifecycle","decay"],c=50,j=n.useMemo(()=>{const D={};for(const P of m)D[P]=0;for(const P of r)P.type in D&&D[P.type]++;const I=Math.max(1,...Object.values(D));return{counts:D,max:I}},[r]),S=n.useMemo(()=>{const D=[];for(const I of m)j.counts[I]>c&&D.push(`${I} 信号量过高 (${j.counts[I]})`);if(r.length>0){const I=r[0].timestamp;Date.now()-I>300*1e3&&D.push("超过 5 分钟未收到新信号")}else t&&D.push("尚未收到任何信号");return D},[r,j,t]);return t?e.jsxs("div",{className:"fixed right-0 top-0 h-full w-80 glass-surface border-l border-[var(--border-muted)] shadow-xl z-50 flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 border-b border-[var(--border-muted)]",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yt,{className:"w-4 h-4 text-[var(--accent)]"}),e.jsx("span",{className:"text-sm font-semibold text-[var(--text-primary)]",children:"Signal Monitor"}),e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-[var(--accent)]/10 text-[var(--accent)]",children:r.length})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>i(!l),className:`p-1 rounded text-xs ${l?"text-red-500":"text-green-500"} hover:bg-[var(--bg-elevated)]`,children:l?"▶":"⏸"}),e.jsx("button",{onClick:()=>o([]),className:"p-1 rounded text-xs text-[var(--text-tertiary)] hover:bg-[var(--bg-elevated)]",children:"Clear"}),e.jsx("button",{onClick:s,className:"p-1 rounded text-[var(--text-tertiary)] hover:bg-[var(--bg-elevated)]",children:e.jsx(ze,{className:"w-4 h-4"})})]})]}),e.jsx("div",{className:"p-2 border-b border-[var(--border-muted)]",children:e.jsx("input",{type:"text",value:p,onChange:D=>d(D.target.value),placeholder:"Filter by type or source...",className:"w-full px-2 py-1 text-xs rounded bg-[var(--bg-elevated)] text-[var(--text-primary)] border border-[var(--border-muted)] focus:outline-none focus:border-[var(--accent)]"})}),e.jsx("div",{ref:g,className:"flex-1 overflow-y-auto min-h-0",children:x.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-32 text-[var(--text-tertiary)]",children:[e.jsx(js,{className:"w-5 h-5 mb-2 opacity-50"}),e.jsx("span",{className:"text-xs",children:"Waiting for signals..."})]}):e.jsx("div",{className:"divide-y divide-[var(--border-muted)]",children:x.map((D,I)=>e.jsxs("div",{className:"p-2 hover:bg-[var(--bg-elevated)] transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:`text-xs font-mono font-semibold ${h[D.type]??"text-[var(--text-secondary)]"}`,children:D.type}),e.jsx("span",{className:"text-[10px] text-[var(--text-tertiary)]",children:new Date(D.timestamp).toLocaleTimeString()})]}),e.jsx("div",{className:"text-[11px] text-[var(--text-tertiary)] mt-0.5 truncate",children:D.source})]},`${D.type}-${D.timestamp}-${I}`))})}),e.jsxs("div",{className:"border-t border-[var(--border-muted)] p-3 shrink-0",children:[e.jsx("h3",{className:"text-xs font-medium text-[var(--fg-muted)] uppercase tracking-wider mb-2",children:"Signal Statistics"}),e.jsx("div",{className:"space-y-1.5",children:m.map(D=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] font-mono w-14 text-[var(--text-tertiary)] text-right",children:D}),e.jsx("div",{className:"flex-1 h-3 rounded-sm bg-[var(--bg-elevated)] overflow-hidden",children:e.jsx("div",{className:"h-full rounded-sm transition-all duration-300",style:{width:`${j.counts[D]/j.max*100}%`,backgroundColor:u[D]}})}),e.jsx("span",{className:"text-[10px] font-mono w-6 text-[var(--text-tertiary)] text-right",children:j.counts[D]})]},D))})]}),S.length>0&&e.jsxs("div",{className:"border-t border-[var(--border-muted)] p-3 shrink-0",children:[e.jsx("h3",{className:"text-xs font-medium text-[var(--fg-muted)] uppercase tracking-wider mb-2",children:"Anomaly Alerts"}),e.jsx("div",{className:"space-y-1",children:S.map((D,I)=>e.jsxs("div",{className:"text-[11px] text-yellow-500 bg-yellow-500/10 rounded px-2 py-1",children:["⚠️ ",D]},I))})]})]}):null};class pd extends it.Component{constructor(s){super(s),this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}render(){return this.state.hasError?e.jsxs("div",{style:{padding:40,textAlign:"center"},children:[e.jsx("h2",{style:{color:"#ef4444",marginBottom:12},children:Us.app.errorBoundary.title}),e.jsx("pre",{style:{fontSize:12,color:"#64748b",whiteSpace:"pre-wrap",maxWidth:600,margin:"0 auto"},children:this.state.error?.message}),e.jsx("button",{onClick:()=>{this.setState({hasError:!1,error:null}),window.location.reload()},style:{marginTop:16,padding:"8px 20px",background:"#3b82f6",color:"#fff",border:"none",borderRadius:8,cursor:"pointer"},children:Us.app.errorBoundary.refreshBtn})]}):this.props.children}}function Ht(t,s="ai-scan"){return{title:t.title||"",description:t.description||"",trigger:t.trigger||"",language:t.language||"",category:t.category||"",tags:t.tags||[],kind:t.kind||"",knowledgeType:t.knowledgeType||"",scope:t.scope||"",complexity:t.complexity||"",difficulty:t.difficulty||"",authority:t.authority,lifecycle:t.lifecycle||"pending",source:t.source||s,doClause:t.doClause||"",dontClause:t.dontClause||"",whenClause:t.whenClause||"",topicHint:t.topicHint||"",coreCode:t.coreCode||"",content:t.content||{},constraints:t.constraints||{},reasoning:t.reasoning||{},quality:t.quality||{},stats:t.stats||{},relations:t.relations||{},headers:t.headers||[],headerPaths:t.headerPaths,moduleName:t.moduleName,includeHeaders:t.includeHeaders,createdAt:t.createdAt,updatedAt:t.updatedAt}}const xd=()=>{const t=to(),s=ao(t.user?.role),a=ro(),{t:r}=Ae(),o=()=>{const C=window.location.pathname.replace(/^\//,"").split("/")[0]||"";return Ol.includes(C)?C:"help"},[l,i]=n.useState(null),[p,d]=n.useState(o()),[g,x]=n.useState(""),[h,u]=n.useState(!1),[m,c]=n.useState(!0),[j,S]=n.useState(null),[D,I]=n.useState([]),[P,Y]=n.useState([]),[w,G]=n.useState(null),[_,N]=n.useState(!1),[E,L]=n.useState({current:0,total:0,status:""}),[$,U]=n.useState([]),[q,A]=n.useState([]),[y,W]=n.useState(null),re=n.useRef(null),he=C=>{const K=re.current;return K?`asd:spm:${C}:${K}`:null},ue=n.useCallback(C=>{A(K=>{const Q=typeof C=="function"?C(K):C;try{const ce=he("scan-results");ce&&sessionStorage.setItem(ce,JSON.stringify(Q))}catch{}return Q})},[]);n.useEffect(()=>{try{const C=he("selected-target");if(!C)return;w?sessionStorage.setItem(C,w):sessionStorage.removeItem(C)}catch{}},[w]),n.useEffect(()=>{try{const C=he("guard-audit");if(!C)return;y?sessionStorage.setItem(C,JSON.stringify(y)):sessionStorage.removeItem(C)}catch{}},[y]);const[V,B]=n.useState(1),[oe,me]=n.useState(12),[R,T]=n.useState(!1),[ee,ie]=n.useState(""),[xe,pe]=n.useState(!1),[M,Ce]=n.useState(null),[F,Se]=n.useState(null),[Te,_e]=n.useState(!1),[Me,te]=n.useState(!0),[de,f]=n.useState(!1),[J,ge]=n.useState(0),[ve,k]=n.useState(!1),b=n.useRef(null),z=n.useRef(null);n.useEffect(()=>{B(1)},[g]),n.useEffect(()=>{if(l?.projectRoot)try{const C=`asd:custom-folder-targets:${l.projectRoot}`,K=localStorage.getItem(C);Y(K?JSON.parse(K):[])}catch{Y([])}},[l?.projectRoot]),n.useEffect(()=>{if(!l?.projectRoot)return;re.current=l.projectRoot;const C=l.projectRoot;try{G(sessionStorage.getItem(`asd:spm:selected-target:${C}`)||null)}catch{G(null)}try{const K=sessionStorage.getItem(`asd:spm:scan-results:${C}`);A(K?JSON.parse(K):[])}catch{A([])}try{const K=sessionStorage.getItem(`asd:spm:guard-audit:${C}`);W(K?JSON.parse(K):null)}catch{W(null)}},[l?.projectRoot]);const le=()=>{b.current&&b.current.abort()},[O,v]=n.useState(!1),se=async()=>{if(!O){v(!0);try{b.current&&b.current.abort(),await Z.cancelBootstrap("Cancelled by user via Dashboard")}catch{}finally{v(!1)}}};n.useEffect(()=>{let C=!1;const K=async()=>{try{const ce=await Z.getSignalStatus();if(!C){const ye=ce?.suggestions?.length||0,Re=ce?.snapshot?.lastResult?.newSuggestions||0;ge(ye||Re)}}catch{}};K();const Q=setInterval(K,300*1e3);return()=>{C=!0,clearInterval(Q)}},[]);const be=n.useRef(null);n.useEffect(()=>{if(a.isAllDone&&a.session){if(be.current!==a.session.id){be.current=a.session.id;const C=a.session.failed>0?r("bootstrap.notifyPartial",{completed:a.session.completed,total:a.session.total,failed:a.session.failed}):r("bootstrap.notifySuccess",{completed:a.session.completed});ne(C,{title:r("bootstrap.coldStartComplete"),type:a.session.failed>0?"error":"success"})}we()}},[a.isAllDone,a.session?.id]),n.useEffect(()=>{if(a.candidateCreatedTick>0){const C=setTimeout(()=>we(),2e3);return()=>clearTimeout(C)}},[a.candidateCreatedTick]);const fe=(C,K)=>{d(C);const Q=K?.preserveSearch&&window.location.search?window.location.search:"";window.history.pushState({},document.title,`/${C}${Q}`)},De=C=>{S(C),d("recipes");const K=new URLSearchParams(window.location.search);K.set("edit",encodeURIComponent(C.name)),window.history.pushState({},document.title,`/recipes?${K.toString()}`)},ae=()=>{S(null),window.history.replaceState({},document.title,"/recipes")};n.useEffect(()=>{g===""&&Ce(null)},[g]),n.useEffect(()=>{d(o())},[]),n.useEffect(()=>{if(!l)return;const C=window.location.pathname.replace(/^\//,"").split("/")[0],Q=new URLSearchParams(window.location.search).get("edit");if(C==="recipes"&&Q&&l.recipes)try{const ce=decodeURIComponent(Q),ye=l.recipes.find(Re=>Re.name===ce);ye&&!j&&(d("recipes"),De(ye))}catch{}},[l]),n.useEffect(()=>{we(),Oe(),rt();const C=()=>{d(o())};window.addEventListener("popstate",C);const K=new URLSearchParams(window.location.search),Q=K.get("action"),ce=K.get("path"),ye=K.get("q")||"";return Q==="search"&&ce?Se({q:ye,path:ce}):Q==="create"&&ce&&(ie(ce),T(!0),K.get("autoScan")==="1"&&setTimeout(()=>Xt(ce),500)),Q&&window.history.replaceState({},document.title,window.location.pathname),()=>{window.removeEventListener("popstate",C)}},[]);const we=async()=>{c(!0);try{const C=await Z.fetchData();i(C)}catch(C){ne(ke(C,r("app.load.failed")),{title:r("app.load.failedTitle"),type:"error"})}finally{c(!1)}},Oe=async()=>{try{const C=await Z.fetchTargets();I(C)}catch(C){console.warn("删除候选残留失败:",ke(C))}},rt=async()=>{try{const C=await Z.getLlmEnvConfig();te(C.llmReady)}catch{}},ct=async()=>{try{await Z.refreshProject(),Oe(),ne(r("app.projectRefresh.success"),{title:r("app.projectRefresh.successTitle")})}catch{ne(r("app.load.failedHint"),{title:r("app.projectRefresh.failed"),type:"error"})}},Xt=async C=>{pe(!0);try{const K=await Z.extractFromPath(C);ue(K.result.map(Q=>({...Ht(Q,"extract"),mode:"full",lang:"cn"}))),fe("spm"),T(!1),we(),K.result?.length>0&&ne(r("app.extract.success"),{title:r("app.extract.successTitle")})}catch{ne(r("app.extract.failed"),{type:"error"})}finally{pe(!1)}},nt=async()=>{if(ee){pe(!0);try{const C=await Z.extractFromPath(ee);ue(C.result.map(K=>({...Ht(K,"extract"),mode:"full",lang:"cn"}))),fe("spm"),T(!1),we(),C.result?.length>0?ne(C.isMarked?r("app.extract.markerSuccess"):r("app.extract.normalSuccess"),{title:r("app.extract.successTitle")}):C.isMarked||ne(r("app.extract.noMarker"),{title:r("app.extract.extracting"),type:"info"})}catch{ne(r("app.extract.failed"),{type:"error"})}finally{pe(!1)}}},Ss=async C=>{try{const K=await navigator.clipboard.readText();if(!K)return ne(r("app.clipboard.empty"),{title:r("app.clipboard.emptyTitle"),type:"info"});ne(r("app.clipboard.analyzing"),{title:r("app.clipboard.analyzingTitle"),type:"info"}),pe(!0);const Q=C||ee;try{const ce=await Z.extractFromText(K,Q||void 0),ye=ce._multipleCount;ue([{...Ht(ce,"clipboard"),mode:"full",lang:"cn"}]),fe("spm"),T(!1),we(),ne(ye?r("app.clipboard.resultMulti",{count:ye}):r("app.extract.normalSuccess"),{title:r("app.clipboard.resultTitle")})}catch(ce){const ye=ke(ce);Jl(ce)?ne(ye,{title:r("app.clipboard.aiFailed"),type:"error"}):ne(ye,{title:r("common.operationFailed"),type:"error"})}}catch{ne(r("app.clipboard.permissionError"),{title:r("app.clipboard.permissionTitle"),type:"error"})}finally{pe(!1)}},rn={"scan:started":{percent:5,status:r("app.scan.events.initializing")},"scan:files-loaded":{percent:15,status:C=>r("app.scan.events.filesLoaded",{count:C.count||0})},"scan:reading":{percent:25,status:C=>r("app.scan.events.readingFiles",{count:C.count||0})},"scan:ai-extracting":{percent:40,status:r("app.scan.events.aiAnalyzing")},"scan:enriching":{percent:85,status:C=>r("app.scan.events.enriching",{count:C.recipeCount||0})},"scan:completed":{percent:95,status:r("app.scan.events.completing")}},nn=async C=>{if(_)return;b.current&&b.current.abort(),z.current&&(clearInterval(z.current),z.current=null);const K=new AbortController;b.current=K,G(C.name),N(!0),ue([]),W(null),U([]),L({current:0,total:100,status:r("app.scan.streamInit")});try{const Q=await Z.scanTargetStream(C,Re=>{const Pe=rn[Re.type];if(Pe){const Fe=typeof Pe.status=="function"?Pe.status(Re):Pe.status;L({current:Pe.percent,total:100,status:Fe})}Re.type==="scan:files-loaded"&&Re.files&&U(Re.files),Re.type==="scan:ai-extracting"&&(z.current&&clearInterval(z.current),z.current=setInterval(()=>{L(Fe=>({...Fe,current:Math.min(Fe.current+1,80)}))},3e3)),(Re.type==="scan:enriching"||Re.type==="scan:completed")&&z.current&&(clearInterval(z.current),z.current=null)},K.signal);z.current&&(clearInterval(z.current),z.current=null),L({current:100,total:100,status:r("app.scan.completed")});const ce=Q.recipes||[],ye=Q.scannedFiles||[];if(ce.length>0||ye.length>0){const Re=typeof C=="string"?C:C?.name||"unknown",Pe=ce.map(Fe=>({...Ht(Fe,"ai-scan"),mode:"full",lang:"cn",candidateTargetName:Re,scanMode:"target"}));if(ue(Pe),ye.length>0&&U(ye),we(),ce.length>0)ne(r("app.scan.targetSuccess",{count:ce.length}),{title:r("app.scan.targetSuccessTitle")});else if(Q.message){const Fe=Q.noAi;ne(Q.message,{title:r(Fe?"app.scan.aiNotConfigured":"app.scan.noResults"),type:Fe?"info":"error"})}else ne(r("app.scan.noResults"),{title:r("app.scan.scanComplete"),type:"info"})}else ne(r("app.scan.scanFailedHint"),{title:r("app.scan.scanFailed"),type:"error"})}catch(Q){if(z.current&&(clearInterval(z.current),z.current=null),fs(Q))return;const ce=ss(Q),ye=ce?r("app.scan.timeout"):ke(Q,r("app.scan.scanError"));ne(ye,{title:r(ce?"app.scan.timeoutTitle":"app.scan.scanError"),type:"error"})}finally{b.current===K&&(N(!1),L({current:0,total:0,status:""}),b.current=null)}},ln=async()=>{if(_)return;b.current&&b.current.abort();const C=new AbortController;b.current=C,fe("candidates"),N(!0),ue([]),W(null),U([]),L({current:0,total:100,status:r("app.coldStart.collecting")}),a.resetSession();try{const K=await Z.bootstrap(C.signal);L({current:100,total:100,status:r("app.coldStart.skeletonCreated")}),K.bootstrapSession&&a.initFromApiResponse(K.bootstrapSession),we();const Q=K.report||{},ce=K.targets?.length||0,ye=Q.totals?.files||0,Re=Q.totals?.graphEdges||0,Pe=K.guardSummary,Fe=Pe?`, ${r("app.coldStart.guardSuffix",{count:Pe.totalViolations})}`:"";ne(r("app.coldStart.skeletonDetail",{targets:ce,files:ye,deps:Re})+Fe)}catch(K){if(Is(K))return;const ce=ss(K)?r("app.coldStart.timeout"):ke(K);ne(ce,{type:"error"})}finally{b.current===C&&(N(!1),L({current:0,total:0,status:""}),b.current=null)}},on=async()=>{if(_)return;b.current&&b.current.abort();const C=new AbortController;b.current=C,fe("candidates"),N(!0),L({current:0,total:100,status:r("app.rescan.analyzing")}),a.resetSession();try{const K=await Z.rescan({reason:"dashboard-rescan"},C.signal);L({current:100,total:100,status:r("app.rescan.done")}),K.bootstrapSession&&a.initFromApiResponse(K.bootstrapSession),we();const Q=K.relevanceAudit||{},ce=K.gapAnalysis||{};ne(r("app.rescan.success",{preserved:K.rescan?.preservedRecipes||0,healthy:Q.healthy||0,decayed:(Q.decay||0)+(Q.severe||0)+(Q.dead||0)})+(ce.gapDimensions>0?` ${r("app.rescan.filling",{count:ce.gapDimensions})}`:""))}catch(K){if(Is(K))return;const Q=ss(K)?r("app.rescan.timeout"):ke(K);ne(Q,{type:"error"})}finally{b.current===C&&(N(!1),L({current:0,total:0,status:""}),b.current=null)}},cn=async()=>{if(_)return;b.current&&b.current.abort();const C=new AbortController;b.current=C,fe("spm"),G("__project__"),N(!0),ue([]),W(null),U([]),L({current:0,total:100,status:r("app.fullScan.collecting")});const K=[{status:r("app.fullScan.phase5"),percent:5},{status:r("app.fullScan.phase15"),percent:15},{status:r("app.fullScan.phase25"),percent:25},{status:r("app.fullScan.phase35"),percent:35},{status:r("app.fullScan.phase45"),percent:45},{status:r("app.fullScan.phase55"),percent:55},{status:r("app.fullScan.phase65"),percent:65},{status:r("app.fullScan.phase75"),percent:75},{status:r("app.fullScan.phase85"),percent:85}];let Q=0;const ce=setInterval(()=>{Q=Math.min(Q+1,K.length);const ye=K[Q-1];ye&&L(Re=>({...Re,current:ye.percent,status:ye.status}))},15e3);try{const ye=await Z.scanProject(C.signal);clearInterval(ce),L({current:100,total:100,status:ye.partial?r("app.fullScan.partialComplete"):r("app.fullScan.completed")});const Re=ye.recipes||[],Pe=ye.scannedFiles||[];if(Re.length>0||Pe.length>0){const Fe=Re.map(yn=>({...Ht(yn,"ai-scan"),mode:"full",lang:"cn",candidateTargetName:"__project__",scanMode:"project"}));ue(Fe),U(Pe),W(ye.guardAudit||null),we();const Ze=ye.guardAudit?.summary,es=Ze?`, ${r("app.fullScan.guardSuffix",{count:Ze.totalViolations})}`:"",_t=ye.partial?r("app.fullScan.timeoutSuffix"):"";ne(r("app.fullScan.resultDetail",{count:Re.length})+es+_t)}else ne(r("app.fullScan.noContent"))}catch(ye){if(clearInterval(ce),Is(ye))return;const Pe=ss(ye)?r("app.fullScan.timeout"):ke(ye);ne(Pe,{type:"error"})}finally{b.current===C&&(N(!1),L({current:0,total:0,status:""}),b.current=null)}},dn=(C,K)=>{const Q=[...q],ce={...Q[C],...K};Q[C]=ce,ue(Q)},un=async C=>{if(!Te){_e(!0);try{const K=(C.content?.pattern||"").trim(),Q=(()=>{if(!K)return!1;const Ze=K.split(`
`).filter(_t=>_t.trim());return Ze.filter(_t=>/^\s*(#{1,6}\s|[-*>]\s|\d+\.\s)/.test(_t)).length<=Ze.length*.3})(),ce=(C.trigger||"").split(/[,,\s]+/).map(Ze=>Ze.trim()).filter(Boolean);if(Q&&ce.length===0){ne(r("app.recipe.triggerRequired"),{type:"error"}),_e(!1);return}const ye={title:C.title||"Untitled",description:C.description||"",trigger:ce.join(", ")||"",language:C.language||"",category:C.category||"Utility",kind:C.kind||"pattern",knowledgeType:C.knowledgeType||"code-pattern",complexity:C.complexity||"intermediate",scope:C.scope||void 0,difficulty:C.difficulty||"",tags:C.tags||[],source:C.source||"ai-scan",sourceFile:C.sourceFile||"",moduleName:C.moduleName||"",doClause:C.doClause||"",dontClause:C.dontClause||"",whenClause:C.whenClause||"",topicHint:C.topicHint||"",coreCode:C.coreCode||"",content:C.content||{},reasoning:C.reasoning||{},quality:C.quality||{},constraints:C.constraints||{},relations:C.relations||{},stats:C.stats||{},headers:C.headers||[],headerPaths:C.headerPaths||[],includeHeaders:C.includeHeaders||!1},Re=await Z.knowledgeCreate(ye);if(Re?.id)try{await Z.knowledgeLifecycle(Re.id,"publish")}catch(Ze){console.warn("auto-publish after save failed:",Ze)}ne(r(Q?"app.recipe.savedAsRecipe":"app.recipe.savedToKb")),ue(Ze=>Ze.filter(es=>es.title!==C.title));const Pe=C.candidateTargetName,Fe=C.candidateId;if(Pe&&Fe)try{await Z.deleteCandidate(Fe)}catch{}we()}catch(K){const Q=ka(K)??ps(K);ne(Q??r("app.recipe.saveFailed"),{type:"error"})}finally{_e(!1)}}},mn=async()=>{if(!(!j||Te)){_e(!0);try{const C=j.id||j.name?.replace(/\.md$/,""),K=typeof j.content=="string"?{pattern:j.content,markdown:"",rationale:"",steps:[],codeChanges:[],verification:null}:j.content||{};await Z.knowledgeUpdate(C,{title:j.name?.replace(/\.md$/,"")||"",description:j.description||"",content:K,tags:j.tags||[],kind:j.kind,language:j.language,category:j.category}),ae(),we()}catch(C){const K=ka(C)??ps(C);ne(K??r("app.recipe.saveRecipeFailed"),{type:"error"})}finally{_e(!1)}}},pn=async C=>{if(window.confirm(r("common.areYouSure")))try{await Z.deleteRecipe(C),we()}catch(K){const Q=ps(K);ne(Q??r("common.deleteFailed"),{type:"error"})}},ua=async(C,K)=>{try{await Z.deleteCandidate(K),ue(Q=>Q.filter(ce=>!(ce.candidateId===K&&ce.candidateTargetName===C))),i(Q=>{if(!Q?.candidates)return Q;const ce={...Q.candidates};if(ce[C]){const ye=ce[C].items.filter(Re=>Re.id!==K);ye.length===0?delete ce[C]:ce[C]={...ce[C],items:ye}}return{...Q,candidates:ce}})}catch{ne(r("common.operationFailed"),{type:"error"})}},xn=async C=>{if(window.confirm(r("app.candidate.clearConfirm",{name:C})))try{await Z.deleteAllCandidatesInTarget(C),we(),ne(r("app.candidate.clearDone",{name:C}))}catch{ne(r("common.operationFailed"),{type:"error"})}},gn=async(C,K)=>{try{await Z.promoteToCandidate(C,C.candidateTargetName||w||"_review"),ne(r("app.candidate.pushSuccess")),ue(Q=>Q.filter((ce,ye)=>ye!==K)),we()}catch(Q){ne(ke(Q,r("app.candidate.pushFailed")),{type:"error"})}},hn=(l?.recipes||[]).filter(C=>{if(M)return M.some(ye=>ye.metadata.type==="recipe"&&ye.metadata.name===C.name);const K=C.name||"",Q=typeof C.content=="string"?C.content:[C.content?.pattern,C.content?.markdown].filter(Boolean).join(" ");return K.toLowerCase().includes(g.toLowerCase())||Q.toLowerCase().includes(g.toLowerCase())||(C.description||"").toLowerCase().includes(g.toLowerCase())}).sort((C,K)=>{if(M){const ye=M.find(Pe=>Pe.metadata.name===C.name)?.similarity||0;return(M.find(Pe=>Pe.metadata.name===K.name)?.similarity||0)-ye}const Q=C.stats?.authorityScore??0;return(K.stats?.authorityScore??0)-Q}),ma=it.useMemo(()=>{const C=new Set(D.map(Q=>`${Q.discovererId||""}::${Q.name}`)),K=P.filter(Q=>!C.has(`${Q.discovererId||""}::${Q.name}`));return[...D,...K]},[D,P]),bn=ma.filter(C=>C.name.toLowerCase().includes(g.toLowerCase())).sort((C,K)=>{const Q=ts(C.name),ce=ts(K.name);if(Q&&!ce)return 1;if(!Q&&ce)return-1;const ye=C.isVirtual?1:0,Re=K.isVirtual?1:0;return ye!==Re?ye-Re:C.name.localeCompare(K.name)}),fn=n.useCallback(C=>{Y(K=>{if(K.some(ce=>ce.path===C.path))return K;const Q=[...K,C];return l?.projectRoot&&localStorage.setItem(`asd:custom-folder-targets:${l.projectRoot}`,JSON.stringify(Q)),Q})},[l?.projectRoot]),vn=n.useCallback(C=>{Y(K=>{const Q=K.filter(ce=>ce.path!==C);return l?.projectRoot&&localStorage.setItem(`asd:custom-folder-targets:${l.projectRoot}`,JSON.stringify(Q)),Q})},[l?.projectRoot]),As=Object.values(l?.candidates||{}).reduce((C,K)=>C+K.items.length,0);return e.jsx(pd,{children:e.jsx(So,{children:e.jsxs("div",{className:"flex h-screen bg-[var(--bg-root)] text-[var(--fg-primary)] overflow-hidden font-sans ambient-bg",children:[e.jsx(zn,{position:"top-center",toastOptions:{duration:5e3,style:{background:"none",padding:0,boxShadow:"none",border:"none"}},containerStyle:{top:24}}),e.jsx(no,{activeTab:p,navigateToTab:fe,candidateCount:As,signalSuggestionCount:J,currentUser:s.user!=="anonymous"?s.user:void 0,currentRole:s.role,permissionMode:s.mode,onLogout:void 0,projectName:l?.projectName}),e.jsxs("main",{className:"flex-1 flex flex-col overflow-hidden relative",children:[e.jsx(_o,{setShowCreateModal:T,aiConfig:l?.aiConfig,llmReady:Me,onOpenLlmConfig:()=>f(!0),onBeforeAiSwitch:le,onAiConfigChange:we,activeTab:p,onOpenCommandPalette:()=>u(!0),projectName:l?.projectName,candidateCount:As,showSignalMonitor:ve,onToggleSignalMonitor:()=>k(C=>!C)}),e.jsx("div",{className:`flex-1 ${p==="wiki"?"overflow-hidden":"overflow-y-auto p-4 xl:p-6 2xl:p-8"}`,children:e.jsx(kl,{mode:"wait",children:e.jsx(Cl.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0,transition:{duration:.2,ease:[.4,0,.2,1]}},exit:{opacity:0,transition:{duration:.15}},className:"h-full",children:m?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-[var(--accent-emphasis)]"})}):p==="recipes"?e.jsx(Si,{recipes:hn,openRecipeEdit:De,handleDeleteRecipe:pn,onRefresh:we,idTitleMap:l?.idTitleMap,currentPage:V,onPageChange:B,pageSize:oe,onPageSizeChange:C=>{me(C),B(1)}}):p==="guard"?e.jsx(Vi,{onRefresh:we}):p==="panorama"?e.jsx(xc,{}):p==="skills"?e.jsx(Mc,{onRefresh:we,signalSuggestionCount:J,onSuggestionCountChange:ge}):p==="candidates"?e.jsxs(e.Fragment,{children:[a.session&&e.jsx("div",{className:"mb-4",children:e.jsx($c,{session:a.session,isAllDone:a.isAllDone,reviewState:a.reviewState,onDismiss:()=>a.resetSession(),onCancel:se,isCancelling:O})}),e.jsx(Fi,{data:l,isShellTarget:ts,isSilentTarget:Kl,isPendingTarget:ql,handleDeleteCandidate:ua,onEditRecipe:De,onColdStart:ln,onRescan:on,isScanning:_,isBootstrapping:a.session?.status==="running",onRefresh:we,onAuditCandidate:(C,K)=>{const Q=(C.content?.pattern||"").trim(),ce=!!Q&&(()=>{const ye=Q.split(`
`).filter(Pe=>Pe.trim());return ye.filter(Pe=>/^\s*(#{1,6}\s|[-*>]\s|\d+\.\s)/.test(Pe)).length<=ye.length*.3})();ue([{...C,mode:ce?"full":"preview",lang:"cn",includeHeaders:!0,difficulty:C.difficulty||C.complexity||"intermediate",authority:C.stats?.authority||3,candidateId:C.id,candidateTargetName:K}]),fe("spm")},onAuditAllInTarget:(C,K)=>{ue(C.map(Q=>{const ce=(Q.content?.pattern||"").trim(),ye=!!ce&&(()=>{const Re=ce.split(`
`).filter(Fe=>Fe.trim());return Re.filter(Fe=>/^\s*(#{1,6}\s|[-*>]\s|\d+\.\s)/.test(Fe)).length<=Re.length*.3})();return{...Q,mode:ye?"full":"preview",lang:"cn",includeHeaders:!0,difficulty:Q.difficulty||Q.complexity||"intermediate",authority:Q.stats?.authority||3,candidateId:Q.id,candidateTargetName:K}})),fe("spm")},handleDeleteAllInTarget:xn})]}):p==="knowledge"?e.jsx(Pc,{onRefresh:ct,idTitleMap:l?.idTitleMap}):p==="spm"?e.jsx(Ki,{targets:ma,filteredTargets:bn,selectedTargetName:w,isScanning:_,scanProgress:E,scanFileList:$,scanResults:q,guardAudit:y,handleScanTarget:nn,handleScanProject:cn,handleUpdateScanResult:dn,handleSaveExtracted:un,handlePromoteToCandidate:gn,handleDeleteCandidate:ua,onEditRecipe:De,isShellTarget:ts,recipes:l?.recipes??[],isSavingRecipe:Te,handleRefreshProject:ct,onAddCustomFolder:fn,onRemoveCustomFolder:vn}):p==="wiki"?e.jsx(Zc,{}):p==="signals"?e.jsx(nd,{}):p==="help"?e.jsx(Ii,{}):e.jsx(Sc,{})},p)})}),j&&e.jsx(od,{editingRecipe:j,setEditingRecipe:S,handleSaveRecipe:mn,closeRecipeEdit:ae,isSavingRecipe:Te}),R&&e.jsx(id,{setShowCreateModal:T,createPath:ee,setCreatePath:ie,handleCreateFromPath:nt,handleCreateFromClipboard:Ss,isExtracting:xe}),F&&e.jsx(dd,{searchQ:F.q,insertPath:F.path,onClose:()=>{Se(null),window.history.replaceState({},document.title,window.location.pathname)}}),de&&e.jsx(ud,{onClose:()=>f(!1),onSaved:()=>{rt(),we()}}),e.jsx(md,{open:ve,onClose:()=>k(!1)})]}),e.jsx(gd,{}),e.jsx(Oo,{open:h,onOpenChange:u,navigateToTab:fe,setShowCreateModal:T,searchQuery:g,setSearchQuery:x,onOpenLlmConfig:()=>f(!0),candidateCount:As})]})})})},gd=()=>{const{isOpen:t}=Zt();return t?e.jsx(Ao,{}):null};Bn.createRoot(document.getElementById("root")).render(e.jsx(it.StrictMode,{children:e.jsx(El,{children:e.jsx(Rl,{children:e.jsx(xd,{})})})}));