autosnippet 3.0.2 → 3.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +85 -239
  2. package/bin/mcp-server.js +12 -1
  3. package/dashboard/dist/assets/{icons-Cdq22n2i.js → icons-eQ_rWCus.js} +97 -102
  4. package/dashboard/dist/assets/index-B3Nnkdxi.js +133 -0
  5. package/dashboard/dist/assets/index-BFNDAqh3.css +1 -0
  6. package/dashboard/dist/index.html +3 -3
  7. package/lib/cli/SetupService.js +9 -12
  8. package/lib/cli/UpgradeService.js +15 -17
  9. package/lib/core/AstAnalyzer.js +2 -2
  10. package/lib/core/ast/ensure-grammars.js +2 -0
  11. package/lib/core/ast/index.js +8 -0
  12. package/lib/core/ast/lang-rust.js +695 -0
  13. package/lib/core/discovery/PythonDiscoverer.js +3 -0
  14. package/lib/core/discovery/RustDiscoverer.js +467 -0
  15. package/lib/core/discovery/index.js +3 -0
  16. package/lib/core/enhancement/django-enhancement.js +169 -3
  17. package/lib/core/enhancement/fastapi-enhancement.js +149 -3
  18. package/lib/core/enhancement/go-grpc-enhancement.js +4 -0
  19. package/lib/core/enhancement/go-web-enhancement.js +6 -0
  20. package/lib/core/enhancement/index.js +5 -0
  21. package/lib/core/enhancement/langchain-enhancement.js +233 -0
  22. package/lib/core/enhancement/ml-enhancement.js +265 -0
  23. package/lib/core/enhancement/nextjs-enhancement.js +219 -0
  24. package/lib/core/enhancement/node-server-enhancement.js +178 -4
  25. package/lib/core/enhancement/react-enhancement.js +165 -4
  26. package/lib/core/enhancement/rust-tokio-enhancement.js +231 -0
  27. package/lib/core/enhancement/rust-web-enhancement.js +256 -0
  28. package/lib/core/enhancement/spring-enhancement.js +2 -0
  29. package/lib/core/enhancement/vue-enhancement.js +143 -2
  30. package/lib/external/ai/AiProvider.js +45 -6
  31. package/lib/external/mcp/handlers/bootstrap/skills.js +2 -0
  32. package/lib/external/mcp/handlers/bootstrap.js +33 -9
  33. package/lib/external/mcp/handlers/guard.js +42 -0
  34. package/lib/http/routes/candidates.js +7 -1
  35. package/lib/service/chat/ChatAgent.js +1 -0
  36. package/lib/service/chat/tools.js +5 -1
  37. package/lib/service/guard/ComplianceReporter.js +20 -7
  38. package/lib/service/guard/GuardCheckEngine.js +156 -5
  39. package/lib/service/guard/SourceFileCollector.js +15 -0
  40. package/package.json +28 -6
  41. package/scripts/install-vscode-copilot.js +32 -97
  42. package/scripts/setup-mcp-config.js +18 -36
  43. package/skills/autosnippet-coldstart/SKILL.md +4 -2
  44. package/skills/autosnippet-concepts/SKILL.md +5 -3
  45. package/skills/autosnippet-reference-rust/SKILL.md +401 -0
  46. package/skills/autosnippet-structure/SKILL.md +1 -1
  47. package/templates/recipes-setup/README.md +2 -2
  48. package/templates/recipes-setup/_template.md +1 -1
  49. package/dashboard/dist/assets/index-ClkyPkDX.js +0 -133
  50. package/dashboard/dist/assets/index-t4QrJwv1.css +0 -1
@@ -0,0 +1,133 @@
1
+ import{r as o,j as e,z as wa,l as sl,h as ka,o as Ca,m as Sa,M as al,a as ll,R as Ct,F as rl,b as nl}from"./vendor-CEnWn7aV.js";import{a as ss}from"./axios-C0Zqfgkc.js";import{Z as et,L as Aa,S as ol,B as rs,H as as,C as il,a as ut,W as cl,G as _s,b as tt,c as lt,d as ws,e as dl,f as ul,D as Da,g as ns,P as pl,h as Pt,i as xl,F as wt,j as xt,k as Ls,l as nt,M as Lt,m as ml,n as $s,o as hl,p as gl,q as Qe,E as os,r as bl,s as fl,U as Ia,t as yl,u as Nt,X as Xe,v as Fe,w as kt,R as Ra,x as rt,y as Bs,A as Ta,z as ft,I as jl,J as Ea,K as Gt,N as yt,O as vl,Q as Nl,T as wl,V as kl,Y as is,_ as Cl,$ as Sl,a0 as Pa,a1 as Al,a2 as Dl,a3 as Et,a4 as ot,a5 as ls,a6 as ht,a7 as Gs,a8 as Cs,a9 as Ht,aa as Ss,ab as Hs,ac as jt,ad as La,ae as Xt,af as Il,ag as Ys,ah as Qs,ai as fs,aj as Ma,ak as cs,al as ys,am as qt,an as Xs,ao as Ot,ap as Rl,aq as Fa,ar as Ms,as as Rt,at as Tl,au as za,av as _a,aw as $a,ax as El,ay as Pl,az as Fs,aA as Ll,aB as qs,aC as Ml,aD as Fl,aE as zl,aF as _l,aG as $l}from"./icons-eQ_rWCus.js";import"./yaml-qRaU8Ldn.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const d of document.querySelectorAll('link[rel="modulepreload"]'))l(d);new MutationObserver(d=>{for(const i of d)if(i.type==="childList")for(const u of i.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&l(u)}).observe(document,{childList:!0,subtree:!0});function a(d){const i={};return d.integrity&&(i.integrity=d.integrity),d.referrerPolicy&&(i.referrerPolicy=d.referrerPolicy),d.crossOrigin==="use-credentials"?i.credentials="include":d.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function l(d){if(d.ep)return;d.ep=!0;const i=a(d);fetch(d.href,i)}})();const zs={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:"代码审计",skills:"Skills",repoWiki:"Wiki",aiAssistant:"AI 助手",help:"使用说明",collapseNav:"折叠导航",expandNav:"展开导航",roleDeveloper:"开发者",roleAgent:"Agent",roleChatAgent:"ChatAgent",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",editEnvConfig:"修改 .env 配置",closeAiChat:"关闭 AI 对话",openAiChat:"打开 AI 对话",aiChat:"AI 对话",newRecipe:"新建 Recipe",syncSnippets:"同步 Snippets",langSwitch:"中 / EN"},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:"字母",sortQuality:"质量",filterAll:"全部类型",filterSnippet:"仅 Snippet",filterKnowledge:"仅 Knowledge",searchPlaceholder:"搜索 Recipes...",totalCount:"共 {count} 条",noResults:"没有匹配的 Recipe",batchActions:"批量操作",selectAll:"全选",deselectAll:"取消全选",batchDelete:"删除选中",batchDeleteConfirm:"确定删除选中的 {count} 条 Recipe?",batchDeleteDone:"已删除 {count} 条",qualityAuthorityScore:"权威分",qualityExcellent:"Excellent",qualityGreat:"Great",qualitySolid:"Solid",qualityGood:"Good",qualityBasic:"Basic",knowledgeType:"类型",typeSnippet:"Snippet",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:"Candidate 审核池",tabs:{pending:"待审",approved:"已批准",rejected:"已拒绝"},sortNewest:"最新优先",sortOldest:"最早优先",sortConfidence:"按置信度",searchPlaceholder:"搜索候选...",totalCount:"共 {count} 条待审",noResults:"没有待审候选",noPending:"已全部审核",confidenceHigh:"高",confidenceMedium:"中",confidenceLow:"低",sourceBootstrap:"冷启动",sourceManual:"manual",sourceAiScan:"ai-scan",sourceExtract:"extract",sourceClipboard:"clipboard",sourceSignal:"signal",approve:"批准",reject:"拒绝",approveAndSave:"批准并保存为 Recipe",batchApprove:"批量批准 ({count})",batchReject:"批量拒绝 ({count})",batchDeleteConfirm:"确定移除选中的 {count} 条候选?",batchDeleteDone:"已删除 {count} 条",approveSuccess:"已批准为 Recipe",rejectSuccess:"已拒绝",aiRefine:"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:"冷启动:结构收集 + 9 维度 Candidate 创建(与 MCP 一致)",enrichTitle:"① 结构补齐:填充缺失的 rationale / knowledgeType / complexity / scope / steps / constraints(只填空不覆盖,建议先于润色执行)",refineTitle:"② 内容润色:改善 summary 描述、补充架构洞察、推断 relations 关联、调整 confidence 评分(逐条 AI 精炼,建议在结构补齐之后执行)",withCode:"(含代码 {count})",emptyHint:"点击下方按钮冷启动知识库,或使用 CLI 命令手动创建",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 审查提交"},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:"待审核",lifecycleActive:"已发布",lifecycleDeprecated:"已废弃",actionPublish:"发布",actionDeprecate:"废弃",actionReactivate:"重新激活",sourceBootstrap:"AI 全量扫描",sourceMcp:"MCP 提交",sourceManual:"手动创建",sourceFileWatcher:"文件监听",sourceClipboard:"剪贴板",sourceCli:"CLI",sourceAgent:"AI Agent",sourceSubmitCheck:"AI 审查提交",allCategories:"所有分类",selectedCount:"已选 {count} 条",batchPublish:"批量发布",quickBatchPublish:"快速批量发布",batchPublishResult:"发布 {success} 条,失败 {fail} 条",batchPublishFailed:"批量发布失败",batchPublishComplete:"批量发布完成",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:"重新打开",aiGenRule:"AI 生成规则",aiGenRuleDesc:"描述你想要检测的模式,AI 将生成 Guard 规则",aiGenPlaceholder:"例: 禁止在 View 中直接调用网络请求",aiGenerating:"AI 生成中...",aiGenSuccess:"规则已生成",aiGenFailed:"规则生成失败",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:"当前项目",generatedRuleId:"已生成规则 ID",dimNoLimit:"不限制",notePlaceholder:"仅作简单模式提示",copyFixSuggestion:"复制修复建议",tableHeaders:{rule:"规则",file:"文件",line:"行号",message:"描述",severity:"级别",status:"状态",actions:"操作"}},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:"架构与设计",bestPractice:"规范与实践",eventAndDataFlow:"事件与数据流",objcDeepScan:"深度扫描",agentGuidelines:"Agent 注意事项",bootstrap:"Bootstrap",codeStandard:"代码规范",codePattern:"设计模式",projectProfile:"项目特征",categoryScan:"Category 分类方法"},pipelineLabels:{"project-profile":"项目概貌","objc-deep-scan":"深度扫描(常量/Hook)","category-scan":"基础类分类方法扫描","code-standard":"代码规范",architecture:"架构模式","code-pattern":"设计模式","event-and-data-flow":"事件与数据流","best-practice":"最佳实践","agent-guidelines":"Agent 开发注意事项"},statusLabels:{skeleton:"等待中",filling:"填充中",completed:"已完成",failed:"失败"},allCompleted:"全部完成",completedWithErrors:"完成(有错误)",elapsed:"已用",estimatedRemaining:"预计剩余",toolCalls:"工具调用",dimensions:"{done}/{total} 维度",notifySuccess:"{completed} 个维度全部填充成功",notifyPartial:"{completed}/{total} 成功,{failed} 失败",coldStartComplete:"冷启动完成",close:"关闭",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 V3 使用说明",subtitle:"连接开发者、AI 与项目知识库:ChatAgent 智能对话 · Skills 开放平台 · 知识库持续生长",techSpecs:"Node.js ≥ 20 · 13 Skills · AI 可自建 · 16 MCP 工具 · ChatAgent 对话 · 4 层检索管线",viewGithub:"查看 GitHub",fullDocs:"完整文档",tokenUsageLast7Days:"Token 用量(近 7 日)",quickStart:"快速开始",coreConcepts:"核心概念",coreFeatures:"核心功能",editorDirectives:"编辑器指令",cursorIntegration:"Cursor AI 集成",v3Architecture:"V3 架构",cliReference:"命令行速查",step1Title:"安装与初始化",step2Title:"启动 Dashboard",step2Desc:"启动 HTTP API + Dashboard + FileWatcher",step3Title:"IDE 集成",step3Desc:"安装 MCP + Skills + Cursor Rules",step4Title:"创建第一个 Recipe",step4Desc1:"Dashboard → New Recipe",step4Desc2:"Use Copied Code → AI 填充 → 保存",threeRoles:"三大角色",roleColumn:"角色",responsibilityColumn:"职责",capabilityColumn:"能力",roleDeveloper:"开发者",roleCursorAgent:"Cursor Agent",roleChatAgent:"ChatAgent",developerResp:"审核与决策、维护项目标准",cursorAgentResp:"按规范生成代码、检索知识库",chatAgentResp:"提取、摘要、扫描、审查",coreComponents:"核心组件",bootstrapLabel:"Bootstrap(冷启动)",bootstrapDesc:"9 维度自动知识提取引擎",candidatesLabel:"Candidates(候选)",candidatesDesc:"待审核的 Recipe 草案",recipeLabel:"Recipe(配方)",recipeDesc:"Markdown 知识文档(Source of Truth)",chatAgentLabel:"ChatAgent(智能对话)",chatAgentDesc:"多 Agent 协作架构,可持续扩展",searchPipelineLabel:"4 层检索管线",searchPipelineDesc:"多模式语义搜索引擎",guardLabel:"Guard(代码审查)",guardDesc:"知识库驱动的代码审查",knowledgeLoop:"知识库闭环",loopStep1:"扫描提取",loopStep1Sub:"AI/Cursor",loopStep2:"人工审核",loopStep2Sub:"Dashboard",loopStep3:"知识沉淀",loopStep3Sub:".md 落盘",loopStep4:"智能使用",loopStep4Sub:"Cursor/Xcode",loopStep5:"持续优化",loopStep5Sub:"asd sync",knowledgeBuild:"知识库构建",semanticSearchLabel:"语义检索",codeAudit:"代码审查(Audit)",dataSync:"数据同步",usageExamples:"使用示例",exampleSearchKB:"检索知识库",exampleSearchKBDesc:'对 Cursor 说:"查找网络请求错误处理的代码"',exampleBatchScan:"批量扫描",exampleBatchScanDesc:'对 Cursor 说:"扫描 NetworkModule,生成 Recipes 到候选"',exampleSubmitCode:"提交代码",exampleSubmitCodeDesc:'对 Cursor 说:"把这段代码保存为 Recipe"',skills10:"10 个 Skills",mcp16:"16 个 MCP 工具(V3 参数化统合)",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/Snippet",searchDirective:"搜索并插入",auditDirective:"代码审查",includeDirective:"自动注入头文件/模块",developerCap:'Dashboard 审核候选、保存 Recipe;Snippet 补全、<code class="bg-slate-100 px-1 rounded">// as:search</code>;运行 <code class="bg-slate-100 px-1 rounded">asd ui</code>',cursorAgentCap:"13 个 Skills 理解规范;16 个 MCP 工具按需检索、提交候选;写操作经 Gateway 审核",chatAgentCap:'<code class="bg-slate-100 px-1 rounded">asd ais</code> 批量扫描;分析剪贴板;Guard 审查;Dashboard RAG',bootstrapBullet1:"扫描项目模块 + AST 分析源码",bootstrapBullet2:"启发式提取 → AI 精炼 → 生成 Candidate",bootstrapBullet3:'MCP 工具:<code class="bg-green-100 px-1 rounded">bootstrap</code>(operation: knowledge / refine / scan)',candidatesBullet1:"来源:AI 扫描、Cursor、剪贴板、Dashboard",candidatesBullet2:"审核后入库为 Recipe,确保质量",candidatesBullet3:"Reasoning 字段记录 AI 推理过程",recipeBullet1:'位置:<code class="bg-blue-100 px-1 rounded">AutoSnippet/recipes/*.md</code>',recipeBullet2:".md 文件 = 唯一数据源,DB 仅作索引缓存",recipeBullet3:'<code class="bg-blue-100 px-1 rounded">asd sync</code> 增量同步 .md → DB',chatAgentCompBullet1:"AnalystAgent 分析意图 → ProducerAgent 执行操作",chatAgentCompBullet2:"HandoffProtocol 自动切换 + 轻量记忆持久化",chatAgentCompBullet3:"项目感知:自动注入知识库状态上下文",searchPipelineBullet1:"InvertedIndex → CoarseRanker → MultiSignalRanker → RetrievalFunnel",searchPipelineBullet2:"BM25 + keyword + semantic 三路融合",searchPipelineBullet3:"search MCP 工具:mode 参数路由 auto / keyword / semantic / context 四种模式",guardCompBullet1:"内建规则 + 自定义规则 + Recipe 关联",guardCompBullet3:'MCP:<code class="bg-rose-100 px-1 rounded">guard</code>(code=单文件 / files=批量)、<code class="bg-rose-100 px-1 rounded">bootstrap</code>(operation: scan)',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 路由 4 种模式)",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 工具',createDirBullet1:"无选项:打开 Dashboard",createDirBullet2:"<code>-c</code>:从剪贴板静默创建",createDirBullet3:"<code>-f</code>:扫描当前文件",searchDirBullet1:"从知识库检索 Recipe/Snippet",searchDirBullet2:"选择后插入代码,替换该行",searchDirBullet3:"记录一次人工使用",auditDirBullet1:"无后缀:审查当前文件",auditDirBullet2:"<code>target</code>:审查当前 Target",auditDirBullet3:"<code>project</code>:审查整个项目",includeDirBullet1:"Snippet 中包含此标记",includeDirBullet2:"补全后自动注入 import",skillIntent:"意图路由",skillConcepts:"概念教学",skillCandidates:"候选提交",skillRecipes:"Recipe 检索",skillGuard:"代码合规",skillStructure:"项目结构",skillAnalysis:"深度分析",skillColdstart:"冷启动",skillCreate:"引导创建",skillLifecycle:"生命周期",mcpLayerHeader:"层级",mcpToolHeader:"工具",mcpDescHeader:"说明",mcpAgentLayerHeader:"Agent 层(12 个)— 默认对外暴露",mcpAdminLayerHeader:"Admin 层(4 个)— 需设置 ASD_MCP_TIER=admin",mcpHealthDesc:"服务健康检查",mcpCapabilitiesDesc:"服务能力清单(Agent 自发现)",mcpGuardDesc:"code=单文件审查 / files=批量审查",mcpSubmitDesc:"提交候选 / 批量 / 保存文档",mcpEnrichDesc:"AI 润色 / 校验 / 查重",mcpLifecycleDesc:"批量生命周期操作",mcpSearchDesc:"mode 路由 auto / keyword / semantic / context",mcpKnowledgeDesc:"operation 路由 list / get / insights / confirm_usage",mcpStructureDesc:"operation 路由 targets / files / metadata",mcpGraphDesc:"operation 路由 query / impact / path / stats",mcpSkillDesc:"operation 路由 list / load / create / update / delete / suggest",mcpBootstrapDesc:"operation 路由 knowledge / refine / scan",archBootstrapStep1:"① 项目扫描 → 依赖 / 目录 / 入口分析",archBootstrapStep2:"② AI 批量提取 → Candidate 候选列表",archBootstrapStep3:"③ 审阅 + Promote → Recipe 知识库就绪",archBootstrapNote:"支持 bootstrap 工具(operation: refine)持续迭代、resume 断点续跑",archPipelineL1:"InvertedIndex — 倒排索引快速召回",archPipelineL2:"CoarseRanker — BM25 + TF-IDF 粗排",archPipelineL3:"MultiSignalRanker — 多维信号精排",archPipelineL4:"RetrievalFunnel — 漏斗截断 + 上下文装配",archAnalystAgent:"<strong>AnalystAgent</strong>:分析用户意图 → 检索知识库 → 给出建议 → 信心信号分级",archProducerAgent:"<strong>ProducerAgent</strong>:生成代码 → 创建候选 → 执行操作 → 结果聚合",archHandoff:"<strong>HandoffProtocol</strong>:两个 Agent 之间的自动切换协议",archMemory:"<strong>轻量记忆</strong>:跨对话偏好/决策/上下文持久化(JSONL,TTL 过期)",archProjectAware:"<strong>项目感知</strong>:自动注入知识库状态(Recipe 分布、候选积压量、Guard 规则数)",archCliDesc:"asd × 10 命令",archMcpDesc:"stdio × 16 工具",archHttpDesc:"Express × 14 路由模块",archSkillsDesc:"13 个 Cursor/Copilot",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:"预览同步变更"},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:"无内容",useSnippet:"使用此片段",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:"待审核",lifecycleActive:"已发布",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 (本地)"}},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:"待审核",active:"已发布",deprecated:"已废弃"},kind:{rule:"规则",pattern:"模式",fact:"事实"},app:{errorBoundary:{title:"页面出现异常",refreshBtn:"刷新页面"},sync:{success:"Recipes 已同步到 IDE Snippets",successTitle:"Snippet 同步成功",failed:"同步失败",failedHint:"请检查 IDE 配置并重试"},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 扫描未返回结果",noSnippets:"该 Target 中未找到可复用的代码片段",scanComplete:"扫描完成",scanFailedHint:"请确认 Target 包含有效的源代码文件",scanFailed:"扫描失败",timeout:"扫描超时,请尝试减少 Target 文件数量",timeoutTitle:"扫描超时",scanError:"扫描出错"},coldStart:{collecting:"正在收集项目结构...",skeletonCreated:"骨架已创建,正在后台填充...",skeletonDetail:"冷启动骨架已创建: {targets} 个 Target, {files} 个文件, {deps} 条依赖...正在后台逐维度填充...",guardSuffix:"Guard: {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}**
2
+
3
+ 当前摘要: {description}
4
+
5
+ **输入润色指令,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:"知识库概览",summarize_code:"生成代码摘要",ai_translate:"翻译文本",analyze_code:"分析代码",extract_recipes:"提取代码片段",enrich_candidate:"丰富候选内容",refine_bootstrap_candidates:"润色候选批次",check_duplicate:"查重检测",discover_relations:"发现关联关系",add_graph_edge:"添加知识图谱边",validate_candidate:"校验候选",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:"查询违规记录",generate_guard_rule:"生成守卫规则",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:"开启:snippet 内写入 // as:include 标记",includeMarkOff:"关闭:不写入导入标记",formatHeaders:"统一导入格式",cleanUnused:"移除代码中未引用的头文件",similarWithClick:"与 {name} 相似 {score}%,点击对比"},skillsView:{aiPromptPrefix:"请为以下场景创建一个 Skill 文档:",placeholderDesc:"例如:创建一个关于 SwiftUI 动画最佳实践的 Skill...",placeholderName:"SwiftUI 动画最佳实践指南",placeholderContent:`# My Custom Skill
6
+
7
+ ## 使用场景
8
+
9
+ ## 操作步骤`},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"}},Bl={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",skills:"Skills",repoWiki:"Repo Wiki",aiAssistant:"AI Assistant",help:"Help",collapseNav:"Collapse navigation",expandNav:"Expand navigation",roleDeveloper:"Developer",roleAgent:"Agent",roleChatAgent:"ChatAgent",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",editEnvConfig:"Edit .env config",closeAiChat:"Close AI Chat",openAiChat:"Open AI Chat",aiChat:"AI Chat",newRecipe:"New Recipe",syncSnippets:"Sync Snippets",langSwitch:"EN / 中"},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",filterAll:"All types",filterSnippet:"Snippets only",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",typeSnippet:"Snippet",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:"Candidate Review Pool",tabs:{pending:"Pending",approved:"Approved",rejected:"Rejected"},sortNewest:"Newest first",sortOldest:"Oldest first",sortConfidence:"By confidence",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:"Approve",reject:"Reject",approveAndSave:"Approve & Save as Recipe",batchApprove:"Approve ({count})",batchReject:"Reject ({count})",batchDeleteConfirm:"Remove {count} selected candidates?",batchDeleteDone:"{count} deleted",approveSuccess:"Approved as Recipe",rejectSuccess:"Rejected",aiRefine:"AI Refine",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:"Cold Start: structural collection + 9-dimension Candidate creation (MCP compatible)",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 cold-start the knowledge base, or use CLI to create manually",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"},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",lifecycleActive:"Active",lifecycleDeprecated:"Deprecated",actionPublish:"Publish",actionDeprecate:"Deprecate",actionReactivate:"Reactivate",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",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",aiGenRule:"AI Generate Rule",aiGenRuleDesc:"Describe the pattern to detect and AI will generate a Guard rule",aiGenPlaceholder:"e.g. Disallow direct network calls in Views",aiGenerating:"AI Generating...",aiGenSuccess:"Rule generated",aiGenFailed:"Rule generation failed",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",generatedRuleId:"Generated rule ID",dimNoLimit:"No limit",notePlaceholder:"Simple pattern hint only",copyFixSuggestion:"Copy fix suggestion",tableHeaders:{rule:"Rule",file:"File",line:"Line",message:"Description",severity:"Severity",status:"Status",actions:"Actions"}},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:"Bootstrap 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:"Bootstrap started",completed:"Bootstrap completed",failed:"Bootstrap failed",partialComplete:"Partially completed"},retryFailed:"Retry failed tasks",viewDetails:"View details",dimLabels:{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"},pipelineLabels:{"project-profile":"Project Overview","objc-deep-scan":"Deep Scan (Constants/Hooks)","category-scan":"Base Class Category Method Scan","code-standard":"Code Standards",architecture:"Architecture Patterns","code-pattern":"Design Patterns","event-and-data-flow":"Events & Data Flow","best-practice":"Best Practices","agent-guidelines":"Agent Development Guidelines"},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:"Bootstrap complete",close:"Close",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 V3 Guide",subtitle:"Connect developers, AI & project knowledge: ChatAgent smart dialog · Skills open platform · Knowledge base continuous growth",techSpecs:"Node.js ≥ 20 · 13 Skills · Self-host AI · 16 MCP Tools · ChatAgent Dialog · 4-Layer Retrieval Pipeline",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:"Cursor AI 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",step4Title:"Create First Recipe",step4Desc1:"Dashboard → New Recipe",step4Desc2:"Use Copied Code → AI Fill → Save",threeRoles:"Three Roles",roleColumn:"Role",responsibilityColumn:"Responsibility",capabilityColumn:"Capabilities",roleDeveloper:"Developer",roleCursorAgent:"Cursor Agent",roleChatAgent:"ChatAgent",developerResp:"Review & decide, maintain project standards",cursorAgentResp:"Generate code per standards, search knowledge base",chatAgentResp:"Extract, summarize, scan, review",coreComponents:"Core Components",bootstrapLabel:"Bootstrap (Cold Start)",bootstrapDesc:"9-dimension auto knowledge extraction engine",candidatesLabel:"Candidates",candidatesDesc:"Draft Recipes pending review",recipeLabel:"Recipe",recipeDesc:"Markdown knowledge document (Source of Truth)",chatAgentLabel:"ChatAgent (Smart Dialog)",chatAgentDesc:"Multi-Agent collaboration architecture, continuously extensible",searchPipelineLabel:"4-Layer Retrieval Pipeline",searchPipelineDesc:"Multi-mode semantic search engine",guardLabel:"Guard (Code Review)",guardDesc:"Knowledge-base driven code review",knowledgeLoop:"Knowledge Loop",loopStep1:"Scan & Extract",loopStep1Sub:"AI/Cursor",loopStep2:"Human Review",loopStep2Sub:"Dashboard",loopStep3:"Knowledge Persist",loopStep3Sub:".md to disk",loopStep4:"Smart Usage",loopStep4Sub:"Cursor/Xcode",loopStep5:"Continuous Optimization",loopStep5Sub:"asd sync",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:"10 Skills",mcp16:"16 MCP Tools (V3 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:"Five 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/Snippet",searchDirective:"Search & Insert",auditDirective:"Code Audit",includeDirective:"Auto-inject headers/modules",developerCap:'Dashboard review candidates, save Recipes; Snippet completion, <code class="bg-slate-100 px-1 rounded">// as:search</code>; run <code class="bg-slate-100 px-1 rounded">asd ui</code>',cursorAgentCap:"13 Skills understand conventions; 16 MCP tools for on-demand retrieval & candidate submission; writes go through Gateway review",chatAgentCap:'<code class="bg-slate-100 px-1 rounded">asd ais</code> batch scan; clipboard analysis; Guard audit; Dashboard RAG',bootstrapBullet1:"Scan project modules + AST source analysis",bootstrapBullet2:"Heuristic extraction → AI refinement → generate Candidate",bootstrapBullet3:'MCP tool: <code class="bg-green-100 px-1 rounded">bootstrap</code> (operation: knowledge / refine / scan)',candidatesBullet1:"Sources: AI scan, Cursor, clipboard, Dashboard",candidatesBullet2:"Reviewed and promoted to Recipe for quality assurance",candidatesBullet3:"Reasoning field records AI inference process",recipeBullet1:'Location: <code class="bg-blue-100 px-1 rounded">AutoSnippet/recipes/*.md</code>',recipeBullet2:".md files = single source of truth, DB is only index cache",recipeBullet3:'<code class="bg-blue-100 px-1 rounded">asd sync</code> incremental sync .md → DB',chatAgentCompBullet1:"AnalystAgent analyze intent → ProducerAgent execute actions",chatAgentCompBullet2:"HandoffProtocol auto-switch + lightweight memory persistence",chatAgentCompBullet3:"Project-aware: auto-inject knowledge base state context",searchPipelineBullet1:"InvertedIndex → CoarseRanker → MultiSignalRanker → RetrievalFunnel",searchPipelineBullet2:"BM25 + keyword + semantic triple fusion",searchPipelineBullet3:"search MCP tool: mode routes auto / keyword / semantic / context four modes",guardCompBullet1:"Built-in rules + custom rules + Recipe association",guardCompBullet3:'MCP: <code class="bg-rose-100 px-1 rounded">guard</code> (code=single file / files=batch), <code class="bg-rose-100 px-1 rounded">bootstrap</code> (operation: scan)',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 4 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',createDirBullet1:"No options: open Dashboard",createDirBullet2:"<code>-c</code>: silently create from clipboard",createDirBullet3:"<code>-f</code>: scan current file",searchDirBullet1:"Retrieve Recipe/Snippet 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:"Snippet 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",mcpLayerHeader:"Layer",mcpToolHeader:"Tool",mcpDescHeader:"Description",mcpAgentLayerHeader:"Agent Layer (12) — 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 / semantic / context",mcpKnowledgeDesc:"operation routes list / get / insights / confirm_usage",mcpStructureDesc:"operation routes targets / files / metadata",mcpGraphDesc:"operation routes query / impact / path / stats",mcpSkillDesc:"operation routes list / load / create / update / delete / suggest",mcpBootstrapDesc:"operation routes knowledge / refine / scan",archBootstrapStep1:"① Project scan → dependency / directory / entry analysis",archBootstrapStep2:"② AI batch extraction → Candidate list",archBootstrapStep3:"③ Review + Promote → Recipe knowledge base ready",archBootstrapNote:"Supports bootstrap tool (operation: refine) for continuous iteration & resume from breakpoint",archPipelineL1:"InvertedIndex — inverted index fast recall",archPipelineL2:"CoarseRanker — BM25 + TF-IDF coarse ranking",archPipelineL3:"MultiSignalRanker — multi-dimensional signal fine ranking",archPipelineL4:"RetrievalFunnel — funnel truncation + context assembly",archAnalystAgent:"<strong>AnalystAgent</strong>: Analyze user intent → retrieve knowledge base → provide suggestions → confidence signal grading",archProducerAgent:"<strong>ProducerAgent</strong>: Generate code → create candidates → execute operations → aggregate results",archHandoff:"<strong>HandoffProtocol</strong>: Automatic switching protocol between two Agents",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 × 10 commands",archMcpDesc:"stdio × 16 tools",archHttpDesc:"Express × 14 route modules",archSkillsDesc:"13 Cursor/Copilot",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"},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",useSnippet:"Use This Snippet",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",lifecycleActive:"Published",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)"}},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",active:"Published",deprecated:"Deprecated"},kind:{rule:"Rule",pattern:"Pattern",fact:"Fact"},app:{errorBoundary:{title:"Something went wrong",refreshBtn:"Refresh Page"},sync:{success:"Recipes synced to IDE Snippets",successTitle:"Snippet Sync Success",failed:"Sync failed",failedHint:"Check IDE configuration and try again"},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",noSnippets:"No reusable code snippets 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:"Cold-start skeleton created: {targets} Targets, {files} files, {deps} dependencies... Filling dimensions in background...",guardSuffix:"Guard: {count} violations",timeout:"Cold-start timed out. Check project file count."},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:"Summary",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}**
10
+
11
+ Current summary: {description}
12
+
13
+ **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",summarize_code:"Summarize code",ai_translate:"Translate text",analyze_code:"Analyze code",extract_recipes:"Extract recipes",enrich_candidate:"Enrich candidate",refine_bootstrap_candidates:"Refine candidates",check_duplicate:"Check duplicate",discover_relations:"Discover relations",add_graph_edge:"Add graph edge",validate_candidate:"Validate candidate",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",generate_guard_rule:"Generate guard rule",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 snippet",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
14
+
15
+ ## Use Cases
16
+
17
+ ## 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"}},Zs={zh:zs,en:Bl},js="asd-dashboard-lang";function Gl(){try{const t=localStorage.getItem(js);if(t==="en"||t==="zh")return t}catch{}return"zh"}function ea(t,s){const a=s.split(".");let l=t;for(const d of a){if(l==null||typeof l!="object")return;l=l[d]}return typeof l=="string"?l:void 0}function Hl(t,s){return s?t.replace(/\{(\w+)\}/g,(a,l)=>{const d=s[l];return d!=null?String(d):`{${l}}`}):t}const Ba=o.createContext(null);function ql({children:t}){const[s,a]=o.useState(Gl);o.useEffect(()=>{const u=localStorage.getItem(js);u==="en"||u==="zh"?fetch("/api/v1/ai/lang",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lang:u})}).catch(()=>{}):fetch("/api/v1/ai/lang").then(p=>p.json()).then(p=>{var g;const n=(g=p==null?void 0:p.data)==null?void 0:g.lang;if(n==="en"||n==="zh"){a(n);try{localStorage.setItem(js,n)}catch{}}}).catch(()=>{})},[]);const l=o.useCallback(u=>{a(u);try{localStorage.setItem(js,u)}catch{}fetch("/api/v1/ai/lang",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lang:u})}).catch(()=>{})},[]),d=o.useCallback((u,p)=>{const n=ea(Zs[s],u)??ea(Zs.zh,u)??u;return Hl(n,p)},[s]),i=o.useMemo(()=>({lang:s,setLang:l,t:d}),[s,l,d]);return e.jsx(Ba.Provider,{value:i,children:t})}function _e(){const t=o.useContext(Ba);if(!t)throw new Error("useI18n must be used within <I18nProvider>");return t}const Ga="asd-dashboard-theme";function Ol(){return typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches}function Kl(){try{const t=localStorage.getItem(Ga);if(t==="light"||t==="dark"||t==="system")return t}catch{}return"system"}const Ha=o.createContext(null);function Ul({children:t}){const[s,a]=o.useState(Kl),[l,d]=o.useState(Ol);o.useEffect(()=>{const g=window.matchMedia("(prefers-color-scheme: dark)"),f=h=>d(h.matches);return g.addEventListener("change",f),()=>g.removeEventListener("change",f)},[]);const i=s==="dark"?!0:s==="light"?!1:l;o.useEffect(()=>{const g=document.documentElement;i?g.classList.add("dark"):g.classList.remove("dark")},[i]);const u=o.useCallback(g=>{a(g);try{localStorage.setItem(Ga,g)}catch{}},[]),p=o.useCallback(()=>{u(i?"light":"dark")},[i,u]),n=o.useMemo(()=>({isDark:i,mode:s,toggle:p,setTheme:u}),[i,s,p,u]);return e.jsx(Ha.Provider,{value:n,children:t})}function St(){const t=o.useContext(Ha);if(!t)throw new Error("useTheme must be used within <ThemeProvider>");return t}const Wl="AutoSnippet";function Vl(t){if(typeof window>"u"||!("Notification"in window))return;const s=()=>{try{new Notification(Wl,{body:t,tag:"autosnippet"})}catch{}};if(Notification.permission==="granted"){s();return}Notification.permission!=="denied"&&Notification.requestPermission().then(a=>{a==="granted"&&s()})}const Jl={success:5e3,error:8e3,info:5e3},ta={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"}},Yl=()=>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"})}),Ql=()=>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"})}),qa=()=>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"})}),Xl={success:Yl,error:Ql,info:qa},Zl=({visible:t,toastId:s,body:a,type:l,title:d,duration:i})=>{const u=ta[l]||ta.info,p=Xl[l]||qa,n=typeof document<"u"&&document.documentElement.classList.contains("dark");return e.jsxs("div",{onClick:()=>wa.dismiss(s),style:{background:n?u.darkBg:u.bg,borderLeft:`4px solid ${n?u.darkBorder:u.border}`,borderRadius:10,boxShadow:n?"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:[d&&e.jsx("div",{style:{fontWeight:600,fontSize:13,lineHeight:1.3,color:n?"#e2e8f0":"#1e293b",marginBottom:2},children:d}),e.jsx("div",{style:{fontSize:12.5,lineHeight:1.45,color:n?"#94a3b8":"#475569",wordBreak:"break-word"},children:a})]}),e.jsx("div",{style:{position:"absolute",bottom:0,left:0,height:3,width:"100%",background:u.bar,opacity:.45,animation:`toast-progress ${i}ms linear forwards`}})]})};function re(t,s){const a=(s==null?void 0:s.type)??"success",l=s==null?void 0:s.title,d=(s==null?void 0:s.duration)??Jl[a]??5e3;typeof document<"u"&&document.visibilityState==="visible"?er(t,a,l,d):Vl(l?`${l}: ${t}`:t)}function er(t,s,a,l){wa.custom(d=>e.jsx(Zl,{visible:d.visible,toastId:d.id,body:t,type:s,title:a,duration:l}),{duration:l})}if(typeof document<"u"){const t="asd-toast-progress-style";if(!document.getElementById(t)){const s=document.createElement("style");s.id=t,s.textContent=`
18
+ @keyframes toast-progress {
19
+ from { width: 100%; }
20
+ to { width: 0%; }
21
+ }`,document.head.appendChild(s)}}const ct={All:{icon:Pt,color:"text-slate-600",bg:"bg-slate-100",border:"border-slate-200"},View:{icon:pl,color:"text-pink-600",bg:"bg-pink-50",border:"border-pink-100"},Service:{icon:ns,color:"text-indigo-600",bg:"bg-indigo-50",border:"border-indigo-100"},Tool:{icon:et,color:"text-amber-600",bg:"bg-amber-50",border:"border-amber-100"},Model:{icon:Da,color:"text-emerald-600",bg:"bg-emerald-50",border:"border-emerald-100"},Network:{icon:ul,color:"text-blue-600",bg:"bg-blue-50",border:"border-blue-100"},Storage:{icon:dl,color:"text-purple-600",bg:"bg-purple-50",border:"border-purple-100"},UI:{icon:ws,color:"text-cyan-600",bg:"bg-cyan-50",border:"border-cyan-100"},Utility:{icon:lt,color:"text-orange-600",bg:"bg-orange-50",border:"border-orange-100"},"code-standard":{icon:tt,color:"text-violet-600",bg:"bg-violet-50",border:"border-violet-100"},"code-pattern":{icon:_s,color:"text-fuchsia-600",bg:"bg-fuchsia-50",border:"border-fuchsia-100"},architecture:{icon:cl,color:"text-sky-600",bg:"bg-sky-50",border:"border-sky-100"},"best-practice":{icon:ut,color:"text-emerald-600",bg:"bg-emerald-50",border:"border-emerald-100"},"event-and-data-flow":{icon:il,color:"text-amber-600",bg:"bg-amber-50",border:"border-amber-100"},"project-profile":{icon:as,color:"text-teal-600",bg:"bg-teal-50",border:"border-teal-100"},"agent-guidelines":{icon:rs,color:"text-rose-600",bg:"bg-rose-50",border:"border-rose-100"},"objc-deep-scan":{icon:ol,color:"text-indigo-600",bg:"bg-indigo-50",border:"border-indigo-100"},"category-scan":{icon:Aa,color:"text-cyan-600",bg:"bg-cyan-50",border:"border-cyan-100"},bootstrap:{icon:et,color:"text-violet-600",bg:"bg-violet-50",border:"border-violet-100"}},tr=["All","View","Service","Tool","Model","Network","Storage","UI","Utility"],sr=["recipes","ai","spm","candidates","knowledge","depgraph","knowledgegraph","guard","skills","wiki","help"],Bt=[{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 Os(t){var a;if(!t)return"";const s=t.toLowerCase().trim();for(const l of Bt)if(l.id===s||(a=l.aliases)!=null&&a.includes(s))return l.id;return s}function sa(t){switch(Os(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 ar="https://github.com/GxFn/AutoSnippet/issues/new?title=Guard%20误报%2F建议%3A%20&body=请描述误报的规则ID、代码片段或改进建议。",us=t=>["Example","Demo","Sample","Tests","Spec","Mock","Runner"].some(a=>t.endsWith(a)||t.includes(a)),lr=t=>t.startsWith("_"),rr=t=>t==="_pending",nr="您暂无写入权限,无法保存。如需此权限请联系管理员;请勿擅自修改核心代码或安装包,以免影响团队协作与数据安全。";function vs(t){var d,i;const s=t==null?void 0:t.response;if((s==null?void 0:s.status)!==403)return null;const a=(d=s.data)==null?void 0:d.code,l=(i=s.data)==null?void 0:i.error;return a==="RECIPE_WRITE_FORBIDDEN"||typeof l=="string"&&l.includes("没权限")?nr:null}const or="保存过于频繁,请稍后再试。";function aa(t){var a;const s=t==null?void 0:t.response;return s!=null&&s.data?s.status===403?vs(t)??null:s.status===429&&((a=s.data)==null?void 0:a.code)==="RECIPE_SAVE_RATE_LIMIT"?or:null:null}const oe=ss.create({baseURL:"/api/v1"});function la(t){const s=t.quality||{},a=t.stats||t.statistics||{},l=t.content||{},d=t.trigger||"@"+(t.title||"").replace(/[\s_-]+(.)?/g,(u,p)=>p?p.toUpperCase():""),i={authority:a.authority||s.overall||0,authorityScore:a.authority||s.overall||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:l,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:i,trigger:d,source:t.source||"",sourceFile:t.sourceFile||"",moduleName:t.moduleName||"",usageGuide:l.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 ir(t){let s="",a="general",l="",d="",i="",u="",p="",n="",g="",f=[],h=[],x="",c=0,j="1.0.0",w="",C="",E="",S="",G="",z="",P="",Z="",X="",H="",q=t;const R=t.match(/^---\n([\s\S]*?)\n---/);if(R){const M=R[1],_=ae=>{const ue=M.match(new RegExp(`^${ae}:\\s*(.+)$`,"m"));return ue?ue[1].trim():null};s=_("language")||s,a=_("category")||a,l=_("title")||l,d=_("trigger")||"",i=_("summary_cn")||_("summary")||_("description")||i,u=_("summary_en")||"",p=_("knowledge_type")||_("knowledgeType")||"",n=_("complexity")||"",g=_("scope")||"",x=_("difficulty")||"",j=_("version")||"1.0.0";const m=_("authority");m&&(c=parseInt(m)||0);const N=_("tags");if(N)try{f=JSON.parse(N)}catch{f=N.split(",").map(ae=>ae.trim()).filter(Boolean)}const y=_("headers");if(y)try{h=JSON.parse(y)}catch{h=[y]}z=_("kind")||"",P=_("doClause")||"",Z=_("dontClause")||"",X=_("whenClause")||"",H=_("topicHint")||"";const W=t.match(/```[\w]*\n([\s\S]*?)```/);W&&(q=W[1].trim());const O=t.replace(/^---\n[\s\S]*?\n---/,"").trim(),be=O.match(/## (?:AI Context \/ )?Usage Guide(?:\s*\(CN\))?\n\n([\s\S]*?)(?=\n## |$)/);be&&(w=be[1].trim());const we=O.match(/## (?:AI Context \/ )?Usage Guide\s*\(EN\)\n\n([\s\S]*?)(?=\n## |$)/);we&&(C=we[1].trim());const ye=O.match(/## Architecture Usage\n\n([\s\S]*?)(?=\n## |$)/);ye&&(E=ye[1].trim());const v=O.match(/## Best Practices\n\n([\s\S]*?)(?=\n## |$)/);v&&(S=v[1].trim());const ee=O.match(/## Standards\n\n([\s\S]*?)(?=\n## |$)/);ee&&(G=ee[1].trim())}return{title:l,language:s,category:a,trigger:d,summary:i,summaryEn:u,knowledgeType:p,complexity:n,scope:g,tags:f,headers:h,difficulty:x,authority:c,version:j,codePattern:q,usageGuide:w,usageGuideEn:C,rationaleText:E,bestPracticesText:S,standardsText:G,kind:z,doClause:P,dontClause:Z,whenClause:X,topicHint:H}}function cr(t,s,a){var d;const l=Array.isArray(t.category)?t.category[0]:t.category||s||"general";return{title:t.title||"Untitled",content:t.content||{pattern:((d=t.content)==null?void 0:d.pattern)||"",markdown:"",rationale:""},description:t.description||"",trigger:t.trigger||"",language:t.language||"",category:l,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:l,headers:t.headers||[],headerPaths:t.headerPaths||[],moduleName:t.moduleName||"",isMarked:t.isMarked||!1}}}async function _t(t){var i,u,p;const s=t.replace(/\.md$/i,"");if(/^[a-f0-9-]{8,}$/i.test(s))return s;const a=await oe.get("/knowledge?limit=1000"),d=(((u=(i=a.data)==null?void 0:i.data)==null?void 0:u.data)||((p=a.data)==null?void 0:p.data)||[]).find(n=>{const g=n.title||n.name||"";return g===s||g+".md"===t});if(d!=null&&d.id)return d.id;throw new Error(`Knowledge entry not found: ${t}`)}async function dr(t,s){var u;const a=(u=t.body)==null?void 0:u.getReader();if(!a)throw new Error("ReadableStream not available");const l=new TextDecoder;let d="",i="";for(;;){const{done:p,value:n}=await a.read();if(p)break;const g=l.decode(n,{stream:!0});d+=g;const f=d.split(`
22
+ `);d=f.pop()||"";for(const h of f){if(h.startsWith(":")||!h.startsWith("data: "))continue;const x=h.slice(6).trim();if(!(!x||x==="[DONE]"))try{const c=JSON.parse(x);if(s(c),c.type==="text:delta"&&c.delta)i+=c.delta;else if(c.type==="stream:done"&&c.text)i=c.text;else if(c.type==="stream:error")throw new Error(c.message||"Stream error")}catch(c){if(c instanceof SyntaxError)continue;throw c}}}return i}const se={async fetchData(){var h,x,c,j,w,C,E;const[t,s,a]=await Promise.all([oe.get("/knowledge?limit=1000").catch(()=>({data:{success:!0,data:{data:[]}}})),oe.get("/ai/config").catch(()=>({data:{success:!0,data:{provider:"",model:""}}})),oe.get("/modules/project-info").catch(()=>({data:{success:!0,data:{projectRoot:""}}}))]),l=((x=(h=t.data)==null?void 0:h.data)==null?void 0:x.data)||((j=(c=t.data)==null?void 0:c.data)==null?void 0:j.items)||[],i=l.filter(S=>S.lifecycle==="active").map(la),u=l.filter(S=>S.lifecycle==="pending"),p={};for(const S of u){const G=S.category||S.language||"_pending";p[G]||(p[G]={targetName:G,scanTime:S.createdAt,items:[]}),p[G].items.push(S)}const n=((w=s.data)==null?void 0:w.data)||{provider:"",model:""},g={};for(const S of l)S.id&&S.title&&(g[S.id]=S.title);const f=((E=(C=a.data)==null?void 0:C.data)==null?void 0:E.projectRoot)||"";return{rootSpec:{list:[]},recipes:i,candidates:p,projectRoot:f,watcherStatus:"active",aiConfig:{provider:n.provider||"",model:n.model||""},idTitleMap:g}},async fetchTargets(){var a;return(((a=(await oe.get("/modules/targets")).data)==null?void 0:a.data)||{}).targets||[]},async getTargetFiles(t,s){var d,i;const l=((d=(await oe.post("/modules/target-files",{target:t},{signal:s})).data)==null?void 0:d.data)||{};return{files:l.files||[],count:l.total||((i=l.files)==null?void 0:i.length)||0}},async scanTarget(t,s){var i;const l=((i=(await oe.post("/modules/scan",{target:t},{signal:s,timeout:6e5})).data)==null?void 0:i.data)||{};return{recipes:l.recipes||l.result||[],scannedFiles:l.scannedFiles||[],message:l.message||"",noAi:!!l.noAi}},async scanTargetStream(t,s,a){let l;const d=await fetch("/api/v1/modules/scan/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({target:t}),signal:a});if(!d.ok)throw new Error(`Scan stream start failed: ${d.status}`);if(l=(await d.json()).sessionId,!l)throw new Error("No sessionId returned");return new Promise((u,p)=>{const n=`/api/v1/modules/scan/events/${l}`,g=new EventSource(n);let f=!1,h={recipes:[],scannedFiles:[],message:"",noAi:!1};function x(){g.close()}if(g.onmessage=c=>{try{const j=JSON.parse(c.data);s(j),j.type==="scan:result"&&(h={recipes:j.recipes||[],scannedFiles:j.scannedFiles||[],message:j.message||"",noAi:!!j.noAi}),j.type==="stream:done"&&(x(),f=!0,u(h)),j.type==="stream:error"&&(x(),f=!0,p(new Error(j.message||"Scan stream error")))}catch{}},g.onerror=()=>{f||(x(),f=!0,h.recipes.length>0?u(h):p(new Error("EventSource connection failed")))},a){const c=()=>{f||(x(),f=!0,p(new DOMException("The operation was aborted.","AbortError")))};if(a.aborted){c();return}a.addEventListener("abort",c,{once:!0})}})},async scanProject(t){var l;const a=((l=(await oe.post("/modules/scan-project",{},{signal:t,timeout:6e5})).data)==null?void 0:l.data)||{};return{targets:a.targets||[],recipes:a.recipes||[],guardAudit:a.guardAudit||null,scannedFiles:a.scannedFiles||[],partial:a.partial||!1}},async browseDirectories(t="",s=3){var d,i;const a=new URLSearchParams;return t&&a.set("path",t),s&&a.set("depth",String(s)),((i=(d=(await oe.get(`/modules/browse-dirs?${a.toString()}`)).data)==null?void 0:d.data)==null?void 0:i.directories)||[]},async scanFolderStream(t,s,a){const l=await fetch("/api/v1/modules/scan-folder/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t}),signal:a});if(!l.ok)throw new Error(`Scan folder start failed: ${l.status}`);const i=(await l.json()).sessionId;if(!i)throw new Error("No sessionId returned");return new Promise((u,p)=>{const n=`/api/v1/modules/scan/events/${i}`,g=new EventSource(n);let f=!1,h={recipes:[],scannedFiles:[],message:"",noAi:!1};function x(){g.close()}if(g.onmessage=c=>{try{const j=JSON.parse(c.data);s(j),j.type==="scan:result"&&(h={recipes:j.recipes||[],scannedFiles:j.scannedFiles||[],message:j.message||"",noAi:!!j.noAi}),j.type==="stream:done"&&(x(),f=!0,u(h)),j.type==="stream:error"&&(x(),f=!0,p(new Error(j.message||"Scan folder stream error")))}catch{}},g.onerror=()=>{f||(x(),f=!0,h.recipes.length>0?u(h):p(new Error("EventSource connection failed")))},a){const c=()=>{f||(x(),f=!0,p(new DOMException("The operation was aborted.","AbortError")))};if(a.aborted){c();return}a.addEventListener("abort",c,{once:!0})}})},async bootstrap(t){var l;const a=((l=(await oe.post("/modules/bootstrap",{},{signal:t,timeout:3e5})).data)==null?void 0:l.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(){var s;return((s=(await oe.get("/modules/bootstrap/status")).data)==null?void 0:s.data)||{status:"idle"}},async getDepGraph(t){var a;return((a=(await oe.get(`/modules/dep-graph?level=${t}`)).data)==null?void 0:a.data)||{}},async getProjectInfo(){var t;try{return((t=(await oe.get("/modules/project-info")).data)==null?void 0:t.data)||{}}catch{return{primaryLanguage:"unknown",discoverers:[],hasSpm:!1}}},async syncSnippets(t="all"){return(await oe.post("/commands/install",{target:t})).data},async refreshProject(){try{await oe.post("/modules/update-map")}catch{await oe.post("/commands/spm-map")}},async extractFromPath(t){var l;const a=((l=(await oe.post("/extract/path",{relativePath:t})).data)==null?void 0:l.data)||{};return{result:a.result||[],isMarked:a.isMarked||!1}},async extractFromText(t,s){var d;const l=((d=(await oe.post("/extract/text",{text:t,...s?{relativePath:s}:{}})).data)==null?void 0:d.data)||{};return Array.isArray(l.result)&&l.result.length>0?l.result[0]:l},async saveRecipe(t,s){const a=ir(s),l=a.title||t.replace(/\.md$/,""),d={trigger:a.trigger,headers:a.headers,difficulty:a.difficulty,authority:a.authority,version:a.version},i={pattern:a.codePattern||"",rationale:a.rationaleText||"",steps:a.bestPracticesText?[a.bestPracticesText]:[],codeChanges:[],verification:null,markdown:a.usageGuide||""},u={};if(a.standardsText){const n=a.standardsText.split(`
23
+ `).map(h=>h.trim()).filter(Boolean),g=n.filter(h=>h.startsWith("- ")).map(h=>h.slice(2).trim());g.length>0&&(u.preconditions=g);const f=n.filter(h=>!h.startsWith("- ")&&!h.startsWith("**"));f.length>0&&(u.boundaries=f)}const p={title:l,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:i,constraints:u,dimensions:d};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 n=await _t(t);await oe.patch(`/knowledge/${n}`,p);return}catch{}await oe.post("/knowledge",p)},async deleteRecipe(t){const s=await _t(t);await oe.delete(`/knowledge/${s}`)},async getRecipeByName(t){var i;const s=await _t(t),l=(i=(await oe.get(`/knowledge/${s}`)).data)==null?void 0:i.data;if(!l)throw new Error("Recipe not found");const d=l.content||{};return{name:t,content:d.pattern||d.markdown||""}},async setRecipeAuthority(t,s){const a=await _t(t);await oe.patch(`/knowledge/${a}/quality`,{codeCompleteness:s,projectAdaptation:s,documentationClarity:s})},async updateRecipeRelations(t,s){const a=await _t(t);await oe.patch(`/knowledge/${a}`,{relations:s})},async getCandidate(t){var l;const a=(l=(await oe.get(`/knowledge/${t}`)).data)==null?void 0:l.data;if(!a)throw new Error("Knowledge entry not found");return a},async deleteCandidate(t){await oe.delete(`/knowledge/${t}`)},async promoteCandidateToRecipe(t,s){var d;const l=(d=(await oe.patch(`/knowledge/${t}/publish`)).data)==null?void 0:d.data;return{recipe:l,candidate:l}},async enrichCandidates(t){var a;return((a=(await oe.post("/candidates/enrich",{candidateIds:t})).data)==null?void 0:a.data)||{enriched:0,total:0,results:[]}},async bootstrapRefine(t,s,a){var d;return((d=(await oe.post("/candidates/bootstrap-refine",{candidateIds:t,userPrompt:s,dryRun:a},{timeout:3e5})).data)==null?void 0:d.data)||{refined:0,total:0,errors:[],results:[]}},async refinePreview(t,s){var l;return((l=(await oe.post("/candidates/refine-preview",{candidateId:t,userPrompt:s},{timeout:12e4})).data)==null?void 0:l.data)||{}},async refineApply(t,s,a){var d;return((d=(await oe.post("/candidates/refine-apply",{candidateId:t,userPrompt:s,preview:a},{timeout:12e4})).data)==null?void 0:d.data)||{}},async getKnowledgeGraph(t=500){var a;return((a=(await oe.get(`/search/graph/all?limit=${t}`)).data)==null?void 0:a.data)||{edges:[],nodeLabels:{},nodeTypes:{},nodeCategories:{}}},async getGraphStats(){var s;return((s=(await oe.get("/search/graph/stats")).data)==null?void 0:s.data)||{totalEdges:0,byRelation:{},nodeTypes:[]}},async discoverRelations(t=20){var a,l,d,i;const s=await oe.post("/recipes/discover-relations",{batchSize:t});if(!((a=s.data)!=null&&a.success))throw new Error(((d=(l=s.data)==null?void 0:l.error)==null?void 0:d.message)||"启动失败");return((i=s.data)==null?void 0:i.data)||{status:"unknown"}},async getDiscoverRelationsStatus(){var s;return((s=(await oe.get("/recipes/discover-relations/status")).data)==null?void 0:s.data)||{status:"idle"}},async deleteAllCandidatesInTarget(t){var d,i;const a=((i=(d=(await oe.get(`/knowledge?category=${encodeURIComponent(t)}&limit=1000`)).data)==null?void 0:d.data)==null?void 0:i.data)||[];let l=0;for(const u of a)try{await oe.delete(`/knowledge/${u.id}`),l++}catch{}return{deleted:l}},async promoteToCandidate(t,s){var d,i;const a=cr(t,s,"review-promote");return{ok:!0,candidateId:((i=(d=(await oe.post("/knowledge",a)).data)==null?void 0:d.data)==null?void 0:i.id)||""}},async getCandidateSimilarity(t,s){var l;return((l=(await oe.post("/search/similarity",{code:t,language:s}).catch(()=>({data:{data:{similar:[]}}}))).data)==null?void 0:l.data)||{similar:[]}},async getCandidateSimilarityEx(t){var a;return((a=(await oe.post("/search/similarity",t).catch(()=>({data:{data:{similar:[]}}}))).data)==null?void 0:a.data)||{similar:[]}},async getRecipeContentByName(t){var p;const s=await _t(t),l=(p=(await oe.get(`/knowledge/${s}`)).data)==null?void 0:p.data;if(!l)throw new Error("Recipe not found");const i=la(l).content,u=[i==null?void 0:i.pattern,i==null?void 0:i.markdown].filter(Boolean).join(`
24
+
25
+ `)||"";return{name:t,content:u}},async getAiProviders(){var s;return((s=(await oe.get("/ai/providers")).data)==null?void 0:s.data)||[]},async setAiConfig(t,s){var l;return((l=(await oe.post("/ai/config",{provider:t,model:s})).data)==null?void 0:l.data)||{provider:t,model:s}},async chat(t,s,a){var i;const d=((i=(await oe.post("/ai/chat",{prompt:t,history:s},{signal:a})).data)==null?void 0:i.data)||{};return{text:d.reply||d.text||"",hasContext:d.hasContext}},async chatStream(t,s,a,l,d){const i=await fetch("/api/v1/ai/chat/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:t,history:s,...d?{lang:d}:{}}),signal:l});if(!i.ok)throw new Error(`Chat start failed: ${i.status}`);if((i.headers.get("content-type")||"").includes("text/event-stream")){let g={text:""};const f=await dr(i,h=>{a(h),h.type==="stream:done"&&(h.text&&(g.text=h.text),g.toolCalls=h.toolCalls,g.hasContext=h.hasContext)});return!g.text&&f&&(g.text=f),g}const p=await i.json(),n=p.sessionId;if(!n)throw new Error(`No sessionId returned: ${JSON.stringify(p)}`);return new Promise((g,f)=>{const h=`/api/v1/ai/chat/events/${n}`,x=new EventSource(h);let c="",j={text:""},w=!1;function C(){x.close()}if(x.onmessage=E=>{try{const S=JSON.parse(E.data);if(S.type==="stream:start")return;a(S),S.type==="text:delta"&&S.delta&&(c+=S.delta),S.type==="stream:done"&&(j={text:S.text||c,toolCalls:S.toolCalls,hasContext:S.hasContext},C(),w=!0,g(j)),S.type==="stream:error"&&(C(),w=!0,f(new Error(S.message||"Stream error")))}catch{}},x.onerror=()=>{w||(C(),c?(w=!0,g({text:c})):(w=!0,f(new Error("EventSource connection failed"))))},l){const E=()=>{w||(C(),w=!0,f(new DOMException("The operation was aborted.","AbortError")))};l.aborted?E():l.addEventListener("abort",E,{once:!0})}})},async refinePreviewStream(t,s,a,l){const d=await fetch("/api/v1/candidates/refine-preview-stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({candidateId:t,userPrompt:s}),signal:l});if(!d.ok)throw new Error(`Refine stream start failed: ${d.status}`);const u=(await d.json()).sessionId;if(!u)throw new Error("No sessionId returned");return new Promise((p,n)=>{const g=`/api/v1/candidates/refine-preview/events/${u}`,f=new EventSource(g);let h=!1;function x(){f.close()}l&&l.addEventListener("abort",()=>{x(),h||(h=!0,n(new DOMException("Aborted","AbortError")))},{once:!0}),f.onmessage=c=>{try{const j=JSON.parse(c.data);a(j),j.type==="stream:done"&&(x(),h=!0,p({candidateId:j.candidateId||t,before:j.before||{},after:j.after||{},preview:j.preview||null})),j.type==="stream:error"&&(x(),h=!0,n(new Error(j.message||"Refine stream error")))}catch{}},f.onerror=()=>{x(),h||(h=!0,n(new Error("Refine EventSource connection lost")))}})},async summarizeCode(t,s){var l;const a=await oe.post("/ai/summarize",{code:t,language:s});return((l=a.data)==null?void 0:l.data)||a.data||{}},async translate(t,s){var d,i;const a=await oe.post("/ai/translate",{summary:t,usageGuide:s}),l=((d=a.data)==null?void 0:d.data)||{summaryEn:"",usageGuideEn:""};return(i=a.data)!=null&&i.warning&&(l.warning=a.data.warning),l},async search(t,s={}){var x,c;const{mode:a="bm25",type:l,limit:d=20,signal:i,context:u}=s,p=j=>{if(!j)return{};if(typeof j=="object")return j;try{return JSON.parse(j)}catch{return{markdown:j}}};if(u){const w=((x=(await oe.post("/search/context-aware",{keyword:t,limit:d,language:u.language,sessionHistory:u.sessionHistory||[]},{signal:i}).catch(()=>({data:{data:{}}}))).data)==null?void 0:x.data)||{},C=(w.results||[]).map(E=>{const S=p(E.content);return{title:(E.name||"").replace(/\.md$/,""),content:S,score:E.similarity||0,qualityScore:E.qualityScore||0,usageCount:E.usageCount||0,authorityScore:E.authority||0,matchType:E.matchType}});return{items:C,total:w.total||C.length,mode:"bm25",ranked:!0}}const n=new URLSearchParams({q:t,mode:a,limit:String(d)});l&&n.set("type",l);const f=((c=(await oe.get(`/search?${n}`,{signal:i})).data)==null?void 0:c.data)||{},h=(f.items||[]).map(j=>({...j,content:p(j.content)}));return{items:h,total:f.totalResults||f.total||h.length,mode:f.mode,ranked:f.ranked}},async semanticSearch(t,s=10){return(await this.search(t,{mode:"semantic",limit:s})).items.map(l=>{var d,i,u;return{name:(l.title||l.name||"")+".md",content:((d=l.content)==null?void 0:d.pattern)||((i=l.content)==null?void 0:i.markdown)||((u=l.content)==null?void 0:u.code)||"",similarity:l.score||0,metadata:{type:"recipe",name:(l.title||l.name||"")+".md"}}})},async contextAwareSearch(t){var a;return((a=(await oe.post("/search/context-aware",t).catch(()=>({data:{data:{}}}))).data)==null?void 0:a.data)||{}},async xcodeSimulateSearch(t){var a;return((a=(await oe.post("/search/xcode-simulate",t).catch(()=>({data:{data:{}}}))).data)==null?void 0:a.data)||{}},async getGuardRules(){var d;const s=((d=(await oe.get("/rules?limit=100")).data)==null?void 0:d.data)||{},a=s.data||s.items||[],l={};for(const i of a)l[i.id]=i;return{rules:l,projectLanguages:s.projectLanguages||[]}},async getGuardViolations(){var a;const s=((a=(await oe.get("/violations")).data)==null?void 0:a.data)||{};return{runs:s.data||s.items||[]}},async clearViolations(){await oe.post("/violations/clear")},async generateGuardRule(t){var a;return((a=(await oe.post("/violations/rules/generate",t)).data)==null?void 0:a.data)||{}},async saveGuardRule(t){var a;return((a=(await oe.post("/rules",t)).data)==null?void 0:a.data)||{}},async insertAtSearchMark(t){return{success:!1}},async searchRecipesForModal(t,s){const a=await this.search(t,{mode:"bm25",type:"recipe",signal:s});return{results:a.items.map(l=>({name:(l.title||l.name||"")+".md",path:"",content:l.content,qualityScore:(l.quality||{}).overall||l.qualityScore||0,recommendReason:""})),total:a.total}},async listSkills(){var s;return((s=(await oe.get("/skills")).data)==null?void 0:s.data)||{skills:[],total:0}},async loadSkill(t,s){var d;const a=s?`?section=${encodeURIComponent(s)}`:"";return((d=(await oe.get(`/skills/${encodeURIComponent(t)}${a}`)).data)==null?void 0:d.data)||{}},async createSkill(t){var a;return((a=(await oe.post("/skills",t)).data)==null?void 0:a.data)||{}},async updateSkill(t,s){var l;return((l=(await oe.put(`/skills/${encodeURIComponent(t)}`,s)).data)==null?void 0:l.data)||{}},async deleteSkill(t){var a;return((a=(await oe.delete(`/skills/${encodeURIComponent(t)}`)).data)==null?void 0:a.data)||{}},async suggestSkills(){var s;return((s=(await oe.get("/skills/suggest")).data)==null?void 0:s.data)||{suggestions:[],analysisContext:{}}},async getSignalStatus(){var s;return((s=(await oe.get("/skills/signal-status")).data)==null?void 0:s.data)||{running:!1,mode:"off",snapshot:null}},async aiGenerateSkill(t){var l;return((l=(await oe.post("/ai/chat",{prompt:`你是一个 AutoSnippet Skill 文档生成助手。用户会描述他们想创建的 Skill,你需要生成完整的 SKILL.md 内容。
26
+
27
+ Skill 文档格式要求:
28
+ 1. 开头用 Markdown 标题说明 Skill 的目的
29
+ 2. 包含清晰的使用场景说明
30
+ 3. 列出具体的操作步骤和指南
31
+ 4. 如有必要,包含代码示例
32
+ 5. 使用中文撰写
33
+
34
+ 请严格按以下格式输出(不要用代码块包裹 JSON):
35
+
36
+ 第一行:一个 JSON 对象,包含 name(kebab-case,3-64 字符)和 description(一句话中文描述)
37
+ 第二行:空行
38
+ 第三行起:Skill 文档正文内容(Markdown 格式,不含 frontmatter)
39
+
40
+ 示例输出:
41
+ {"name": "swiftui-animation-guide", "description": "SwiftUI 动画最佳实践指南"}
42
+
43
+ # SwiftUI 动画最佳实践
44
+
45
+ ## 使用场景
46
+ ...
47
+
48
+ 用户需求:${t}`,history:[]})).data)==null?void 0:l.data)||{reply:""}},async getLlmEnvConfig(){var s;return((s=(await oe.get("/ai/env-config")).data)==null?void 0:s.data)||{vars:{},hasEnvFile:!1,llmReady:!1}},async getTokenUsage7Days(){var s;return((s=(await oe.get("/ai/token-usage")).data)==null?void 0:s.data)||{daily:[],bySource:[],summary:{input_tokens:0,output_tokens:0,total_tokens:0,call_count:0,avg_per_call:0}}},async saveLlmEnvConfig(t){var a;return((a=(await oe.post("/ai/env-config",t)).data)==null?void 0:a.data)||{vars:{},hasEnvFile:!1,llmReady:!1}},async knowledgeList(t={}){var d;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((d=(await oe.get(`/knowledge${a?`?${a}`:""}`)).data)==null?void 0:d.data)||{data:[],pagination:{page:1,pageSize:20,total:0}}},async knowledgeStats(){var s;return((s=(await oe.get("/knowledge/stats")).data)==null?void 0:s.data)||{total:0,pending:0,active:0,deprecated:0,rules:0,patterns:0,facts:0}},async knowledgeGet(t){var a;return(a=(await oe.get(`/knowledge/${t}`)).data)==null?void 0:a.data},async knowledgeCreate(t){var a;return(a=(await oe.post("/knowledge",t)).data)==null?void 0:a.data},async knowledgeUpdate(t,s){var l;return(l=(await oe.patch(`/knowledge/${t}`,s)).data)==null?void 0:l.data},async knowledgeDelete(t){await oe.delete(`/knowledge/${t}`)},async knowledgeLifecycle(t,s,a){var d;return(d=(await oe.patch(`/knowledge/${t}/${s}`,a?{reason:a}:{})).data)==null?void 0:d.data},async knowledgeBatchPublish(t){var a;return((a=(await oe.post("/knowledge/batch-publish",{ids:t})).data)==null?void 0:a.data)||{published:[],failed:[],successCount:0,failureCount:0}},async knowledgeRecordUsage(t,s="adoption",a){await oe.post(`/knowledge/${t}/usage`,{type:s,feedback:a})},async knowledgeUpdateQuality(t){var a;return((a=(await oe.patch(`/knowledge/${t}/quality`)).data)==null?void 0:a.data)||{quality:{}}},async wikiGenerate(){await oe.post("/wiki/generate")},async wikiUpdate(){await oe.post("/wiki/update")},async wikiAbort(){await oe.post("/wiki/abort")},async wikiStatus(){var s;return((s=(await oe.get("/wiki/status")).data)==null?void 0:s.data)||{task:{status:"idle"}}},async wikiFiles(){var s;return((s=(await oe.get("/wiki/files")).data)==null?void 0:s.data)||{files:[],exists:!1}},async wikiFileContent(t){var a;return((a=(await oe.get(`/wiki/file/${t}`)).data)==null?void 0:a.data)||{path:t,content:"",size:0}},async getLang(){var s,a;return((a=(s=(await oe.get("/ai/lang")).data)==null?void 0:s.data)==null?void 0:a.lang)||"zh"},async setLang(t){await oe.post("/ai/lang",{lang:t})}},ur=!1,Ds="auth_token",Is="auth_user";function pr(){const[t,s]=o.useState(()=>localStorage.getItem(Ds)),[a,l]=o.useState(()=>{try{const g=localStorage.getItem(Is);return g?JSON.parse(g):null}catch{return null}}),[d,i]=o.useState(!1),u=o.useCallback(async(g,f)=>{var h,x,c,j;i(!0);try{const C=(await ss.post("/api/v1/auth/login",{username:g,password:f})).data;if(C.success){const E=C.data.token,S=C.data.user??{username:g,role:"developer"};return localStorage.setItem(Ds,E),localStorage.setItem(Is,JSON.stringify(S)),s(E),l(S),{success:!0}}return{success:!1,error:((h=C.error)==null?void 0:h.message)||"登录失败"}}catch(w){return{success:!1,error:((j=(c=(x=w.response)==null?void 0:x.data)==null?void 0:c.error)==null?void 0:j.message)||w.message||"网络错误"}}finally{i(!1)}},[]),p=o.useCallback(()=>{localStorage.removeItem(Ds),localStorage.removeItem(Is),s(null),l(null)},[]);o.useEffect(()=>{},[]);const n=o.useMemo(()=>!0,[t,a]);return{authEnabled:ur,isAuthenticated:n,isLoading:d,user:a,login:u,logout:p}}const xr={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 mr(t){const[s,a]=o.useState(()=>"developer"),[l,d]=o.useState("anonymous"),[i,u]=o.useState("probe"),[p,n]=o.useState(!0),[g,f]=o.useState(null),h=o.useCallback(async()=>{n(!0);try{const C=localStorage.getItem("auth_token"),E={};C&&(E.Authorization=`Bearer ${C}`);const S=await ss.get("/api/v1/auth/probe",{headers:E});if(S.data.success){const G=S.data.data;a(G.role),d(G.user),u(G.mode),f(G.probeCache??null)}}catch{a("developer")}finally{n(!1)}},[]);o.useEffect(()=>{h()},[t,h]);const x=o.useCallback((C,E)=>{const S=xr[s]||[];if(S.includes("*"))return!0;const G=E?`${C}:${E}`:C;if(S.includes(G))return!0;const z=C.split(":")[0];return!!(S.includes(`${z}:*`)||z==="read"&&S.includes("read:*"))},[s]),c=o.useMemo(()=>s==="developer",[s]),j=o.useMemo(()=>s==="developer",[s]),w=o.useMemo(()=>s!=="developer",[s]);return{role:s,user:l,mode:i,isLoading:p,isAdmin:c,canWrite:j,isReadOnly:w,can:x,probeCache:g,refresh:h}}let Ut=null;function Ks(){return Ut||(Ut=sl(window.location.origin,{path:"/socket.io",transports:["websocket"],reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:2e3,reconnectionDelayMax:1e4}),Ut.on("connect",()=>{Ut.emit("join-notifications")})),Ut}const Rs={activeRound:0,round1:{status:"idle"},round2:{status:"idle"},round3:{status:"idle"}};function hr(){const[t,s]=o.useState(null),[a,l]=o.useState(!1),[d,i]=o.useState(Rs),[u,p]=o.useState(0),n=o.useRef(null),g=o.useRef(null);o.useEffect(()=>{const c=Ks(),j=()=>{l(!0),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>C(),500)},w=()=>l(!1),C=async()=>{try{const N=await se.getBootstrapStatus();N&&N.status==="running"&&N.tasks&&s(y=>!y||y.id===N.id||N.progress>((y==null?void 0:y.progress)??0)?(n.current=N.id,N):y)}catch{}},E=()=>C(),S=N=>{n.current=N.sessionId,i(Rs),s({id:N.sessionId,status:"running",progress:0,total:N.total,completed:0,failed:0,filling:0,skeleton:N.total,startedAt:N.startedAt||Date.now(),totalToolCalls:0,elapsedMs:0,tasks:N.tasks.map(y=>({id:y.id,status:"skeleton",meta:{type:y.type,dimId:y.dimId,label:y.label,skillWorthy:y.skillWorthy,skillMeta:y.skillMeta}}))})},G=N=>{s(y=>{if(!y)return y;const W=y.tasks.map(O=>O.id===N.taskId?{...O,status:"filling",startedAt:Date.now()}:O);return{...y,progress:N.progress,tasks:W,filling:W.filter(O=>O.status==="filling").length,skeleton:W.filter(O=>O.status==="skeleton").length}})},z=N=>{var W,O;s(be=>{if(!be)return be;const we=be.tasks.map(ye=>ye.id===N.taskId?{...ye,status:"completed",completedAt:Date.now(),result:N.result}:ye);return{...be,progress:N.progress,completed:N.completed,total:N.total,totalToolCalls:N.totalToolCalls??be.totalToolCalls,elapsedMs:N.elapsedMs??be.elapsedMs,tasks:we,filling:we.filter(ye=>ye.status==="filling").length,skeleton:we.filter(ye=>ye.status==="skeleton").length}}),(Number((W=N.result)==null?void 0:W.created)||Number((O=N.result)==null?void 0:O.extracted)||0)>0&&p(be=>be+1)},P=N=>{s(y=>{if(!y)return y;const W=y.tasks.map(O=>O.id===N.taskId?{...O,status:"failed",completedAt:Date.now(),error:N.error}:O);return{...y,progress:N.progress,failed:W.filter(O=>O.status==="failed").length,tasks:W,filling:W.filter(O=>O.status==="filling").length,skeleton:W.filter(O=>O.status==="skeleton").length}})},Z=N=>{s(y=>{if(!y||N.sessionId&&y.id!==N.sessionId)return y;const W=y.tasks.map(O=>O.status==="skeleton"||O.status==="filling"?{...O,status:"completed",completedAt:Date.now()}:O);return{...y,status:W.some(O=>O.status==="failed")?"completed_with_errors":"completed",progress:100,completed:W.filter(O=>O.status==="completed").length,summary:N.summary,tasks:W,filling:0,skeleton:0}})},X=N=>{i(y=>({...y,activeRound:1,round1:{status:"running",total:N.total}}))},H=N=>{i(y=>({...y,activeRound:1,round1:{status:"completed",total:N.total,kept:N.kept,dropped:N.dropped,merged:N.merged}}))},q=N=>{i(y=>({...y,activeRound:2,round2:{status:"running",total:N.total}}))},R=N=>{i(y=>({...y,activeRound:2,round2:{...y.round2,status:"running",current:N.current,total:N.total,progress:N.progress}}))},M=N=>{i(y=>({...y,activeRound:2,round2:{status:"completed",total:N.total,refined:N.refined,progress:100}}))},_=N=>{i(y=>({...y,activeRound:3,round3:{status:"running",total:N.total}}))},m=N=>{i(y=>({...y,activeRound:3,round3:{status:"completed",total:N.total,afterDedup:N.afterDedup,relationsFound:N.relationsFound}}))};return c.on("connect",j),c.on("disconnect",w),c.io.on("reconnect",E),c.on("bootstrap:started",S),c.on("bootstrap:task-started",G),c.on("bootstrap:task-completed",z),c.on("bootstrap:task-failed",P),c.on("bootstrap:all-completed",Z),c.on("review:round1-started",X),c.on("review:round1-completed",H),c.on("review:round2-started",q),c.on("review:round2-progress",R),c.on("review:round2-completed",M),c.on("review:round3-started",_),c.on("review:round3-completed",m),l(c.connected),c.connected&&C(),()=>{g.current&&clearTimeout(g.current),c.off("connect",j),c.off("disconnect",w),c.io.off("reconnect",E),c.off("bootstrap:started",S),c.off("bootstrap:task-started",G),c.off("bootstrap:task-completed",z),c.off("bootstrap:task-failed",P),c.off("bootstrap:all-completed",Z),c.off("review:round1-started",X),c.off("review:round1-completed",H),c.off("review:round2-started",q),c.off("review:round2-progress",R),c.off("review:round2-completed",M),c.off("review:round3-started",_),c.off("review:round3-completed",m)}},[]);const f=o.useCallback(()=>{n.current=null,s(null),i(Rs)},[]),h=o.useCallback(c=>{c&&s(j=>{if(j&&j.id===c.id){const w=(j.filling??0)+(j.completed??0)+(j.failed??0),C=(c.filling??0)+(c.completed??0)+(c.failed??0);if(j.progress>c.progress||w>C)return j}return n.current=c.id,c})},[]),x=(t==null?void 0:t.status)==="completed"||(t==null?void 0:t.status)==="completed_with_errors";return{session:t,isConnected:a,isAllDone:x,reviewState:d,candidateCreatedTick:u,resetSession:f,initFromApiResponse:h}}const F={xs:12,sm:14,md:16,lg:20,xl:24,xxl:32,xxxl:48};function ra(t){return t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"k":String(t)}const na={developer:{key:"sidebar.roleDeveloper",color:"text-emerald-700",bg:"bg-emerald-50 border-emerald-200"},external_agent:{key:"sidebar.roleAgent",color:"text-purple-700",bg:"bg-purple-50 border-purple-200"},chat_agent:{key:"sidebar.roleChatAgent",color:"text-blue-700",bg:"bg-blue-50 border-blue-200"}},gr={token:bl,probe:os},br=({activeTab:t,navigateToTab:s,candidateCount:a,signalSuggestionCount:l=0,currentUser:d,currentRole:i,permissionMode:u,onLogout:p,collapsed:n=!1,onToggleCollapse:g})=>{const{t:f}=_e(),{isDark:h}=St(),x=na[i||""]||na.developer,c=gr[u||"probe"]||os,[j,w]=o.useState(null),C=o.useCallback(()=>{se.getTokenUsage7Days().then(z=>w(z.summary)).catch(()=>{})},[]);o.useEffect(()=>{C();const z=Ks(),P=()=>C();return z.on("candidate-created",P),z.on("bootstrap:all-completed",P),z.on("token-usage-updated",P),()=>{z.off("candidate-created",P),z.off("bootstrap:all-completed",P),z.off("token-usage-updated",P)}},[C]);const E=[{tab:"recipes",icon:xl,label:f("sidebar.recipes")},{tab:"spm",icon:wt,label:f("sidebar.moduleExplorer")},{tab:"candidates",icon:xt,label:f("sidebar.candidates",{count:a})},{tab:"knowledge",icon:Aa,label:f("sidebar.batchManage")},{tab:"depgraph",icon:_s,label:f("sidebar.depGraph")},{tab:"knowledgegraph",icon:Ls,label:f("sidebar.knowledgeGraph")},{tab:"guard",icon:ut,label:f("sidebar.guard")},{tab:"skills",icon:tt,label:f("sidebar.skills"),badge:l>0?l:void 0,badgeColor:"bg-amber-100 text-amber-700"},{tab:"wiki",icon:nt,label:f("sidebar.repoWiki")},{tab:"ai",icon:Lt,label:f("sidebar.aiAssistant")},{tab:"help",icon:ml,label:f("sidebar.help")}],S=h?"bg-blue-900/30 text-blue-400 font-medium":"bg-blue-50 text-blue-700 font-medium",G=h?"text-slate-300 hover:bg-slate-700/50":"text-slate-600 hover:bg-slate-50";return e.jsxs("aside",{className:`${n?"w-16":"w-64"} ${h?"bg-[#252526] border-r border-[#3e3e42]":"bg-white border-r border-slate-200"} flex flex-col shrink-0 transition-all duration-200`,children:[e.jsxs("div",{className:`${n?"px-3 py-4":"p-6"} border-b ${h?"border-[#3e3e42]":"border-slate-100"} flex items-center ${n?"justify-center":"justify-between"}`,children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center text-white shrink-0",children:e.jsx($s,{size:F.lg})}),!n&&e.jsx("h1",{className:"font-bold text-lg truncate",children:"AutoSnippet"})]}),g&&!n&&e.jsx("button",{onClick:g,className:`p-1 rounded-md transition-colors ${h?"text-slate-500 hover:text-slate-300 hover:bg-slate-700/50":"text-slate-400 hover:text-slate-600 hover:bg-slate-100"}`,title:f("sidebar.collapseNav"),children:e.jsx(hl,{size:16})})]}),n&&g&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsx("button",{onClick:g,className:`p-1.5 rounded-md transition-colors ${h?"text-slate-500 hover:text-slate-300 hover:bg-slate-700/50":"text-slate-400 hover:text-slate-600 hover:bg-slate-100"}`,title:f("sidebar.expandNav"),children:e.jsx(gl,{size:16})})}),e.jsx("nav",{className:`flex-1 ${n?"px-2 py-2":"p-4"} space-y-1 overflow-y-auto scrollbar-light`,children:E.map(({tab:z,icon:P,label:Z,badge:X,badgeColor:H})=>e.jsxs("button",{type:"button",onClick:()=>s(z),title:n?Z:void 0,className:`w-full flex items-center ${n?"justify-center px-2 py-2.5 relative":"gap-3 px-4 py-2"} rounded-lg transition-colors ${t===z?S:G}`,children:[e.jsx(P,{size:F.lg,className:"shrink-0"}),!n&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flex-1 text-left truncate text-[13px]",children:Z}),X!=null&&e.jsxs("span",{className:`flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[10px] font-bold ${H||"bg-blue-100 text-blue-700"}`,children:[e.jsx(Qe,{size:10}),X]})]}),n&&X!=null&&e.jsx("span",{className:"absolute top-0 right-0 w-2 h-2 rounded-full bg-amber-400"})]},z))}),e.jsxs("div",{className:`${n?"px-2 py-3":"p-4"} ${h?"border-t border-[#3e3e42]":"border-t border-slate-100"}`,children:[!n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`flex items-center gap-1.5 mb-3 px-2 py-1.5 rounded-lg border text-[10px] font-bold uppercase tracking-wider ${h?"bg-slate-700/30 border-slate-600 text-slate-400":x.bg+" "+x.color}`,children:[e.jsx(c,{size:F.xs}),e.jsx("span",{children:f(u==="token"?"sidebar.modeLogin":"sidebar.modeProbe")}),e.jsx("span",{className:"mx-0.5",children:"·"}),e.jsx(fl,{size:F.xs}),e.jsx("span",{children:f(x.key)})]}),d&&e.jsxs("div",{className:`flex items-center justify-between mb-3 px-2 py-1.5 rounded-lg ${h?"bg-slate-700/30":"bg-slate-50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Ia,{size:F.sm,className:h?"text-slate-400":"text-slate-500"}),e.jsx("span",{className:`text-xs font-medium truncate ${h?"text-slate-300":"text-slate-600"}`,children:d})]}),p&&e.jsx("button",{onClick:p,title:f("sidebar.logout"),className:`shrink-0 p-1 rounded transition-colors ${h?"text-slate-500 hover:text-red-400 hover:bg-slate-700/50":"text-slate-400 hover:text-red-500 hover:bg-red-50"}`,children:e.jsx(yl,{size:F.sm})})]})]}),j&&j.total_tokens>0&&e.jsxs("button",{onClick:()=>s("help"),title:n?`${f("sidebar.tokenLabel")}: ${ra(j.total_tokens)} (${f("sidebar.tokenCallsFull",{count:j.call_count})})`:void 0,className:`w-full flex items-center ${n?"justify-center py-2 mb-1":"gap-2 px-2 py-1.5 mb-2"} rounded-lg transition-colors ${h?"bg-slate-700/30 hover:bg-slate-700/50 text-slate-400":"bg-amber-50 hover:bg-amber-100 text-amber-700"}`,children:[e.jsx(et,{size:n?F.lg:F.sm,className:h?"text-amber-400":"text-amber-500"}),!n&&e.jsxs("div",{className:"flex flex-col items-start min-w-0",children:[e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider",children:f("sidebar.tokenLabel")}),e.jsxs("span",{className:`text-xs font-mono font-semibold ${h?"text-amber-300":"text-amber-800"}`,children:[ra(j.total_tokens),e.jsxs("span",{className:`ml-1 text-[10px] font-normal ${h?"text-slate-500":"text-amber-600/70"}`,children:["(",j.call_count,f("sidebar.tokenCalls"),")"]})]})]})]})]})]})},fr={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 Us(t){if(!t)return t;let s=t;!s.includes(`
49
+ `)&&s.includes("\\n")&&(s=s.replace(/\\n/g,`
50
+ `));const a=s.match(/\\(?=[\[\]{}()*+?^$.|])/g);return a&&a.length>=3&&(s=s.replace(/\\([\[\]{}()*+?^$.|])/g,"$1")),s}const dt=({code:t,language:s="text",className:a="",showLineNumbers:l=!1})=>{const d=fr[s==null?void 0:s.toLowerCase()]||(s==null?void 0:s.toLowerCase())||"text",i=a.includes("!rounded-none"),u=Us(t);return e.jsx("div",{className:`rounded-xl overflow-x-auto text-sm min-w-0 ${a}`,children:e.jsx(ka,{language:d,style:Ca,showLineNumbers:l,customStyle:{margin:0,padding:"1rem 1.25rem",fontSize:"0.8125rem",lineHeight:1.5,borderRadius:i?0:"0.75rem",overflowX:"auto"},codeTagProps:{className:"language-highlighted",style:{fontFamily:"ui-monospace, monospace"}},PreTag:"div",children:u})})};let yr=0,oa="";function jr(t){const s=t?"dark":"default";s!==oa&&(Sa.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"}}:{}}),oa=s)}const Oa=({code:t})=>{const{t:s}=_e(),{isDark:a}=St(),[l,d]=o.useState(""),[i,u]=o.useState("");return o.useEffect(()=>{let p=!1;const n=`mermaid_${yr++}`;async function g(){var f;jr(a);try{const{svg:h}=await Sa.render(n,t.trim());p||(d(h),u(""))}catch(h){p||(u((h==null?void 0:h.message)||"Mermaid render failed"),d(""));try{(f=document.getElementById("d"+n))==null||f.remove()}catch{}}}return g(),()=>{p=!0}},[t,a]),i?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}):l?e.jsx("div",{className:`my-5 flex justify-center overflow-x-auto rounded-lg border p-4 ${a?"border-slate-700 bg-[#1e1e1e]":"border-slate-200 bg-white"}`,dangerouslySetInnerHTML:{__html:l}}):e.jsx("div",{className:"my-4 flex items-center justify-center py-8 text-slate-400 text-sm",children:s("shared.renderingChart")})};function Ws(t){return!t||typeof t!="string"?t:t.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,"").trim()||t}function vr(t){return!t||typeof t!="string"?t:t.replace(/\\\\n/g,`
51
+ `)}function Nr(t){if(!t||typeof t!="string")return t;const s=t.split(`
52
+ `),a=[];let l=!1;for(let d=0;d<s.length;d++){const i=s[d];if(/^\s*(`{3,}|~{3,})/.test(i)){l=!l,a.push(i);continue}if(l){a.push(i);continue}const u=s[d+1];i!==""&&u!==void 0&&u!==""?a.push(i+" "):a.push(i)}return a.join(`
53
+ `)}const wr=/^\s*(graph|flowchart|sequenceDiagram|classDiagram|stateDiagram|erDiagram|gantt|pie|gitGraph|mindmap|timeline|journey|quadrantChart|sankey|xychart|block)\b/i;function kr(t){const s=[],a=t.split(`
54
+ `);let l=[],d=!1,i=!1,u=[];for(let p=0;p<a.length;p++){const n=a[p],g=/^\s*(`{3,}|~{3,})(.*)$/.exec(n);if(g&&!i&&!d)if(g[2].trim().toLowerCase()==="mermaid"){l.length>0&&(s.push({type:"markdown",content:l.join(`
55
+ `)}),l=[]),d=!0,u=[];continue}else{i=!0,l.push(n);continue}if(d&&g){s.push({type:"mermaid",content:u.join(`
56
+ `)}),d=!1,u=[];continue}if(i&&g){i=!1,l.push(n);continue}d?u.push(n):l.push(n)}return d&&u.length>0&&s.push({type:"mermaid",content:u.join(`
57
+ `)}),l.length>0&&s.push({type:"markdown",content:l.join(`
58
+ `)}),s}const Cr=t=>({pre({children:s}){return e.jsx("div",{className:"min-w-0",children:s})},code({node:s,className:a,children:l,...d}){const i=/language-(\w+)/.exec(a||""),u=Array.isArray(l)?l.join(""):String(l),p=u.replace(/\n$/,""),n=u.includes(`
59
+ `)||!!i;return n&&wr.test(p)?e.jsx(Oa,{code:p}):n&&i?e.jsx(dt,{code:p,language:i[1],showLineNumbers:t}):n?e.jsx(dt,{code:p,language:"text",showLineNumbers:t}):e.jsx("code",{className:"px-1.5 py-0.5 bg-slate-100 text-slate-800 rounded text-[0.9em] font-mono border border-slate-200/60",...d,children:l})},p:({children:s})=>e.jsx("p",{className:"mb-4 leading-7 last:mb-0",children:s}),h1:({children:s,...a})=>{const l=typeof s=="string"?s.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g,"-").replace(/(^-|-$)/g,""):void 0;return e.jsx("h1",{id:l,className:"text-[1.75rem] font-bold mb-4 mt-8 first:mt-0 pb-2 border-b border-slate-200/70 text-slate-900 leading-tight scroll-mt-20",...a,children:s})},h2:({children:s,...a})=>{const l=typeof s=="string"?s.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g,"-").replace(/(^-|-$)/g,""):void 0;return e.jsx("h2",{id:l,className:"text-xl font-bold mb-3 mt-8 pb-1.5 border-b border-slate-100 text-slate-800 leading-snug scroll-mt-20",...a,children:s})},h3:({children:s,...a})=>{const l=typeof s=="string"?s.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g,"-").replace(/(^-|-$)/g,""):void 0;return e.jsx("h3",{id:l,className:"text-lg font-semibold mb-2 mt-6 text-slate-800 leading-snug scroll-mt-20",...a,children:s})},h4:({children:s,...a})=>{const l=typeof s=="string"?s.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g,"-").replace(/(^-|-$)/g,""):void 0;return e.jsx("h4",{id:l,className:"text-base font-semibold mb-2 mt-5 text-slate-700 scroll-mt-20",...a,children:s})},strong:({children:s})=>e.jsx("strong",{className:"font-semibold text-slate-900",children:s}),em:({children:s})=>e.jsx("em",{className:"italic text-slate-600",children:s}),del:({children:s})=>e.jsx("del",{className:"line-through text-slate-400",children:s}),hr:()=>e.jsx("hr",{className:"my-8 border-0 h-px bg-slate-200"}),ul:({children:s})=>e.jsx("ul",{className:"list-disc pl-6 mb-4 space-y-1.5 marker:text-slate-400",children:s}),ol:({children:s})=>e.jsx("ol",{className:"list-decimal pl-6 mb-4 space-y-1.5 marker:text-slate-500",children:s}),li:({children:s,...a})=>{var i,u,p,n;const l=a.node,d=((u=(i=l==null?void 0:l.children)==null?void 0:i[0])==null?void 0:u.type)==="element"&&((n=(p=l==null?void 0:l.children)==null?void 0:p[0])==null?void 0:n.tagName)==="input";return e.jsx("li",{className:`leading-7 ${d?"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-slate-600 rounded-r-lg [&>p]:mb-2 [&>p:last-child]:mb-0",children:s}),a:({href:s,children:a})=>s!=null&&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-slate-200 my-4",loading:"lazy"}),table:({children:s})=>e.jsx("div",{className:"my-5 overflow-x-auto rounded-lg border border-slate-200",children:e.jsx("table",{className:"w-full border-collapse text-sm",children:s})}),thead:({children:s})=>e.jsx("thead",{className:"bg-slate-50 border-b border-slate-200",children:s}),tbody:({children:s})=>e.jsx("tbody",{className:"divide-y divide-slate-100",children:s}),tr:({children:s})=>e.jsx("tr",{className:"hover:bg-slate-50/50 transition-colors",children:s}),th:({children:s})=>e.jsx("th",{className:"px-4 py-2.5 text-left text-xs font-semibold text-slate-600 uppercase tracking-wider",children:s}),td:({children:s})=>e.jsx("td",{className:"px-4 py-2.5 text-slate-700 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-slate-300 text-blue-600 cursor-default"})}),gt=({content:t,className:s="",showLineNumbers:a=!1,stripFrontmatter:l=!1})=>{const d=o.useMemo(()=>Cr(a),[a]),i=o.useMemo(()=>{let u=l?Ws(t):t;return u=vr(u),u=Nr(u),kr(u)},[t,l]);return e.jsx("div",{className:`markdown-body text-slate-700 ${s}`,children:i.map((u,p)=>u.type==="mermaid"?e.jsx(Oa,{code:u.content},`mermaid-${p}`):e.jsx(al,{remarkPlugins:[ll],components:d,children:u.content},`md-${p}`))})},Ka="asd-chat-topics",Sr=50;function Ar(){return Date.now().toString(36)+Math.random().toString(36).substring(2,8)}function Dr(t){const s=t.find(l=>l.role==="user");if(!s)return"新话题";const a=s.content.trim().replace(/\n/g," ");return a.length>30?a.slice(0,30)+"…":a}function Ir(){try{const t=localStorage.getItem(Ka);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s:[]}catch{return[]}}function Rr(t){try{const s=t.slice(0,Sr);localStorage.setItem(Ka,JSON.stringify(s))}catch(s){console.warn("[ChatTopics] localStorage save failed:",s)}}function Ua(){const[t,s]=o.useState(()=>Ir()),[a,l]=o.useState(null),d=o.useRef(t);o.useEffect(()=>{d.current=t},[t]);const i=o.useCallback(x=>{s(c=>{const j=typeof x=="function"?x(c):x;return Rr(j),j})},[]),u=o.useCallback(x=>{const c=Ar(),j={id:c,title:x||"新话题",messages:[],createdAt:Date.now(),updatedAt:Date.now()};return i(w=>[j,...w]),l(c),c},[i]),p=o.useCallback(x=>{i(c=>c.filter(j=>j.id!==x)),l(c=>c===x?null:c)},[i]),n=o.useCallback((x,c)=>{i(j=>{const w=j.findIndex(G=>G.id===x);if(w<0)return j;const C={...j[w],messages:c,updatedAt:Date.now()},E=Dr(c);E!=="新话题"&&(C.title=E);const S=[...j];return S[w]=C,S.splice(w,1),S.unshift(C),S})},[i]),g=o.useCallback(x=>d.current.find(c=>c.id===x),[]),f=o.useCallback(x=>{l(x)},[]),h=t.find(x=>x.id===a)??null;return{topics:t,activeTopicId:a,activeTopic:h,createTopic:u,deleteTopic:p,saveTopic:n,getTopic:g,switchTopic:f,setActiveTopicId:l}}function Tr(t,s){const a=`chatStream.tools.${s}`,l=t(a);return l===a?s:l}function Er(t,s,a){if(!a)return"";switch(s){case"read_project_file":{const l=a.filePath||(Array.isArray(a.filePaths)?a.filePaths[0]:"");if(!l)return"";const d=String(l).split("/").pop()||l,i=Array.isArray(a.filePaths)&&a.filePaths.length>1?t("chatStream.andNFiles",{n:a.filePaths.length}):"";return`${d}${i}`}case"list_project_structure":{const l=a.directory||a.path||"";return l?String(l):""}case"search_project_code":{const l=a.patterns||a.pattern||a.query||"";return Array.isArray(l)?l.slice(0,2).join(", ")+(l.length>2?" …":""):String(l).slice(0,40)}case"semantic_search_code":case"search_knowledge":case"search_recipes":case"search_candidates":{const l=a.query||a.keyword||"";return String(l).slice(0,40)}case"get_class_info":case"get_protocol_info":return a.className||a.name||a.protocolName||"";case"get_file_summary":{const l=a.filePath||"";return l&&String(l).split("/").pop()||""}case"summarize_code":case"analyze_code":{const l=a.language||"";return l?`${l}`:""}case"get_class_hierarchy":return a.rootClass||"";case"check_duplicate":return a.title||"";default:return""}}function ia(t,s,a){const l=Tr(t,s),d=Er(t,s,a);return d?`${l}: ${d}`:l}function Wa(t,s,a){const l=[],d=[];let i="";function u(n){s(g=>g.map(f=>f.id===t?{...f,content:n}:f))}function p(n){switch(n.type){case"step:start":{const g=n.phase==="user"?"":` [${n.phase}]`,f=a("chatStream.stepProgress",{step:n.step,maxSteps:n.maxSteps})+g+"...",h=l.length>0?l.join(`
60
+ `)+`
61
+
62
+ `+f:f;u(h);break}case"tool:start":{l.push(`🔧 ${ia(a,n.tool,n.args)}...`),d.push({tool:n.tool,args:n.args}),u(l.join(`
63
+ `));break}case"tool:end":{const g=l.length-1;if(g>=0){const f=d[g]||{tool:n.tool},h=ia(a,f.tool,f.args);if(n.status==="error"||n.error)l[g]=`❌ ${h} ${a("chatStream.toolFailed")} (${n.duration}ms)`;else{const x=n.resultSize>1e3?`${(n.resultSize/1024).toFixed(1)}KB`:a("chatStream.toolResultChars",{size:n.resultSize});l[g]=`✅ ${h} → ${x} (${n.duration}ms)`}u(l.join(`
64
+ `))}break}case"text:start":{i="";break}case"text:delta":{i+=n.delta||"";const g=l.length>0?l.join(`
65
+ `)+`
66
+
67
+ ---
68
+
69
+ `:"";u(g+i);break}}}return{onEvent:p,getState:()=>({answerText:i,toolLogs:l})}}const Va=o.createContext({openChat:()=>{},openRefine:()=>{},close:()=>{},toggle:()=>{},newTopic:()=>{},isOpen:!1}),ds=()=>o.useContext(Va),$t=()=>Math.random().toString(36).substring(2,10),Pr=[{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(`
70
+ `):String(t||"")},{key:"relations",labelKey:"globalChat.refineFields.relations",format:t=>JSON.stringify(t||{},null,2)}];function Lr(t,s,a){const l=[];for(const d of Pr){const i=d.format||(n=>String(n??"")),u=i(t[d.key]),p=i(s[d.key]);p&&p!==u&&l.push({field:d.key,label:a(d.labelKey),before:u,after:p})}return l}function ca(t){var s,a,l,d;return{title:t.title||"",description:t.description||"",pattern:((s=t.content)==null?void 0:s.pattern)||"",markdown:((a=t.content)==null?void 0:a.markdown)||"",rationale:((l=t.content)==null?void 0:l.rationale)||"",tags:t.tags||[],confidence:((d=t.reasoning)==null?void 0:d.confidence)??.6,relations:t.relations||{},aiInsight:t.aiInsight||null,agentNotes:t.agentNotes||null}}const Mr=({diff:t,excludedFields:s=[],onToggleField:a})=>{const{t:l}=_e();return t.length===0?e.jsx("p",{className:"text-xs text-slate-400 italic py-2",children:l("globalChat.diff.noChanges")}):e.jsx("div",{className:"space-y-2 mt-2",children:t.map(d=>{const i=s.includes(d.field);return e.jsxs("div",{className:`border rounded-lg overflow-hidden transition-opacity ${i?"border-slate-100 opacity-45":"border-slate-200"}`,children:[e.jsxs("div",{className:`px-2.5 py-1.5 border-b flex items-center gap-1.5 ${i?"bg-slate-50/50 border-slate-100":"bg-slate-50 border-slate-200"}`,children:[e.jsx(Ta,{size:10,className:i?"text-slate-300":"text-emerald-500"}),e.jsx("span",{className:`text-[10px] font-bold flex-1 ${i?"text-slate-400 line-through":"text-slate-600"}`,children:d.label}),a&&(i?e.jsx("button",{onClick:()=>a(d.field),className:"px-2 py-0.5 text-[9px] font-bold rounded-full bg-slate-200 text-slate-500 hover:bg-emerald-100 hover:text-emerald-600 transition-colors",title:l("globalChat.diff.excludedRestore"),children:l("globalChat.diff.excludedRestore")}):e.jsxs("button",{onClick:()=>a(d.field),className:"group flex items-center gap-0.5 px-1.5 py-0.5 text-[9px] font-medium rounded-full text-slate-400 hover:bg-red-50 hover:text-red-500 transition-colors",title:l("globalChat.diff.exclude"),children:[e.jsx(Xe,{size:10,className:"opacity-60 group-hover:opacity-100"}),l("globalChat.diff.exclude")]}))]}),!i&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"p-2 bg-red-50/30 border-b border-slate-200",children:[e.jsx("div",{className:"text-[9px] font-bold text-red-400 mb-0.5 uppercase",children:l("globalChat.diff.before")}),e.jsx("pre",{className:"text-[11px] text-slate-600 whitespace-pre-wrap break-words max-h-40 overflow-auto font-mono leading-relaxed scrollbar-light",children:d.before||e.jsx("span",{className:"italic text-slate-300",children:l("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:l("globalChat.diff.after")}),e.jsx("pre",{className:"text-[11px] text-slate-700 whitespace-pre-wrap break-words max-h-40 overflow-auto font-mono leading-relaxed scrollbar-light",children:d.after})]})]})]},d.field)})})},Ja=o.createContext(null),Fr=({children:t})=>{const{t:s}=_e(),[a,l]=o.useState(!1),[d,i]=o.useState([]),[u,p]=o.useState(!1),[n,g]=o.useState(!1),[f,h]=o.useState(null),[x,c]=o.useState(new Set),[j,w]=o.useState(""),C=o.useRef([]),E=!!f,S=f?f.candidateIds[f.currentIdx]:null,G=f?f.candidates.find(_=>_.id===S):void 0,z=f?f.candidateIds.length>1:!1;o.useEffect(()=>{f&&G&&(i(_=>[..._,{id:$t(),role:"system",content:s("globalChat.system.refinePrefix",{title:G.title,description:G.description||s("globalChat.system.noDescription")}),timestamp:Date.now()}]),w(""))},[f==null?void 0:f.currentIdx]);const P=o.useCallback(()=>{h(null),l(!0)},[]),Z=o.useCallback(_=>{h({..._,currentIdx:0}),c(new Set),i([]),C.current=[],l(!0)},[]),X=o.useCallback(()=>l(!1),[]),H=o.useCallback(()=>l(_=>!_),[]),q=o.useCallback(()=>{i([]),C.current=[],w(""),h(null),c(new Set)},[]),R={openChat:P,openRefine:Z,close:X,toggle:H,newTopic:q,isOpen:a},M={messages:d,setMessages:i,loading:u,setLoading:p,applying:n,setApplying:g,refineCtx:f,setRefineCtx:h,applied:x,setApplied:c,lastPrompt:j,setLastPrompt:w,chatHistoryRef:C,isRefineMode:E,currentRefineId:S,currentRefineCandidate:G,isBatchRefine:z,close:X};return e.jsx(Va.Provider,{value:R,children:e.jsx(Ja.Provider,{value:M,children:t})})},zr=()=>{const{t,lang:s}=_e(),a=o.useContext(Ja),{messages:l,setMessages:d,loading:i,setLoading:u,applying:p,setApplying:n,refineCtx:g,setRefineCtx:f,applied:h,setApplied:x,lastPrompt:c,setLastPrompt:j,chatHistoryRef:w,isRefineMode:C,currentRefineId:E,currentRefineCandidate:S,isBatchRefine:G,close:z}=a,P=o.useRef(null),Z=o.useRef(null),[X,H]=o.useState(""),q=Ua(),R=o.useRef(null),M=o.useRef(!1);o.useEffect(()=>{if(C&&S){M.current=!0;const v=q.createTopic(t("globalChat.refineTopicPrefix",{title:S.title||t("globalChat.untitled")}));R.current=v,setTimeout(()=>{M.current=!1},50)}},[g]),o.useEffect(()=>{M.current||R.current&&l.length>0&&q.saveTopic(R.current,l)},[l]);const _=o.useCallback(()=>{if(!R.current){M.current=!0;const v=q.createTopic();R.current=v,setTimeout(()=>{M.current=!1},50)}},[q]);o.useEffect(()=>{var v;(v=P.current)==null||v.scrollIntoView({behavior:"smooth"})},[l,i]),o.useEffect(()=>{setTimeout(()=>{var v;return(v=Z.current)==null?void 0:v.focus()},200)},[]);const m=C&&E&&l.some(v=>{if(v.role!=="assistant"||!v.diff||v.diff.length===0)return!1;const ee=v.excludedFields||[];return v.diff.some(ae=>!ee.includes(ae.field))})&&!h.has(E),N=o.useCallback((v,ee)=>{d(ae=>ae.map(ue=>{if(ue.id!==v)return ue;const fe=ue.excludedFields||[],he=fe.includes(ee)?fe.filter(ce=>ce!==ee):[...fe,ee];return{...ue,excludedFields:he}}))},[]),y=o.useRef(null),W=o.useCallback(async()=>{const v=X.trim();if(!(!v||i)){if(C||_(),H(""),d(ee=>[...ee,{id:$t(),role:"user",content:v,timestamp:Date.now()}]),u(!0),C&&E){j(v);const ee=$t();d(ue=>[...ue,{id:ee,role:"assistant",content:t("globalChat.system.refining"),timestamp:Date.now()}]);const ae=new AbortController;y.current=ae;try{const ue=await se.refinePreviewStream(E,v,ce=>{if(ce.type==="data:progress"){const je=ce.message||ce.stage||t("globalChat.system.processing");d($=>$.map(K=>K.id===ee?{...K,content:`🔄 ${je}`}:K))}},ae.signal),fe=ue.before||(S?ca(S):{}),he=Lr(fe,ue.after||{},t);d(ce=>ce.map(je=>je.id===ee?{...je,content:he.length>0?t("globalChat.previewGenerated",{count:he.length}):t("globalChat.noChangeHint"),diff:he.length>0?he:void 0,preview:he.length>0?ue.preview??void 0:void 0,excludedFields:[]}:je))}catch(ue){ue.name==="AbortError"?d(fe=>fe.map(he=>he.id===ee?{...he,content:t("globalChat.system.cancelled")}:he)):d(fe=>fe.map(he=>{var ce,je;return he.id===ee?{...he,content:t("globalChat.refinePreviewFailed",{error:((je=(ce=ue.response)==null?void 0:ce.data)==null?void 0:je.error)||ue.message})}:he}))}finally{y.current=null}}else{w.current.push({role:"user",content:v});const ee=$t();d(ce=>[...ce,{id:ee,role:"assistant",content:t("globalChat.system.thinking"),timestamp:Date.now()}]);const ae=new AbortController;y.current=ae;const{onEvent:ue,getState:fe}=Wa(ee,d,t);let he="";try{const je=(await se.chatStream(v,w.current,$=>{ue($),he=fe().answerText},ae.signal,s)).text||he;w.current.push({role:"model",content:je}),d($=>$.map(K=>K.id===ee?{...K,content:je}:K))}catch(ce){if(ce.name==="AbortError"){const{answerText:je,toolLogs:$}=fe(),K=je||($.length>0?$.join(`
71
+ `)+`
72
+
73
+ `+t("globalChat.system.cancelled"):t("globalChat.system.cancelled"));je&&w.current.push({role:"model",content:je}),d(xe=>xe.map(L=>L.id===ee?{...L,content:K}:L))}else d(je=>je.map($=>$.id===ee?{...$,content:t("globalChat.requestFailed",{error:ce.message})}:$))}finally{y.current=null}}u(!1)}},[X,i,C,E,S,_]),O=o.useCallback(async()=>{var v,ee,ae,ue;if(!(p||!E||!g)){n(!0);try{const fe=[...l].reverse().find(ce=>ce.role==="assistant"&&ce.preview);let he=fe==null?void 0:fe.preview;if(he&&((v=fe==null?void 0:fe.excludedFields)!=null&&v.length)&&fe.diff){he={...he};const ce=S?ca(S):{};for(const je of fe.excludedFields)je in ce&&(he[je]=ce[je])}await se.refineApply(E,c,he),x(ce=>new Set(ce).add(E)),(ee=g.onCandidateUpdated)==null||ee.call(g,E),d(ce=>[...ce,{id:$t(),role:"system",content:t("globalChat.system.changesApplied"),timestamp:Date.now()}]),re(t("globalChat.applySuccess"),{title:t("globalChat.applySuccessTitle")})}catch(fe){const he=(ue=(ae=fe.response)==null?void 0:ae.data)==null?void 0:ue.error;re(typeof he=="string"?he:(he==null?void 0:he.message)||fe.message,{title:t("globalChat.applyFailed"),type:"error"})}finally{n(!1)}}},[p,E,c,g]),be=o.useCallback(()=>{!g||g.currentIdx>=g.candidateIds.length-1||f(v=>v?{...v,currentIdx:v.currentIdx+1}:null)},[g]),we=o.useCallback(()=>{R.current=null,f(null),d(v=>[...v,{id:$t(),role:"system",content:t("globalChat.system.exitedRefine"),timestamp:Date.now()}])},[]),ye=o.useCallback(v=>{v.key==="Enter"&&!v.shiftKey&&(v.preventDefault(),W())},[W]);return e.jsxs("aside",{className:"w-[420px] h-full bg-white border-l border-slate-200 flex flex-col shrink-0",children:[e.jsxs("div",{className:"px-4 py-2.5 border-b border-slate-200 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:C?e.jsx(Qe,{className:"text-emerald-500",size:16}):e.jsx(Lt,{className:"text-blue-600",size:16})}),e.jsxs("div",{children:[e.jsxs("h3",{className:"text-[13px] font-bold text-slate-800 flex items-center gap-2",children:[t(C?"globalChat.refineTitle":"globalChat.chatTitle"),C&&G&&e.jsxs("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-emerald-50 text-emerald-600 font-medium",children:[((g==null?void 0:g.currentIdx)??0)+1,"/",g==null?void 0:g.candidateIds.length]})]}),e.jsx("p",{className:"text-[10px] text-slate-400 truncate max-w-[250px]",children:C?(S==null?void 0:S.title)||t("globalChat.refineSubtitle"):t("globalChat.chatSubtitle")})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[C&&e.jsx("button",{onClick:we,className:"px-2 py-1 text-[10px] font-medium text-slate-500 hover:text-slate-700 hover:bg-slate-100 rounded-md transition-colors",children:t("globalChat.exitRefine")}),!C&&l.length>0&&e.jsx("button",{onClick:()=>{R.current=null,d([]),w.current=[],j("")},className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors",title:t("globalChat.newTopic"),children:e.jsx(Nt,{size:16,className:"text-slate-400"})}),e.jsx("button",{onClick:z,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors",title:t("globalChat.closeChat"),children:e.jsx(Xe,{size:16,className:"text-slate-400"})})]})]}),C&&S&&e.jsx("div",{className:"border-b border-slate-100 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:S.title}),S.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:S.language})]})}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-3 min-h-0 scrollbar-light",children:[l.length===0&&!C&&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(Lt,{className:"text-blue-500",size:20})}),e.jsx("h4",{className:"text-sm font-bold text-slate-700 mb-1",children:t("globalChat.emptyTitle")}),e.jsx("p",{className:"text-xs text-slate-400 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(v=>e.jsx("button",{onClick:()=>{var ee;H(v),(ee=Z.current)==null||ee.focus()},className:"text-[10px] px-2.5 py-1 rounded-md bg-slate-100 text-slate-600 hover:bg-blue-50 hover:text-blue-700 transition-colors",children:v},v))})]}),C&&l.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(v=>e.jsx("button",{onClick:()=>{var ee;H(v),(ee=Z.current)==null||ee.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:v},v))}),l.map(v=>e.jsx("div",{className:`flex ${v.role==="user"?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[95%] ${v.role==="user"?"bg-blue-600 text-white rounded-2xl rounded-tr-md px-3.5 py-2":v.role==="system"?"bg-slate-50 border border-slate-200 text-slate-600 rounded-2xl px-3.5 py-2 w-full":"bg-white border border-slate-200 rounded-2xl rounded-tl-md px-3.5 py-2.5 shadow-sm w-full"}`,children:[v.role==="assistant"&&e.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[e.jsx(rs,{size:12,className:C?"text-emerald-500":"text-blue-500"}),e.jsx("span",{className:`text-[10px] font-bold ${C?"text-emerald-600":"text-blue-600"}`,children:t(C?"globalChat.assistantRefine":"globalChat.assistantChat")})]}),v.role==="assistant"&&!v.diff?e.jsx(gt,{content:v.content,className:"text-xs text-slate-700"}):e.jsx("p",{className:`text-xs leading-relaxed whitespace-pre-wrap ${v.role==="user"?"":v.role==="system"?"text-slate-500":"text-slate-700"}`,children:v.content}),v.diff&&v.diff.length>0&&e.jsx(Mr,{diff:v.diff,excludedFields:v.excludedFields,onToggleField:C&&!h.has(E)?ee=>N(v.id,ee):void 0})]})},v.id)),i&&e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"bg-white border border-slate-200 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(Fe,{size:12,className:`animate-spin ${C?"text-emerald-500":"text-blue-500"}`}),e.jsx("span",{className:"text-xs text-slate-500",children:t(C?"globalChat.loading.analyzing":"globalChat.loading.thinking")}),y.current&&e.jsx("button",{onClick:()=>{var v;return(v=y.current)==null?void 0:v.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:P})]}),C&&m&&!i&&(()=>{var fe,he;const v=[...l].reverse().find(ce=>ce.role==="assistant"&&ce.diff&&ce.diff.length>0),ee=((fe=v==null?void 0:v.diff)==null?void 0:fe.length)||0,ae=((he=v==null?void 0:v.excludedFields)==null?void 0:he.length)||0,ue=ee-ae;return e.jsxs("div",{className:"px-4 py-2 border-t border-slate-100 bg-emerald-50/50 flex items-center gap-2 shrink-0",children:[e.jsxs("button",{onClick:O,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(Fe,{size:11,className:"animate-spin"}):e.jsx(kt,{size:11}),p?t("globalChat.applyingBtn"):ae>0?t("globalChat.confirmApplyN",{i:ue,total:ee}):t("globalChat.confirmApply")]}),e.jsxs("button",{className:"flex items-center gap-1 px-2.5 py-1.5 text-[11px] font-bold text-slate-500 hover:text-slate-700 rounded-lg hover:bg-slate-100 transition-colors",children:[e.jsx(Ra,{size:11})," ",t("globalChat.continueAdjust")]}),G&&h.has(E)&&g.currentIdx<g.candidateIds.length-1&&e.jsxs("button",{onClick:be,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(rt,{size:11})]})]})})(),C&&!m&&!i&&G&&h.has(E)&&g.currentIdx<g.candidateIds.length-1&&e.jsx("div",{className:"px-4 py-2 border-t border-slate-100 flex items-center justify-center shrink-0",children:e.jsxs("button",{onClick:be,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==null?void 0:g.currentIdx)??0)+2,"/",g==null?void 0:g.candidateIds.length,") ",e.jsx(rt,{size:12})]})}),e.jsxs("div",{className:"px-4 py-2.5 border-t border-slate-200 bg-white shrink-0",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx("textarea",{ref:Z,value:X,onChange:v=>H(v.target.value),onKeyDown:ye,placeholder:t(C?"globalChat.refinePlaceholder":"globalChat.chatPlaceholder"),rows:2,className:`flex-1 px-3 py-2 text-sm border border-slate-200 rounded-xl focus:outline-none focus:ring-2 ${C?"focus:ring-emerald-200 focus:border-emerald-400":"focus:ring-blue-200 focus:border-blue-400"} resize-none placeholder:text-slate-300`,disabled:i||p}),e.jsx("button",{onClick:W,disabled:!X.trim()||i||p,className:`self-stretch w-9 flex items-center justify-center rounded-xl bg-gradient-to-r ${C?"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(Bs,{size:14})})]}),e.jsx("p",{className:"text-[9px] text-slate-400 mt-1",children:t(C?"globalChat.inputHintRefine":"globalChat.inputHintChat")})]})]})},_r=({searchQuery:t,setSearchQuery:s,setShowCreateModal:a,handleSyncSnippets:l,aiConfig:d,llmReady:i=!0,onOpenLlmConfig:u,onSemanticSearchResults:p,onBeforeAiSwitch:n,onAiConfigChange:g})=>{const{toggle:f,isOpen:h}=ds(),{t:x,lang:c,setLang:j}=_e(),{isDark:w,toggle:C}=St(),[E,S]=o.useState(!1),[G,z]=o.useState(!1),[P,Z]=o.useState([]),[X,H]=o.useState(!1),q=o.useRef(null);o.useEffect(()=>{G&&P.length===0&&se.getAiProviders().then(_=>Z(_)).catch(()=>{})},[G,P.length]),o.useEffect(()=>{const _=m=>{q.current&&!q.current.contains(m.target)&&z(!1)};return document.addEventListener("click",_),()=>document.removeEventListener("click",_)},[]);const R=async()=>{if(t){S(!0);try{const m=((await se.search(t,{mode:"semantic"})).items||[]).map(N=>{var y,W,O;return{name:(N.title||N.name||"")+".md",content:((y=N.content)==null?void 0:y.pattern)||((W=N.content)==null?void 0:W.markdown)||((O=N.content)==null?void 0:O.code)||"",similarity:N.score||0,metadata:{type:"recipe",name:(N.title||N.name||"")+".md"}}});p&&p(m)}catch(_){console.error("Semantic search failed",_),alert(x("header.semanticSearchFailed"))}finally{S(!1)}}},M=async _=>{H(!0);try{n==null||n(),await se.setAiConfig(_.id,_.defaultModel),z(!1),g&&g()}catch(m){console.error("AI config update failed",m),alert(x("header.aiSwitchFailed"))}finally{H(!1)}};return e.jsxs("header",{className:`h-16 ${w?"bg-[#252526] border-b border-[#3e3e42]":"bg-white border-b border-slate-200"} flex items-center justify-between px-8 shrink-0`,children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"relative w-96",children:[e.jsx(ft,{className:`absolute left-3 top-1/2 -translate-y-1/2 ${w?"text-slate-500":"text-slate-400"}`,size:F.md}),e.jsx("input",{type:"text",placeholder:x("header.searchPlaceholder"),className:`w-full pl-10 pr-4 py-2 ${w?"bg-[#1e1e1e] text-slate-300 placeholder-slate-500":"bg-slate-100 text-slate-900"} border-transparent rounded-lg text-sm outline-none focus:ring-2 focus:ring-blue-500/20 transition-all`,value:t,onChange:_=>s(_.target.value),onKeyDown:_=>_.key==="Enter"&&R()})]}),e.jsxs("button",{onClick:R,disabled:!t||E,className:`flex items-center gap-2 px-3 py-2 rounded-lg text-xs font-bold transition-all ${E?w?"bg-blue-900/30 text-blue-300":"bg-blue-50 text-blue-400":w?"bg-blue-900/30 text-blue-400 hover:bg-blue-900/50":"bg-blue-50 text-blue-600 hover:bg-blue-100"}`,title:x("header.semanticSearchTitle"),children:[E?e.jsx(Fe,{size:F.sm,className:"animate-spin"}):e.jsx(jl,{size:F.sm}),x("header.semanticSearch")]})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[i?d?e.jsxs("div",{className:"relative",ref:q,children:[e.jsxs("button",{type:"button",onClick:_=>{_.stopPropagation(),z(m=>!m)},className:`flex items-center gap-2 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${w?"bg-slate-700 text-slate-300 hover:bg-slate-600":"bg-slate-100 text-slate-600 hover:bg-slate-200"}`,title:x("header.clickSwitchAi"),children:[e.jsx(ns,{size:F.sm}),d.provider," / ",d.model,e.jsx(Gt,{size:F.xs,className:G?"rotate-180":""})]}),G&&e.jsxs("div",{className:`absolute top-full right-0 mt-1 py-1 rounded-lg border shadow-lg z-20 min-w-[200px] ${w?"bg-[#252526] border-[#3e3e42]":"bg-white border-slate-200"}`,children:[e.jsx("div",{className:`px-3 py-2 text-xs border-b ${w?"text-slate-400 border-[#3e3e42]":"text-slate-500 border-slate-100"}`,children:x("header.switchAi")}),e.jsx("div",{className:`px-3 py-1.5 text-[11px] border-b ${w?"text-slate-500 border-[#3e3e42]":"text-slate-400 border-slate-100"}`,children:e.jsx("button",{type:"button",onClick:()=>{z(!1),u==null||u()},className:"text-blue-500 hover:underline",children:x("header.editEnvConfig")})}),P.length===0?e.jsx("div",{className:`px-3 py-2 text-xs ${w?"text-slate-500":"text-slate-400"}`,children:x("common.loading")}):P.map(_=>e.jsxs("button",{type:"button",disabled:X,onClick:()=>M(_),className:`w-full text-left px-3 py-2 text-sm flex items-center justify-between ${d.provider===_.id?w?"bg-blue-900/30 text-blue-400 font-medium":"bg-blue-50 text-blue-700 font-medium":w?"text-slate-300 hover:bg-slate-700/50":"text-slate-700 hover:bg-slate-50"}`,children:[e.jsx("span",{children:_.label}),d.provider===_.id&&e.jsx("span",{className:"text-xs",children:"✓"})]},_.id))]})]}):null:e.jsxs("button",{type:"button",onClick:u,className:`flex items-center gap-2 px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors animate-pulse ${w?"bg-amber-900/30 text-amber-300 border-amber-700 hover:bg-amber-900/50":"bg-amber-50 text-amber-700 border-amber-200 hover:bg-amber-100"}`,title:x("header.aiNotConfigured"),children:[e.jsx(Ea,{size:F.sm}),x("header.configureLlm")]}),e.jsxs("button",{onClick:f,className:`flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-medium transition-all duration-150 ${h?w?"bg-blue-500/20 text-blue-300 ring-1 ring-blue-500/30 hover:bg-blue-500/35 hover:brightness-125":"bg-blue-100 text-blue-700 ring-1 ring-blue-200 hover:bg-blue-200":w?"bg-slate-700 text-slate-300 hover:bg-slate-500 hover:text-white":"bg-slate-100 text-slate-600 hover:bg-slate-200"}`,title:x(h?"header.closeAiChat":"header.openAiChat"),children:[e.jsx(Lt,{size:F.sm}),!h&&e.jsx("span",{className:"text-xs",children:x("header.aiChat")})]}),e.jsxs("button",{onClick:()=>a(!0),className:`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all duration-150 border ${w?"bg-slate-200 text-slate-900 border-slate-300 hover:bg-white hover:border-white hover:shadow-[0_0_12px_rgba(255,255,255,0.15)]":"bg-slate-900 text-white border-slate-900 hover:bg-slate-800 hover:border-slate-800"}`,children:[e.jsx(Nt,{size:F.md})," ",x("header.newRecipe")]}),e.jsxs("button",{onClick:l,className:`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all duration-150 border ${w?"bg-blue-500/20 text-blue-300 border-blue-500/30 hover:bg-blue-500/40 hover:text-blue-200 hover:border-blue-400/50":"bg-blue-600 text-white border-blue-600 hover:bg-blue-700 hover:border-blue-700"}`,children:[e.jsx(yt,{size:F.md})," ",x("header.syncSnippets")]}),e.jsxs("button",{onClick:()=>j(c==="zh"?"en":"zh"),className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium transition-all duration-150 ${w?"bg-slate-700 text-slate-300 hover:bg-slate-500 hover:text-white":"bg-slate-100 text-slate-600 hover:bg-slate-200"}`,title:c==="zh"?"Switch to English":x("shared.switchToChinese"),children:[e.jsx(vl,{size:F.sm}),x("header.langSwitch")]}),e.jsx("button",{onClick:C,className:`flex items-center p-2 rounded-lg transition-all duration-150 ${w?"bg-slate-700 text-amber-300 hover:bg-slate-500 hover:text-amber-200":"bg-slate-100 text-slate-600 hover:bg-slate-200"}`,title:w?"Light mode":"Dark mode",children:w?e.jsx(Nl,{size:F.sm}):e.jsx(wl,{size:F.sm})})]})]})},$r=({selectedCategory:t,setSelectedCategory:s})=>e.jsx("div",{className:"bg-white border-b border-slate-100 shrink-0 overflow-hidden",children:e.jsx("div",{className:"flex items-center gap-2 overflow-x-auto no-scrollbar px-8 py-3",children:Object.entries(ct).map(([a,l])=>{const d=l.icon,i=t===a;return e.jsxs("button",{onClick:()=>s(a),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-[10px] font-bold transition-all border whitespace-nowrap
74
+ ${i?`${l.bg} ${l.color} ${l.border} shadow-sm scale-105`:"bg-white text-slate-400 border-slate-100 hover:border-slate-200 hover:text-slate-600"}`,children:[e.jsx(d,{size:F.xs}),a]},a)})})}),Ya="asd-drawer-wide";function Br(){try{return localStorage.getItem(Ya)==="1"}catch{return!1}}function Vs(){const[t,s]=o.useState(Br),a=o.useCallback(()=>{s(l=>{const d=!l;try{localStorage.setItem(Ya,d?"1":"0")}catch{}return d})},[]);return{isWide:t,toggle:a}}const Js=({currentPage:t,totalPages:s,totalItems:a,pageSize:l,onPageChange:d,onPageSizeChange:i,pageSizeOptions:u=[12,24,48,96]})=>{if(s<=1&&a<=u[0])return null;const{t:p}=_e(),n=(t-1)*l+1,g=Math.min(t*l,a),f=()=>{const h=[];if(s<=7)for(let c=1;c<=s;c++)h.push(c);else if(t<=3){for(let c=1;c<=5;c++)h.push(c);h.push("..."),h.push(s)}else if(t>=s-2){h.push(1),h.push("...");for(let c=s-5+1;c<=s;c++)h.push(c)}else{h.push(1),h.push("...");for(let c=t-1;c<=t+1;c++)h.push(c);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-slate-500",children:p("pagination.showing",{start:n,end:g,total:a})}),i&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-slate-500",children:p("pagination.perPage")}),e.jsx("select",{value:l,onChange:h=>i(Number(h.target.value)),className:"text-sm border border-slate-200 rounded-md px-2 py-1 bg-white focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent",children:u.map(h=>e.jsx("option",{value:h,children:h},h))}),e.jsx("span",{className:"text-sm text-slate-500",children:p("pagination.unit")})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>d(1),disabled:t===1,className:"p-1.5 rounded-md hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:p("pagination.firstPage"),children:e.jsx(kl,{size:F.md,className:"text-slate-600"})}),e.jsx("button",{onClick:()=>d(t-1),disabled:t===1,className:"p-1.5 rounded-md hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:p("pagination.prevPage"),children:e.jsx(is,{size:F.md,className:"text-slate-600"})}),e.jsx("div",{className:"flex items-center gap-1 mx-2",children:f().map((h,x)=>typeof h=="number"?e.jsx("button",{onClick:()=>d(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-slate-100 text-slate-600"}`,children:h},x):e.jsx("span",{className:"px-1 text-slate-400",children:h},x))}),e.jsx("button",{onClick:()=>d(t+1),disabled:t===s,className:"p-1.5 rounded-md hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:p("pagination.nextPage"),children:e.jsx(rt,{size:F.md,className:"text-slate-600"})}),e.jsx("button",{onClick:()=>d(s),disabled:t===s,className:"p-1.5 rounded-md hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:p("pagination.lastPage"),children:e.jsx(Cl,{size:F.md,className:"text-slate-600"})})]})]})},Gr=Ct.memo(({code:t,lang:s,editorStyles:a})=>e.jsx(ka,{language:s,style:Ca,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 l=t;return l[l.length-1]===`
75
+ `?l+" ":l})()})),ps=19.5,Hr=Ct.memo(({totalLines:t,scrollTop:s,viewportHeight:a,fontSize:l,lineHeight:d,fontFamily:i})=>{const p=Math.max(0,Math.floor(s/ps)-10),n=Math.ceil(a/ps)+20,g=Math.min(t,p+n),f=p*ps,h=Math.max(0,(t-g)*ps),x=[];for(let c=p;c<g;c++)x.push(e.jsx("div",{children:c+1},c));return e.jsx("div",{style:{paddingTop:f,paddingBottom:h,fontSize:l,lineHeight:d,fontFamily:i},children:x})}),ks=({value:t,onChange:s,onCursorChange:a,language:l="javascript",height:d="400px",className:i="",placeholder:u="",rows:p,showLineNumbers:n=!0})=>{const g=o.useRef(null),f=o.useRef(null),h=o.useRef(null),x=o.useRef(null),[c,j]=o.useState(t),w=o.useRef(void 0);o.useEffect(()=>{const q=t.length>5e3?200:t.length>1e3?80:0;if(q===0){j(t);return}return w.current=setTimeout(()=>j(t),q),()=>clearTimeout(w.current)},[t]);const[C,E]=o.useState({top:0,height:400}),G={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"}[l==null?void 0:l.toLowerCase()]||(l==null?void 0:l.toLowerCase())||"text",z=o.useMemo(()=>({padding:"1rem 1.25rem",fontSize:"0.8125rem",lineHeight:1.5,fontFamily:"ui-monospace, monospace",minHeight:"200px"}),[]),P=o.useCallback(q=>{const R=q.currentTarget;h.current&&(h.current.scrollTop=R.scrollTop,h.current.scrollLeft=R.scrollLeft),x.current&&(x.current.scrollTop=R.scrollTop),E({top:R.scrollTop,height:R.clientHeight})},[]),Z=o.useCallback(q=>{s(q.target.value),a&&a(q.target.selectionStart||0)},[s,a]),X=o.useCallback(q=>{a&&a(q.currentTarget.selectionStart||0)},[a]),H=o.useMemo(()=>(t||"").split(`
76
+ `).length,[t]);return o.useEffect(()=>{f.current&&E(q=>({...q,height:f.current.clientHeight}))},[]),e.jsxs("div",{ref:g,className:`relative overflow-hidden ${i}`,style:{height:p?"auto":d,minHeight:z.minHeight,display:"flex",borderRadius:"0",backgroundColor:"#282c34"},children:[n&&e.jsx("div",{ref:x,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(Hr,{totalLines:H,scrollTop:C.top,viewportHeight:C.height,fontSize:z.fontSize,lineHeight:z.lineHeight,fontFamily:z.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(Gr,{code:c||u,lang:G,editorStyles:z})}),e.jsx("textarea",{ref:f,value:t,onChange:Z,onSelect:X,onKeyUp:X,onClick:X,onScroll:P,rows:p,placeholder:u,className:"absolute inset-0 w-full h-full resize-none outline-none editor-with-dark-scrollbar",style:{padding:z.padding,lineHeight:z.lineHeight,fontSize:z.fontSize,fontFamily:z.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"}})]})]})},qr=420,Or=({className:t="bg-black/20 backdrop-blur-[1px]"})=>e.jsx("div",{className:`absolute inset-0 ${t}`}),Ze=({children:t,onClick:s,className:a="",style:l})=>{const{isOpen:d}=ds();return e.jsx("div",{className:`fixed inset-0 overflow-hidden ${a}`,style:{right:d?qr:0,...l},onClick:s,children:t})};Ze.Backdrop=Or;const Kr={rule:{label:"Rule",color:"text-red-700",bg:"bg-red-50",border:"border-red-200",icon:ut},pattern:{label:"Pattern",color:"text-violet-700",bg:"bg-violet-50",border:"border-violet-200",icon:jt},fact:{label:"Fact",color:"text-cyan-700",bg:"bg-cyan-50",border:"border-cyan-200",icon:tt}},da={"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 at(t){return(t.name||t.title||"Untitled").replace(/\.md$/i,"")}function Ur(t){const s=t.content;if(!s)return"";if(typeof s=="string")return s;const a=[];return s.pattern&&a.push(s.pattern),s.markdown&&a.push(s.markdown),a.length>0?a.join(`
77
+
78
+ `):JSON.stringify(s,null,2)}function ua(t){var s;return((s=t.content)==null?void 0:s.pattern)||""}function pa(t){const s=(t.language||"").toLowerCase();return["objectivec","objc","objective-c","obj-c"].includes(s)?"objectivec":t.language||"text"}function Qa(t){if(t==null)return!1;const s=typeof t=="string"?new Date(t).getTime():t;return!isNaN(s)&&s>9466848e5}function xa(t){return Qa(t)?(typeof t=="string"?new Date(t):new Date(t)).toLocaleDateString("zh-CN",{year:"numeric",month:"2-digit",day:"2-digit"}):""}const Wr=({recipes:t,handleDeleteRecipe:s,onRefresh:a,idTitleMap:l,currentPage:d,onPageChange:i,pageSize:u,onPageSizeChange:p})=>{const{t:n}=_e(),[g,f]=o.useState("default"),[h,x]=o.useState("desc"),c=[{key:"default",label:n("recipes.sortNewest"),defaultDir:"desc"},{key:"authorityScore",label:n("recipes.qualityAuthorityScore"),defaultDir:"desc"},{key:"authority",label:n("recipes.qualityExcellent"),defaultDir:"desc"},{key:"totalUsage",label:n("recipes.qualityBasic"),defaultDir:"desc"},{key:"lastUsed",label:n("recipes.sortQuality"),defaultDir:"desc"},{key:"name",label:n("recipes.sortAlpha"),defaultDir:"asc"},{key:"category",label:n("recipes.knowledgeType"),defaultDir:"asc"}],[j,w]=o.useState(1),[C,E]=o.useState(12),S=d??j,G=u??C,z=i??w,P=p?r=>p(r):r=>{E(r),w(1)},{isWide:Z,toggle:X}=Vs(),[H,q]=o.useState(null),[R,M]=o.useState("view"),[_,m]=o.useState(""),[N,y]=o.useState({title:"",description:"",markdown:"",codePattern:"",rationale:"",tags:[],tagInput:""}),[W,O]=o.useState(!1),be=o.useRef(!0),[we,ye]=o.useState(!1),[v,ee]=o.useState("related"),[ae,ue]=o.useState("");o.useEffect(()=>()=>{be.current=!1},[]);const fe=[{key:"related",label:n("knowledgeGraph.relationAssociates"),icon:"∼"},{key:"dependsOn",label:n("knowledgeGraph.relationDependsOn"),icon:"⊕"},{key:"inherits",label:n("knowledgeGraph.relationInherits"),icon:"↑"},{key:"implements",label:n("knowledgeGraph.relationImplements"),icon:"◇"},{key:"calls",label:n("knowledgeGraph.relationCalls"),icon:"→"},{key:"dataFlow",label:n("knowledgeGraph.relationDataFlow"),icon:"⇢"},{key:"conflicts",label:n("knowledgeGraph.relationConflicts"),icon:"✕"},{key:"extends",label:n("knowledgeGraph.relationExtends"),icon:"⊃"}],he=r=>{var k,b,B,D;q(r),M("view"),m(Ur(r)),y({title:((k=r.name)==null?void 0:k.replace(/\.md$/,""))||"",description:r.description||"",markdown:((b=r.content)==null?void 0:b.markdown)||"",codePattern:((B=r.content)==null?void 0:B.pattern)||"",rationale:((D=r.content)==null?void 0:D.rationale)||"",tags:r.tags||[],tagInput:""}),ye(!1),ue("")},ce=()=>{q(null),M("view"),ye(!1),ue("")},je=async()=>{if(!(!H||W)){O(!0);try{const r=H.id||H.name;await se.knowledgeUpdate(r,{title:N.title,description:N.description,tags:N.tags,content:{...H.content||{},pattern:N.codePattern,markdown:N.markdown,rationale:N.rationale}}),be.current&&(M("view"),a==null||a())}catch(r){re((r==null?void 0:r.message)||n("common.saveFailed"),{title:n("common.operationFailed"),type:"error"})}finally{be.current&&O(!1)}}},$=async r=>{if(H)try{await se.setRecipeAuthority(H.id||H.name,r),a==null||a()}catch(k){re((k==null?void 0:k.message)||n("common.operationFailed"),{title:n("common.operationFailed"),type:"error"})}},K=r=>{const k=r.replace(/\.md$/i,"").toLowerCase();return t.find(b=>at(b).toLowerCase()===k)},xe=o.useMemo(()=>{const r=new Map;if(l)for(const[k,b]of Object.entries(l))r.set(k,b);for(const k of t)k.id&&r.set(k.id,at(k)),k.name&&r.set(k.name,at(k));return r},[t,l]),L=async(r,k)=>{if(!H)return;const b={};if(H.relations)for(const[U,te]of Object.entries(H.relations))b[U]=[...te];const B=b[r]||[],D=k.replace(/\.md$/i,"");if(!B.some(U=>(typeof U=="string"?U:U.id||U.title||"").replace(/\.md$/i,"").toLowerCase()===D.toLowerCase())){b[r]=[...B,D];try{await se.updateRecipeRelations(H.id||H.name,b),q({...H,relations:b}),ye(!1),ue(""),a==null||a()}catch(U){re((U==null?void 0:U.message)||n("common.operationFailed"),{title:n("common.operationFailed"),type:"error"})}}},T=async(r,k)=>{if(!H)return;const b={};if(H.relations)for(const[D,U]of Object.entries(H.relations))b[D]=[...U];const B=b[r]||[];b[r]=B.filter(D=>(typeof D=="string"?D:D.id||D.title||"").replace(/\.md$/i,"").toLowerCase()!==k.replace(/\.md$/i,"").toLowerCase()),b[r].length===0&&delete b[r];try{await se.updateRecipeRelations(H.id||H.name,b),q({...H,relations:b}),a==null||a()}catch(D){re((D==null?void 0:D.message)||n("common.operationFailed"),{title:n("common.operationFailed"),type:"error"})}};o.useEffect(()=>{H&&!t.find(r=>at(r)===at(H))&&ce()},[t,H]),o.useEffect(()=>{d==null&&w(1)},[t.length,d]);const Q=Ct.useMemo(()=>{if(g==="default")return t;const r=[...t],k=h==="asc"?1:-1;return r.sort((b,B)=>{var te,de,me,I,V,Ce,Ae,Re,Be,Ye,J,Le;let D=0,U=0;switch(g){case"name":return D=at(b).toLowerCase(),U=at(B).toLowerCase(),k*(D<U?-1:D>U?1:0);case"authorityScore":D=((te=b.stats)==null?void 0:te.authorityScore)??-1,U=((de=B.stats)==null?void 0:de.authorityScore)??-1;break;case"authority":D=((me=b.stats)==null?void 0:me.authority)??-1,U=((I=B.stats)==null?void 0:I.authority)??-1;break;case"totalUsage":D=(((V=b.stats)==null?void 0:V.guardUsageCount)??0)+(((Ce=b.stats)==null?void 0:Ce.humanUsageCount)??0)+(((Ae=b.stats)==null?void 0:Ae.aiUsageCount)??0),U=(((Re=B.stats)==null?void 0:Re.guardUsageCount)??0)+(((Be=B.stats)==null?void 0:Be.humanUsageCount)??0)+(((Ye=B.stats)==null?void 0:Ye.aiUsageCount)??0);break;case"lastUsed":{const qe=(J=b.stats)!=null&&J.lastUsedAt?new Date(b.stats.lastUsedAt).getTime():0,ze=(Le=B.stats)!=null&&Le.lastUsedAt?new Date(B.stats.lastUsedAt).getTime():0;D=isNaN(qe)?0:qe,U=isNaN(ze)?0:ze;break}case"category":return D=(b.category||"").toLowerCase(),U=(B.category||"").toLowerCase(),k*(D<U?-1:D>U?1:0)}return k*(D-U)}),r},[t,g,h]),ie=Math.ceil(Q.length/G),ke=(S-1)*G,Ue=Q.slice(ke,ke+G),Ie=r=>{z(r),window.scrollTo({top:0,behavior:"smooth"})},ne=H?Q.findIndex(r=>at(r)===at(H)):-1,ve=()=>{ne>0&&he(Q[ne-1])},He=()=>{ne<Q.length-1&&he(Q[ne+1])},Pe=({recipe:r,compact:k})=>{const b=r.kind?Kr[r.kind]:null,B=(b==null?void 0:b.icon)||nt,D=r.category||"Utility",U=ct[D]||ct.Utility,te=U.icon,de=r.knowledgeType,me=k?"text-[8px]":"text-[9px]";return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[b&&e.jsxs("span",{className:`${me} font-bold px-1.5 py-0.5 rounded uppercase flex items-center gap-1 border ${b.bg} ${b.color} ${b.border}`,children:[e.jsx(B,{size:k?9:10}),b.label]}),e.jsxs("span",{className:`${me} font-bold px-1.5 py-0.5 rounded uppercase flex items-center gap-1 border ${U.bg} ${U.color} ${U.border}`,children:[e.jsx(te,{size:k?9:10}),D]}),de&&e.jsx("span",{className:`${me} font-medium px-1.5 py-0.5 rounded bg-indigo-50 text-indigo-600 border border-indigo-100`,children:da[de]?n(da[de]):de}),r.language&&e.jsx("span",{className:`${me} font-medium px-1.5 py-0.5 rounded bg-slate-100 text-slate-500 uppercase`,children:r.language}),r.trigger&&e.jsx("span",{className:`${me} font-mono font-bold px-1.5 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100`,children:r.trigger})]})},Ne=({recipe:r})=>{const k=[];return r.scope&&k.push({icon:Pt,iconClass:"text-teal-400",label:n("candidates.path"),value:r.scope==="universal"?n("common.all"):r.scope==="project-specific"?n("candidates.category"):r.scope}),r.complexity&&k.push({icon:lt,iconClass:"text-orange-400",label:n("candidates.category"),value:r.complexity==="advanced"?n("candidates.confidenceHigh"):r.complexity==="intermediate"?n("candidates.confidenceMedium"):r.complexity==="basic"?n("candidates.confidenceLow"):r.complexity}),r.difficulty&&r.difficulty!==r.complexity&&k.push({icon:lt,iconClass:"text-amber-400",label:n("candidates.category"),value:r.difficulty}),r.moduleName&&k.push({icon:lt,iconClass:"text-purple-400",label:n("candidates.category"),value:r.moduleName,mono:!0}),r.source&&r.source!=="unknown"&&k.push({icon:Pt,iconClass:"text-violet-400",label:n("recipes.sourceLabel"),value:r.source==="bootstrap-scan"?n("recipes.sourceBootstrap"):r.source==="agent"?n("recipes.sourceAiScan"):r.source}),r.version&&k.push({icon:as,iconClass:"text-slate-400",label:n("candidates.language"),value:r.version}),r.updatedAt&&Qa(r.updatedAt)&&k.push({icon:as,iconClass:"text-slate-400",label:n("candidates.updatedAt"),value:xa(r.updatedAt)}),k.length===0&&!r.sourceFile?null:e.jsxs("div",{className:"flex flex-wrap gap-x-5 gap-y-2 text-xs",children:[k.map((b,B)=>{const D=b.icon;return e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(D,{size:11,className:`${b.iconClass} shrink-0`}),e.jsx("span",{className:"text-slate-400",children:b.label}),e.jsx("span",{className:`font-medium text-slate-600 ${b.mono?"font-mono text-[11px]":""}`,children:b.value})]},B)}),r.sourceFile&&e.jsxs("div",{className:"flex items-center gap-1.5 basis-full mt-0.5",children:[e.jsx(wt,{size:11,className:"text-slate-300 shrink-0"}),e.jsx("span",{className:"text-slate-400",children:n("candidates.path")}),e.jsx("code",{className:"font-mono text-[11px] text-slate-500 break-all",title:r.sourceFile,children:r.sourceFile})]})]})};return e.jsxs("div",{className:"relative",children:[t.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-24 text-center",children:[e.jsx(Sl,{size:48,className:"text-slate-200 mb-4"}),e.jsx("p",{className:"font-medium text-slate-600 mb-1",children:n("recipes.noResults")}),e.jsx("p",{className:"text-sm text-slate-400",children:n("recipes.noContent")})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4 text-xs",children:[e.jsx(Pa,{size:14,className:"text-slate-400 shrink-0"}),c.map(r=>{const k=g===r.key;return e.jsxs("button",{onClick:()=>{k?x(b=>b==="asc"?"desc":"asc"):(f(r.key),x(r.defaultDir)),z(1)},className:`px-2 py-1 rounded-md flex items-center gap-0.5 transition-colors ${k?"bg-blue-50 text-blue-700 font-medium border border-blue-200":"text-slate-500 hover:bg-slate-100 border border-transparent"}`,children:[r.label,k&&g!=="default"&&(h==="asc"?e.jsx(Al,{size:12}):e.jsx(Dl,{size:12}))]},r.key)}),e.jsx("span",{className:"ml-auto text-slate-400",children:n("recipes.totalCount",{count:t.length})})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-5",children:Ue.map(r=>{var U,te;const k=at(r),b=ua(r),B=r.description||r.usageGuide||"",D=H&&at(H)===k;return e.jsxs("div",{onClick:()=>he(r),className:`bg-white rounded-xl border shadow-sm hover:shadow-md transition-all group relative cursor-pointer overflow-hidden ${D?"border-blue-300 ring-1 ring-blue-200":"border-slate-200"}`,children:[e.jsxs("div",{className:"absolute top-3 right-3 flex gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity z-10",children:[e.jsx("button",{onClick:de=>{de.stopPropagation(),he(r),M("edit")},className:"p-1.5 bg-white/90 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-md transition-colors shadow-sm border border-slate-100",title:n("recipes.editRecipe"),children:e.jsx(Et,{size:F.sm})}),e.jsx("button",{onClick:de=>{de.stopPropagation(),s(r.name||r.id)},className:"p-1.5 bg-white/90 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-md transition-colors shadow-sm border border-slate-100",title:n("recipes.deleteRecipe"),children:e.jsx(ot,{size:F.sm})})]}),e.jsxs("div",{className:"px-5 pt-4 pb-3",children:[e.jsx("h3",{className:"font-bold text-slate-900 text-sm mb-2 pr-16 break-words leading-snug",children:k}),e.jsx(Pe,{recipe:r,compact:!0})]}),r.tags&&r.tags.length>0&&e.jsxs("div",{className:"px-5 pb-2 flex flex-wrap gap-1",children:[r.tags.slice(0,4).map((de,me)=>e.jsxs("span",{className:"text-[9px] px-1.5 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100 flex items-center gap-0.5",children:[e.jsx(ls,{size:7}),de]},me)),r.tags.length>4&&e.jsxs("span",{className:"text-[9px] text-slate-400",children:["+",r.tags.length-4]})]}),B&&e.jsx("div",{className:"px-5 pb-3",children:e.jsx("p",{className:"text-xs text-slate-500 line-clamp-2 leading-relaxed",children:B.replace(/^#+\s*/gm,"").replace(/\*\*/g,"")})}),((U=r.content)==null?void 0:U.markdown)&&e.jsxs("div",{className:"mx-4 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1 mb-1 px-0.5",children:[e.jsx(nt,{size:9,className:"text-blue-400"}),e.jsx("span",{className:"text-[9px] font-bold text-blue-400 uppercase",children:"Markdown"})]}),e.jsx("div",{className:"bg-blue-50/30 dark:bg-blue-900/15 border border-blue-100 dark:border-blue-800/40 rounded-lg px-3 py-2 max-h-[60px] overflow-hidden",children:e.jsx("p",{className:"text-[11px] text-slate-600 line-clamp-2 leading-relaxed",children:r.content.markdown.replace(/^#+\s*/gm,"").replace(/\*\*/g,"").replace(/```[\s\S]*?```/g,"").trim().slice(0,200)})})]}),b&&e.jsxs("div",{className:"mx-4 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-1 mb-1 px-0.5",children:[e.jsx(ht,{size:9,className:"text-emerald-400"}),e.jsx("span",{className:"text-[9px] font-bold text-emerald-400 uppercase",children:"Code"})]}),e.jsx("div",{className:"rounded-lg overflow-hidden max-h-[120px]",children:e.jsx(dt,{code:b.split(`
79
+ `).slice(0,6).join(`
80
+ `),language:pa(r)})})]}),e.jsxs("div",{className:"px-5 py-2.5 bg-slate-50/80 dark:bg-[#252a36] border-t border-slate-100 dark:border-slate-700 flex items-center gap-3 text-[10px] text-slate-400",children:[e.jsxs("span",{className:"font-bold text-amber-600",children:["★ ",((te=r.stats)==null?void 0:te.authority)??0]}),e.jsx("span",{children:n("recipes.usageCount",{count:r.stats?r.stats.guardUsageCount+r.stats.humanUsageCount+r.stats.aiUsageCount:0})}),r.source&&r.source!=="unknown"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-slate-200",children:"|"}),e.jsx("span",{children:r.source==="bootstrap-scan"?n("recipes.sourceBootstrap"):r.source==="agent"?n("recipes.sourceAiScan"):r.source})]}),r.moduleName&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-slate-200",children:"|"}),e.jsx("span",{className:"font-mono",children:r.moduleName})]}),r.relations&&Object.values(r.relations).flat().length>0&&e.jsxs("span",{className:"ml-auto text-purple-500 font-medium",children:[n("recipes.relations")," ",Object.values(r.relations).flat().length]})]})]},r.id||k)})})]}),t.length>0&&e.jsx(Js,{currentPage:S,totalPages:ie,totalItems:Q.length,pageSize:G,onPageChange:Ie,onPageSizeChange:P}),H&&(()=>{var U,te,de,me;const r=H,k=at(r),b=ua(r),B=pa(r),D=r.content;return e.jsxs(Ze,{className:"z-30 flex justify-end",onClick:ce,children:[e.jsx(Ze.Backdrop,{}),e.jsxs("div",{className:`relative h-full bg-white dark:bg-[#1e1e1e] shadow-2xl flex flex-col ${Z?"w-[min(92vw,1100px)]":"w-[min(92vw,800px)]"}`,style:{animation:"slideInRight 0.25s ease-out"},onClick:I=>I.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-slate-200 dark:border-slate-700 bg-gradient-to-b from-white to-slate-50/50 dark:from-[#252526] dark:to-[#1e1e1e] shrink-0",children:[e.jsx("div",{className:"flex-1 min-w-0 mr-3",children:e.jsx("h3",{className:"font-bold text-slate-800 text-lg leading-snug break-words",children:k})}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx("button",{onClick:ve,disabled:ne<=0,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors disabled:opacity-30",title:n("common.back"),children:e.jsx(is,{size:F.md})}),e.jsxs("span",{className:"text-xs text-slate-400 tabular-nums",children:[ne+1,"/",Q.length]}),e.jsx("button",{onClick:He,disabled:ne>=Q.length-1,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors disabled:opacity-30",title:n("common.more"),children:e.jsx(rt,{size:F.md})}),e.jsx("div",{className:"w-px h-5 bg-slate-200 mx-1"}),e.jsxs("div",{className:"flex bg-slate-100 p-0.5 rounded-lg mr-1",children:[e.jsxs("button",{onClick:()=>M("view"),className:`px-2.5 py-1 rounded-md text-xs font-bold transition-all flex items-center gap-1 ${R==="view"?"bg-white shadow-sm text-blue-600":"text-slate-400 hover:text-slate-600"}`,children:[e.jsx(os,{size:F.sm})," ",n("common.preview")]}),e.jsxs("button",{onClick:()=>{M("edit")},className:`px-2.5 py-1 rounded-md text-xs font-bold transition-all flex items-center gap-1 ${R==="edit"?"bg-white shadow-sm text-blue-600":"text-slate-400 hover:text-slate-600"}`,children:[e.jsx(Et,{size:F.sm})," ",n("common.edit")]})]}),e.jsx("button",{onClick:X,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors text-slate-400",title:n(Z?"common.collapse":"common.expand"),children:Z?e.jsx(Gs,{size:F.md}):e.jsx(Cs,{size:F.md})}),e.jsx("button",{onClick:()=>{s(r.name||r.id),ce()},className:"p-1.5 hover:bg-red-50 rounded-lg text-red-500 transition-colors",title:n("recipes.deleteRecipe"),children:e.jsx(ot,{size:F.md})}),e.jsx("button",{onClick:ce,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors",children:e.jsx(Xe,{size:F.md})})]})]}),R==="edit"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 overflow-y-auto p-5 space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-1.5 block",children:n("recipes.recipeDetail")}),e.jsx("input",{type:"text",value:N.title,onChange:I=>y(V=>({...V,title:I.target.value})),className:"w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300 focus:border-blue-300"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-1.5 block",children:n("recipes.description")}),e.jsx("textarea",{value:N.description,onChange:I=>y(V=>({...V,description:I.target.value})),rows:2,className:"w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300 resize-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-1.5 block",children:n("recipes.tags")}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:N.tags.map((I,V)=>e.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] px-2 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100 font-medium",children:[I,e.jsx("button",{onClick:()=>y(Ce=>({...Ce,tags:Ce.tags.filter((Ae,Re)=>Re!==V)})),className:"text-blue-400 hover:text-red-500",children:e.jsx(Xe,{size:10})})]},V))}),e.jsx("div",{className:"flex gap-2",children:e.jsx("input",{type:"text",value:N.tagInput,onChange:I=>y(V=>({...V,tagInput:I.target.value})),onKeyDown:I=>{I.key==="Enter"&&N.tagInput.trim()&&(I.preventDefault(),y(V=>({...V,tags:[...V.tags,V.tagInput.trim()],tagInput:""})))},placeholder:n("recipes.tags"),className:"flex-1 px-3 py-1.5 text-xs border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300"})})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-1.5 block flex items-center gap-1.5",children:[e.jsx(nt,{size:11,className:"text-blue-400"})," ",n("recipes.markdown")]}),e.jsx("textarea",{value:N.markdown,onChange:I=>y(V=>({...V,markdown:I.target.value})),rows:4,className:"w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300 resize-y font-mono",placeholder:n("recipes.markdown")})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-1.5 block flex items-center gap-1.5",children:[e.jsx(Ht,{size:11,className:"text-emerald-500"})," ",n("recipes.code")]}),e.jsx("div",{className:"border border-slate-200 rounded-lg overflow-hidden",style:{minHeight:200},children:e.jsx(ks,{value:N.codePattern,onChange:I=>y(V=>({...V,codePattern:I})),language:B,height:"200px",showLineNumbers:!0})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-1.5 block",children:n("recipes.designRationale")}),e.jsx("textarea",{value:N.rationale,onChange:I=>y(V=>({...V,rationale:I.target.value})),rows:3,className:"w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300 resize-y",placeholder:n("recipes.designRationale")})]})]}),e.jsxs("div",{className:"px-5 py-3 border-t border-slate-200 flex items-center justify-between shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-slate-400",children:n("recipes.qualityAuthorityScore")}),e.jsx("select",{className:"font-bold text-amber-600 bg-amber-50 border border-amber-100 px-2 py-1 rounded-lg outline-none text-[10px]",value:((U=r.stats)==null?void 0:U.authority)??3,onChange:I=>$(parseInt(I.target.value)),children:[1,2,3,4,5].map(I=>e.jsxs("option",{value:I,children:["⭐".repeat(I)," ",I]},I))})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:()=>M("view"),disabled:W,className:"px-4 py-1.5 text-sm text-slate-600 font-medium rounded-lg hover:bg-slate-50",children:n("common.cancel")}),e.jsxs("button",{onClick:je,disabled:W,className:"px-5 py-1.5 bg-blue-600 text-white text-sm font-medium rounded-lg flex items-center gap-1.5 hover:bg-blue-700 disabled:opacity-60",children:[W?e.jsx(Fe,{size:F.sm,className:"animate-spin"}):e.jsx(Ss,{size:F.sm}),n(W?"common.saving":"common.save")]})]})]})]}):e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100 space-y-3",children:[e.jsx(Pe,{recipe:r}),e.jsx(Ne,{recipe:r})]}),r.tags&&r.tags.length>0&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100 flex flex-wrap items-center gap-1.5",children:[e.jsx(ls,{size:11,className:"text-slate-300 mr-0.5"}),r.tags.map((I,V)=>e.jsx("span",{className:"text-[9px] px-2 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100 font-medium",children:I},V))]}),e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",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(Hs,{size:12,className:"text-purple-400"}),e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase",children:n("recipes.relations")}),(()=>{const I=r.relations?Object.values(r.relations).flat().length:0;return I>0?e.jsx("span",{className:"text-[9px] bg-purple-100 text-purple-600 px-1.5 py-0.5 rounded-full font-bold",children:I}):null})()]}),e.jsx("button",{onClick:()=>{ye(!we),ue("")},className:`text-[9px] px-2 py-0.5 rounded font-bold flex items-center gap-1 transition-colors ${we?"bg-slate-200 text-slate-600":"bg-purple-500 text-white hover:bg-purple-600"}`,children:we?e.jsxs(e.Fragment,{children:[e.jsx(Xe,{size:10})," ",n("common.cancel")]}):e.jsxs(e.Fragment,{children:[e.jsx(Nt,{size:10})," ",n("recipes.editBtn")]})})]}),we&&e.jsxs("div",{className:"mb-3 bg-purple-50/80 border border-purple-200 rounded-lg p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("select",{value:v,onChange:I=>ee(I.target.value),className:"text-[10px] font-bold bg-white border border-purple-200 text-purple-700 rounded px-2 py-1 outline-none",children:fe.map(I=>e.jsxs("option",{value:I.key,children:[I.icon," ",I.label]},I.key))}),e.jsxs("div",{className:"flex-1 relative",children:[e.jsx(ft,{size:12,className:"absolute left-2 top-1/2 -translate-y-1/2 text-slate-300"}),e.jsx("input",{type:"text",placeholder:n("recipes.searchPlaceholder"),value:ae,onChange:I=>ue(I.target.value),className:"w-full text-xs bg-white border border-purple-200 rounded pl-7 pr-2 py-1 outline-none",autoFocus:!0})]})]}),ae.length>0&&e.jsx("div",{className:"max-h-36 overflow-y-auto rounded border border-purple-100 bg-white divide-y divide-slate-100",children:(()=>{const I=t.filter(V=>at(V)===k?!1:at(V).toLowerCase().includes(ae.toLowerCase())).slice(0,10);return I.length?I.map(V=>{const Ce=at(V),Ae=r.relations&&Object.values(r.relations).flat().some(Re=>(typeof Re=="string"?Re:Re.target||Re.id||Re.title||"").replace(/\.md$/i,"").toLowerCase()===Ce.toLowerCase());return e.jsxs("div",{className:`flex items-center justify-between px-3 py-1.5 text-xs ${Ae?"bg-slate-50 text-slate-400":"hover:bg-purple-50 cursor-pointer"}`,onClick:()=>!Ae&&L(v,Ce),children:[e.jsx("span",{className:"font-medium truncate mr-2",children:Ce}),Ae?e.jsx("span",{className:"text-[9px] text-slate-400 font-bold shrink-0",children:n("recipes.relations")}):e.jsxs("span",{className:"text-[9px] text-purple-600 font-bold shrink-0",children:["+ ",n("recipes.editBtn")]})]},Ce)}):e.jsx("div",{className:"text-xs text-slate-400 py-3 text-center",children:n("recipes.noResults")})})()})]}),r.relations&&Object.entries(r.relations).some(([,I])=>Array.isArray(I)&&I.length>0)?e.jsx("div",{className:"space-y-1.5",children:fe.map(({key:I,label:V,icon:Ce})=>{var Re;const Ae=(Re=r.relations)==null?void 0:Re[I];return!Ae||!Array.isArray(Ae)||Ae.length===0?null:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("span",{className:"text-[10px] font-mono text-slate-500 w-14 shrink-0 pt-0.5",children:[Ce," ",V]}),e.jsx("div",{className:"flex flex-wrap gap-1",children:Ae.map((Be,Ye)=>{const J=typeof Be=="string"?Be:Be.target||Be.id||Be.title||JSON.stringify(Be),Le=K(J)||(xe.has(J)?K(xe.get(J)):void 0),qe=Le?at(Le):xe.get(J)||J;return e.jsxs("span",{className:`group/rel inline-flex items-center gap-1 px-1.5 py-0.5 border rounded text-[10px] font-mono transition-colors ${Le?"bg-purple-50 border-purple-200 text-purple-700 cursor-pointer hover:bg-purple-100":"bg-white border-slate-200 text-slate-600"}`,onClick:()=>Le&&he(Le),title:Le?n("candidates.viewDetail"):qe,children:[qe.replace(/\.md$/i,""),e.jsx("button",{onClick:ze=>{ze.stopPropagation(),T(I,J)},className:"opacity-0 group-hover/rel:opacity-100 text-red-400 hover:text-red-600 transition-opacity ml-0.5",title:n("common.delete"),children:e.jsx(Xe,{size:10})})]},Ye)})})]},I)})}):!we&&e.jsx("div",{className:"text-xs text-slate-300 py-2 text-center",children:n("recipes.noContent")})]}),e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"bg-amber-50/60 dark:bg-amber-900/20 rounded-xl p-3 text-center border border-amber-100 dark:border-amber-800/40",children:[e.jsx("div",{className:"text-lg font-bold text-amber-700",children:((te=r.stats)==null?void 0:te.authority)??"—"}),e.jsx("div",{className:"text-[10px] text-amber-500 font-medium",children:n("recipes.qualityAuthorityScore")})]}),e.jsxs("div",{className:"bg-blue-50/60 dark:bg-blue-900/20 rounded-xl p-3 text-center border border-blue-100 dark:border-blue-800/40",children:[e.jsx("div",{className:"text-lg font-bold text-blue-700",children:((de=r.stats)==null?void 0:de.authorityScore)!=null?r.stats.authorityScore.toFixed(1):"—"}),e.jsx("div",{className:"text-[10px] text-blue-500 font-medium",children:n("recipes.qualityGreat")})]}),e.jsxs("div",{className:"bg-slate-50 rounded-xl p-3 text-center border border-slate-100",children:[e.jsx("div",{className:"text-lg font-bold text-slate-800",children:r.stats?r.stats.guardUsageCount+r.stats.humanUsageCount+r.stats.aiUsageCount:0}),e.jsx("div",{className:"text-[10px] text-slate-400 font-medium",children:n("recipes.qualitySolid")})]}),e.jsxs("div",{className:"bg-slate-50 rounded-xl p-3 text-center border border-slate-100",children:[e.jsx("div",{className:"text-sm font-bold text-slate-700",children:xa((me=r.stats)==null?void 0:me.lastUsedAt)||n("recipes.noContent")}),e.jsx("div",{className:"text-[10px] text-slate-400 font-medium",children:n("recipes.qualityGood")})]})]}),r.stats!=null&&(r.stats.guardUsageCount>0||r.stats.humanUsageCount>0||r.stats.aiUsageCount>0)&&e.jsxs("div",{className:"flex items-center gap-4 mt-2 text-[10px] text-slate-400",children:[e.jsxs("span",{children:["Guard: ",r.stats.guardUsageCount]}),e.jsxs("span",{children:["Human: ",r.stats.humanUsageCount]}),e.jsxs("span",{children:["AI: ",r.stats.aiUsageCount]})]})]}),r.reasoning&&(r.reasoning.whyStandard||r.reasoning.sources&&r.reasoning.sources.length>0)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(jt,{size:11,className:"text-amber-400"})," ",n("recipes.reasoning")]}),e.jsxs("div",{className:"bg-amber-50/30 dark:bg-amber-900/15 border border-amber-100 dark:border-amber-800/40 rounded-xl p-4 space-y-2.5",children:[r.reasoning.whyStandard&&e.jsx("p",{className:"text-sm text-slate-700 leading-relaxed",children:r.reasoning.whyStandard}),r.reasoning.sources&&r.reasoning.sources.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"text-[10px] text-slate-400 font-bold",children:n("recipes.sourceColon")}),r.reasoning.sources.map((I,V)=>e.jsx("code",{className:"text-[10px] px-2 py-0.5 bg-white border border-amber-200 rounded text-amber-700 font-mono",children:I},V))]}),r.reasoning.confidence!=null&&r.reasoning.confidence>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] text-slate-400 font-bold",children:n("recipes.confidenceColon")}),e.jsx("div",{className:"flex-1 max-w-[160px] h-1.5 bg-slate-200 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-amber-400 rounded-full",style:{width:`${Math.round(r.reasoning.confidence*100)}%`}})}),e.jsxs("span",{className:"text-[10px] font-bold text-amber-600",children:[Math.round(r.reasoning.confidence*100),"%"]})]}),r.reasoning.alternatives&&r.reasoning.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-slate-400 font-bold",children:n("recipes.alternativesLabel")}),r.reasoning.alternatives.map((I,V)=>e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-slate-100 border border-slate-200 rounded text-slate-600",children:I},V))]})]})]}),r.quality&&r.quality.grade&&r.quality.grade!=="F"&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:n("recipes.qualityGrade")}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("span",{className:`text-2xl font-black ${r.quality.grade==="A"?"text-emerald-600":r.quality.grade==="B"?"text-blue-600":r.quality.grade==="C"?"text-amber-600":r.quality.grade==="D"?"text-orange-600":"text-slate-400"}`,children:r.quality.grade}),e.jsxs("div",{className:"flex-1 grid grid-cols-3 gap-2 text-[10px]",children:[r.quality.completeness!=null&&r.quality.completeness>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-slate-700",children:r.quality.completeness}),e.jsx("div",{className:"text-slate-400",children:n("recipes.qualityCompleteness")})]}),r.quality.adaptation!=null&&r.quality.adaptation>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-slate-700",children:r.quality.adaptation}),e.jsx("div",{className:"text-slate-400",children:n("recipes.qualityAdaptation")})]}),r.quality.documentation!=null&&r.quality.documentation>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-slate-700",children:r.quality.documentation}),e.jsx("div",{className:"text-slate-400",children:n("recipes.qualityDocumentation")})]})]})]})]}),r.description&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-1.5 block",children:n("recipes.description")}),e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:r.description})]}),(D==null?void 0:D.markdown)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(nt,{size:11,className:"text-blue-400"})," ",n("recipes.markdown")]}),e.jsx("div",{className:"bg-blue-50/30 dark:bg-blue-900/15 border border-blue-100 dark:border-blue-800/40 rounded-xl p-4",children:e.jsx("div",{className:"markdown-body text-sm text-slate-700 leading-relaxed",children:e.jsx(gt,{content:D.markdown})})})]}),r.headers&&r.headers.length>0&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:n("recipes.headers")}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:r.headers.map((I,V)=>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:I},V))})]}),b&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(ht,{size:11,className:"text-emerald-500"})," ",n("recipes.code")]}),e.jsx(dt,{code:b,language:B,showLineNumbers:!0})]}),(D==null?void 0:D.rationale)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:n("recipes.designRationale")}),e.jsx("div",{className:"bg-slate-50 border border-slate-100 rounded-xl p-4",children:e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:D.rationale})})]}),(D==null?void 0:D.steps)&&D.steps.length>0&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:n("recipes.steps")}),e.jsx("div",{className:"space-y-2",children:D.steps.map((I,V)=>{if(typeof I=="string")return e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 border border-slate-100 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:V+1}),e.jsx("p",{className:"text-xs text-slate-700 leading-relaxed",children:I})]},V);const Ce=typeof I.title=="string"?I.title:"",Ae=typeof I.description=="string"?I.description:"",Re=typeof I.code=="string"?I.code:"";return e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 border border-slate-100",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:V+1}),Ce&&e.jsx("span",{className:"text-xs font-bold text-slate-700",children:Ce})]}),Ae&&e.jsx("p",{className:"text-xs text-slate-600 ml-7 leading-relaxed",children:Ae}),Re&&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:Re})]},V)})})]}),(D==null?void 0:D.codeChanges)&&D.codeChanges.length>0&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:n("recipes.codeChanges")}),e.jsx("div",{className:"space-y-2",children:D.codeChanges.map((I,V)=>e.jsxs("div",{className:"border border-slate-200 rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-3 py-1.5 bg-slate-50 border-b border-slate-200 flex items-center gap-2",children:[e.jsx(ht,{size:11,className:"text-blue-400"}),e.jsx("code",{className:"text-[10px] font-mono text-slate-600",children:I.file})]}),I.explanation&&e.jsx("p",{className:"text-[11px] text-slate-500 px-3 py-1.5 border-b border-slate-100 bg-yellow-50/30",children:I.explanation}),e.jsxs("div",{className:"p-2 bg-red-50/20 border-b border-slate-100",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-slate-600 whitespace-pre-wrap break-words font-mono",children:I.before||n("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-slate-700 whitespace-pre-wrap break-words font-mono",children:I.after})]})]},V))})]}),(D==null?void 0:D.verification)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:n("recipes.validation")}),e.jsxs("div",{className:"bg-teal-50/50 border border-teal-100 rounded-xl p-4 space-y-1.5",children:[D.verification.method&&e.jsxs("p",{className:"text-xs text-slate-600",children:[e.jsx("span",{className:"font-bold text-teal-600",children:n("recipes.verificationMethod")})," ",D.verification.method]}),D.verification.expectedResult&&e.jsxs("p",{className:"text-xs text-slate-600",children:[e.jsx("span",{className:"font-bold text-teal-600",children:n("recipes.verificationExpected")})," ",D.verification.expectedResult]}),D.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:D.verification.testCode})]})]}),r.constraints&&(()=>{var Ce,Ae,Re,Be,Ye,J,Le,qe;const I=r.constraints,V=(((Ce=I.guards)==null?void 0:Ce.length)||0)+(((Ae=I.boundaries)==null?void 0:Ae.length)||0)+(((Re=I.preconditions)==null?void 0:Re.length)||0)+(((Be=I.sideEffects)==null?void 0:Be.length)||0);return V?e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(ut,{size:11,className:"text-amber-500"})," ",n("recipes.constraints")," ",e.jsx("span",{className:"text-amber-500 font-mono",children:V})]}),e.jsxs("div",{className:"space-y-1.5 text-xs text-slate-600",children:[(Ye=I.guards)==null?void 0:Ye.map((ze,Ve)=>e.jsxs("div",{className:"flex gap-1.5 items-start",children:[e.jsx("span",{className:`text-xs mt-0.5 ${ze.severity==="error"?"text-red-500":"text-yellow-500"}`,children:"●"}),e.jsx("code",{className:"font-mono text-[10px] bg-slate-100 px-1.5 py-0.5 rounded",children:ze.pattern}),ze.message&&e.jsxs("span",{className:"text-[10px] text-slate-400",children:["— ",ze.message]})]},Ve)),(J=I.boundaries)==null?void 0:J.map((ze,Ve)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("span",{className:"text-orange-400",children:"●"}),ze]},Ve)),(Le=I.preconditions)==null?void 0:Le.map((ze,Ve)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("span",{className:"text-blue-400",children:"◆"}),ze]},Ve)),(qe=I.sideEffects)==null?void 0:qe.map((ze,Ve)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("span",{className:"text-pink-400",children:"⚡"}),ze]},Ve))]})]}):null})()]})]})]})})()]})};function Dt(t){return t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"k":String(t)}function Vr(t){const s=new Map(t.map(l=>[l.date,l])),a=[];for(let l=6;l>=0;l--){const d=new Date;d.setDate(d.getDate()-l);const i=d.toISOString().slice(0,10);a.push(s.get(i)||{date:i,input_tokens:0,output_tokens:0,total_tokens:0,call_count:0})}return a}const Jr={user:"bg-blue-500",mcp:"bg-purple-500",bootstrap:"bg-amber-500",guard:"bg-rose-500",analyst:"bg-indigo-500",producer:"bg-green-500"},Yr=()=>{const{t}=_e(),[s,a]=o.useState([]),[l,d]=o.useState([]),[i,u]=o.useState({input_tokens:0,output_tokens:0,total_tokens:0,call_count:0,avg_per_call:0}),[p,n]=o.useState(!0),[g,f]=o.useState(null);o.useEffect(()=>{let j=!1;return(async()=>{try{const w=await se.getTokenUsage7Days();if(j)return;a(w.daily||[]),d(w.bySource||[]),u(w.summary||{input_tokens:0,output_tokens:0,total_tokens:0,call_count:0,avg_per_call:0})}catch(w){j||f(w.message||t("tokenUsageChart.loadFailed"))}finally{j||n(!1)}})(),()=>{j=!0}},[]);const h=o.useMemo(()=>Vr(s),[s]),x=o.useMemo(()=>Math.max(...h.map(j=>j.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 c=i.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(xs,{label:t("tokenUsageChart.totalToken"),value:Dt(i.total_tokens),sub:t("tokenUsageChart.totalSub"),color:"blue"}),e.jsx(xs,{label:t("tokenUsageChart.input"),value:Dt(i.input_tokens),sub:"Prompt",color:"green"}),e.jsx(xs,{label:t("tokenUsageChart.output"),value:Dt(i.output_tokens),sub:"Completion",color:"purple"}),e.jsx(xs,{label:t("tokenUsageChart.calls"),value:String(i.call_count),sub:t("tokenUsageChart.avgPerCall",{avg:Dt(i.avg_per_call)}),color:"amber"})]}),c?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(j=>{const w=j.input_tokens/x*100,C=j.output_tokens/x*100,E=t(`tokenUsageChart.weekday${new Date(j.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:j.date}),e.jsx("p",{children:t("tokenUsageChart.dailyDetail",{input:Dt(j.input_tokens),output:Dt(j.output_tokens)})}),e.jsx("p",{children:t("tokenUsageChart.dailyCalls",{count:String(j.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:`${w}%`,minHeight:j.input_tokens>0?"2px":"0"}}),e.jsx("div",{className:"bg-purple-400 rounded-b-sm w-full transition-all",style:{height:`${C}%`,minHeight:j.output_tokens>0?"2px":"0"}})]}),e.jsx("span",{className:"text-[10px] text-slate-400",children:E})]},j.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")]})]})]}),l.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:l.map(j=>{const w=i.total_tokens>0?j.total_tokens/i.total_tokens*100:0,C=Jr[j.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:j.source}),e.jsx("div",{className:"flex-1 bg-slate-100 rounded-full h-3 overflow-hidden",children:e.jsx("div",{className:`${C} h-full rounded-full transition-all`,style:{width:`${w}%`,minWidth:w>0?"4px":"0"}})}),e.jsx("span",{className:"w-16 text-xs text-slate-500 text-right",children:Dt(j.total_tokens)}),e.jsxs("span",{className:"w-12 text-xs text-slate-400 text-right",children:[w.toFixed(0),"%"]})]},j.source)})})]})]})]})};function xs({label:t,value:s,sub:a,color:l}){const d={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"},i=d[l]||d.blue;return e.jsxs("div",{className:`rounded-lg border p-3 ${i}`,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 vt=({id:t,title:s,icon:a,isExpanded:l,onToggle:d,children:i})=>e.jsxs("section",{className:"border border-slate-200 rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>d(t),className:"w-full flex items-center justify-between p-4 bg-slate-50 hover:bg-slate-100 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[a,e.jsx("h2",{className:"text-lg font-bold text-slate-800",children:s})]}),l?e.jsx(Gt,{size:F.lg}):e.jsx(rt,{size:F.lg})]}),l&&e.jsx("div",{className:"p-4 bg-white",children:i})]}),Qr=()=>{const{t}=_e(),[s,a]=o.useState(new Set(["quick-start"])),l=d=>{const i=new Set(s);i.has(d)?i.delete(d):i.add(d),a(i)};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.jsxs("h1",{className:"text-4xl font-bold text-slate-900 mb-4 flex items-center justify-center gap-3",children:[e.jsx(tt,{size:F.xxl,className:"text-blue-600"}),t("help.pageTitle")]}),e.jsx("p",{className:"text-slate-600 text-lg max-w-3xl mx-auto whitespace-nowrap",children:t("help.subtitle")}),e.jsx("p",{className:"text-slate-400 text-sm mt-2",children:t("help.techSpecs")}),e.jsxs("div",{className:"mt-6 flex gap-4 justify-center text-sm",children:[e.jsx("a",{href:"https://github.com/GxFn/AutoSnippet",target:"_blank",rel:"noopener noreferrer",className:"px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors",children:t("help.viewGithub")}),e.jsx("a",{href:"https://github.com/GxFn/AutoSnippet/blob/main/README.md",target:"_blank",rel:"noopener noreferrer",className:"px-4 py-2 border border-slate-300 text-slate-700 rounded-lg hover:bg-slate-50 transition-colors",children:t("help.fullDocs")})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(vt,{id:"token-usage",title:t("help.tokenUsageLast7Days"),icon:e.jsx(La,{size:F.xl,className:"text-blue-600"}),isExpanded:s.has("token-usage"),onToggle:l,children:e.jsx(Yr,{})}),e.jsx(vt,{id:"quick-start",title:t("help.quickStart"),icon:e.jsx(Xt,{size:F.xl,className:"text-blue-600"}),isExpanded:s.has("quick-start"),onToggle:l,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-slate-800 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-hidden",children:e.jsxs("code",{children:["npm install -g autosnippet",`
81
+ `,"cd your-project",`
82
+ `,"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-slate-800 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-hidden",children:e.jsx("code",{children:"asd ui"})}),e.jsx("p",{className:"text-slate-600 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-slate-800 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-hidden",children:e.jsx("code",{children:"asd upgrade"})}),e.jsx("p",{className:"text-slate-600 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-slate-800 mb-2",children:t("help.step4Title")}),e.jsx("p",{className:"text-slate-600 text-sm mb-1",children:t("help.step4Desc1")}),e.jsx("p",{className:"text-slate-600 text-sm",children:t("help.step4Desc2")})]})]})}),e.jsxs(vt,{id:"concepts",title:t("help.coreConcepts"),icon:e.jsx(Da,{size:F.xl,className:"text-blue-600"}),isExpanded:s.has("concepts"),onToggle:l,children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-700 mb-3",children:t("help.threeRoles")}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full border border-slate-200 rounded-lg text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-slate-50",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-slate-50",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-slate-50",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-slate-50",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-slate-700 mb-3",children:t("help.coreComponents")}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",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(et,{size:F.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",{children:t("help.bootstrapBullet1")}),e.jsx("li",{children: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(Il,{size:F.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",{children:t("help.candidatesBullet1")}),e.jsx("li",{children:t("help.candidatesBullet2")}),e.jsx("li",{children: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(ht,{size:F.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",{children: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(Ys,{size:F.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",{children:t("help.chatAgentCompBullet1")}),e.jsx("li",{children:t("help.chatAgentCompBullet2")}),e.jsx("li",{children: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(ft,{size:F.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",{children:t("help.searchPipelineBullet1")}),e.jsx("li",{children:t("help.searchPipelineBullet2")}),e.jsx("li",{children:t("help.searchPipelineBullet3")})]})]}),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(ut,{size:F.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",{children:t("help.guardCompBullet1")}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.guardCompBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.guardCompBullet3")}})]})]})]})]}),e.jsxs("div",{className:"mt-6 bg-gradient-to-r from-blue-50 to-purple-50 rounded-lg p-5 border border-slate-200",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-700 mb-4",children:t("help.knowledgeLoop")}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-[100px] text-center",children:[e.jsx("div",{className:"bg-blue-500 text-white rounded-full w-10 h-10 flex items-center justify-center mx-auto mb-2 font-bold text-lg",children:"1"}),e.jsx("p",{className:"text-slate-700 font-medium text-sm",children:t("help.loopStep1")}),e.jsx("p",{className:"text-slate-500 text-xs",children:t("help.loopStep1Sub")})]}),e.jsx("div",{className:"text-slate-400 text-2xl",children:"→"}),e.jsxs("div",{className:"flex-1 min-w-[100px] text-center",children:[e.jsx("div",{className:"bg-green-500 text-white rounded-full w-10 h-10 flex items-center justify-center mx-auto mb-2 font-bold text-lg",children:"2"}),e.jsx("p",{className:"text-slate-700 font-medium text-sm",children:t("help.loopStep2")}),e.jsx("p",{className:"text-slate-500 text-xs",children:t("help.loopStep2Sub")})]}),e.jsx("div",{className:"text-slate-400 text-2xl",children:"→"}),e.jsxs("div",{className:"flex-1 min-w-[100px] text-center",children:[e.jsx("div",{className:"bg-purple-500 text-white rounded-full w-10 h-10 flex items-center justify-center mx-auto mb-2 font-bold text-lg",children:"3"}),e.jsx("p",{className:"text-slate-700 font-medium text-sm",children:t("help.loopStep3")}),e.jsx("p",{className:"text-slate-500 text-xs",children:t("help.loopStep3Sub")})]}),e.jsx("div",{className:"text-slate-400 text-2xl",children:"→"}),e.jsxs("div",{className:"flex-1 min-w-[100px] text-center",children:[e.jsx("div",{className:"bg-amber-500 text-white rounded-full w-10 h-10 flex items-center justify-center mx-auto mb-2 font-bold text-lg",children:"4"}),e.jsx("p",{className:"text-slate-700 font-medium text-sm",children:t("help.loopStep4")}),e.jsx("p",{className:"text-slate-500 text-xs",children:t("help.loopStep4Sub")})]}),e.jsx("div",{className:"text-slate-400 text-2xl",children:"→"}),e.jsxs("div",{className:"flex-1 min-w-[100px] text-center",children:[e.jsx("div",{className:"bg-rose-500 text-white rounded-full w-10 h-10 flex items-center justify-center mx-auto mb-2 font-bold text-lg",children:"5"}),e.jsx("p",{className:"text-slate-700 font-medium text-sm",children:t("help.loopStep5")}),e.jsx("p",{className:"text-slate-500 text-xs",children:t("help.loopStep5Sub")})]})]})]})]}),e.jsx(vt,{id:"features",title:t("help.coreFeatures"),icon:e.jsx(et,{size:F.xl,className:"text-blue-600"}),isExpanded:s.has("features"),onToggle:l,children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-5",children:[e.jsxs("div",{className:"border border-slate-200 rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx($s,{size:F.lg,className:"text-blue-600"}),e.jsx("h3",{className:"font-semibold text-slate-800",children:t("help.knowledgeBuild")})]}),e.jsxs("ul",{className:"text-slate-600 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-slate-200 rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(ft,{size:F.lg,className:"text-blue-600"}),e.jsx("h3",{className:"font-semibold text-slate-800",children:t("help.semanticSearchLabel")})]}),e.jsxs("ul",{className:"text-slate-600 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-slate-200 rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(ut,{size:F.lg,className:"text-blue-600"}),e.jsx("h3",{className:"font-semibold text-slate-800",children:t("help.codeAudit")})]}),e.jsxs("ul",{className:"text-slate-600 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-slate-200 rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(yt,{size:F.lg,className:"text-blue-600"}),e.jsx("h3",{className:"font-semibold text-slate-800",children:t("help.dataSync")})]}),e.jsxs("ul",{className:"text-slate-600 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(vt,{id:"editor-directives",title:t("help.editorDirectives"),icon:e.jsx(Qs,{size:F.xl,className:"text-blue-600"}),isExpanded:s.has("editor-directives"),onToggle:l,children:[e.jsx("p",{className:"text-slate-600 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-slate-50 rounded-lg p-4 border border-slate-200",children:[e.jsxs("h4",{className:"font-semibold text-slate-800 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-slate-600 text-sm mb-2",children:t("help.createDirective")}),e.jsxs("ul",{className:"text-slate-600 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-slate-50 rounded-lg p-4 border border-slate-200",children:[e.jsxs("h4",{className:"font-semibold text-slate-800 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-slate-600 text-sm mb-2",children:t("help.searchDirective")}),e.jsxs("ul",{className:"text-slate-600 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-slate-50 rounded-lg p-4 border border-slate-200",children:[e.jsxs("h4",{className:"font-semibold text-slate-800 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-slate-600 text-sm mb-2",children:t("help.auditDirective")}),e.jsxs("ul",{className:"text-slate-600 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-slate-50 rounded-lg p-4 border border-slate-200",children:[e.jsxs("h4",{className:"font-semibold text-slate-800 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-slate-600 text-sm mb-2",children:t("help.includeDirective")}),e.jsxs("ul",{className:"text-slate-600 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(vt,{id:"cursor-integration",title:t("help.cursorIntegration"),icon:e.jsx(Lt,{size:F.xl,className:"text-blue-600"}),isExpanded:s.has("cursor-integration"),onToggle:l,children:[e.jsxs("div",{className:"mb-5",children:[e.jsx("h3",{className:"font-semibold text-slate-800 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"}].map(d=>e.jsxs("div",{className:"bg-slate-50 border border-slate-200 rounded-lg px-3 py-2 text-center",children:[e.jsx("p",{className:"text-xs font-mono text-blue-600",children:d.name}),e.jsx("p",{className:"text-xs text-slate-500 mt-0.5",children:t(d.descKey)})]},d.name))})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("h3",{className:"font-semibold text-slate-800 mb-3",children:t("help.mcp16")}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full border border-slate-200 rounded-lg text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-slate-50",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:"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.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-slate-500 mt-2",children:t("help.mcpWriteNote")})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-slate-800 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.jsx(vt,{id:"v2-architecture",title:t("help.v3Architecture"),icon:e.jsx(lt,{size:F.xl,className:"text-blue-600"}),isExpanded:s.has("v2-architecture"),onToggle:l,children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-5",children:[e.jsxs("div",{className:"border border-slate-200 rounded-lg p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(et,{size:F.lg,className:"text-indigo-600"}),e.jsx("h3",{className:"font-semibold text-slate-800",children:t("help.bootstrapEngine")})]}),e.jsx("p",{className:"text-slate-600 text-sm mb-2",children:t("help.bootstrapEngineDesc")}),e.jsxs("div",{className:"bg-slate-50 rounded p-3 text-xs font-mono text-slate-700 space-y-1",children:[e.jsx("p",{children:t("help.archBootstrapStep1")}),e.jsx("p",{children:t("help.archBootstrapStep2")}),e.jsx("p",{children:t("help.archBootstrapStep3")})]}),e.jsx("p",{className:"text-slate-500 text-xs mt-2",children:t("help.archBootstrapNote")})]}),e.jsxs("div",{className:"border border-slate-200 rounded-lg p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(ft,{size:F.lg,className:"text-indigo-600"}),e.jsx("h3",{className:"font-semibold text-slate-800",children:t("help.fourLayerPipeline")})]}),e.jsx("p",{className:"text-slate-600 text-sm mb-2",children:t("help.fourLayerPipelineDesc")}),e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"bg-blue-100 text-blue-700 px-2 py-0.5 rounded font-medium shrink-0",children:"L1"}),e.jsx("span",{className:"text-slate-600",children:t("help.archPipelineL1")})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"bg-green-100 text-green-700 px-2 py-0.5 rounded font-medium shrink-0",children:"L2"}),e.jsx("span",{className:"text-slate-600",children:t("help.archPipelineL2")})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"bg-amber-100 text-amber-700 px-2 py-0.5 rounded font-medium shrink-0",children:"L3"}),e.jsx("span",{className:"text-slate-600",children:t("help.archPipelineL3")})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"bg-red-100 text-red-700 px-2 py-0.5 rounded font-medium shrink-0",children:"L4"}),e.jsx("span",{className:"text-slate-600",children:t("help.archPipelineL4")})]})]})]}),e.jsxs("div",{className:"border border-slate-200 rounded-lg p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Ys,{size:F.lg,className:"text-indigo-600"}),e.jsx("h3",{className:"font-semibold text-slate-800",children:t("help.chatAgentSystem")})]}),e.jsx("p",{className:"text-slate-600 text-sm mb-2",children:t("help.chatAgentSystemDesc")}),e.jsxs("div",{className:"bg-slate-50 rounded p-3 text-xs text-slate-700 space-y-1.5",children:[e.jsx("p",{dangerouslySetInnerHTML:{__html:t("help.archAnalystAgent")}}),e.jsx("p",{dangerouslySetInnerHTML:{__html:t("help.archProducerAgent")}}),e.jsx("p",{dangerouslySetInnerHTML:{__html:t("help.archHandoff")}}),e.jsx("p",{dangerouslySetInnerHTML:{__html:t("help.archMemory")}}),e.jsx("p",{dangerouslySetInnerHTML:{__html:t("help.archProjectAware")}})]})]}),e.jsxs("div",{className:"border border-slate-200 rounded-lg p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(_s,{size:F.lg,className:"text-indigo-600"}),e.jsx("h3",{className:"font-semibold text-slate-800",children:t("help.fiveEntryChannels")})]}),e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("span",{className:"font-medium",children:"CLI"}),e.jsx("span",{className:"text-slate-500",children:t("help.archCliDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("span",{className:"font-medium",children:"MCP Server"}),e.jsx("span",{className:"text-slate-500",children:t("help.archMcpDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("span",{className:"font-medium",children:"HTTP API"}),e.jsx("span",{className:"text-slate-500",children:t("help.archHttpDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("span",{className:"font-medium",children:"Dashboard"}),e.jsx("span",{className:"text-slate-500",children:"React 19 + Vite 6 + Tailwind 4"})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("span",{className:"font-medium",children:"Skills"}),e.jsx("span",{className:"text-slate-500",children:t("help.archSkillsDesc")})]})]})]})]})}),e.jsx(vt,{id:"cli-reference",title:t("help.cliReference"),icon:e.jsx(Qs,{size:F.xl,className:"text-blue-600"}),isExpanded:s.has("cli-reference"),onToggle:l,children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-slate-800 mb-2",children:t("help.initAndEnv")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd setup"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliSetupDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd status"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliStatusDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd ui"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliUiDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd upgrade"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliUpgradeDesc")})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-slate-800 mb-2",children:t("help.kbManagement")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd sync"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliSyncDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd ais [Target]"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliAisDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd ais --force"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliAisForceDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd watch"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliWatchDesc")})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-slate-800 mb-2",children:t("help.searchAndAudit")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd search <query>"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliSearchDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd search -m semantic"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliSearchSemanticDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd guard <file>"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliGuardDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd server"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliServerDesc")})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-slate-800 mb-2",children:t("help.maintenanceUpgrade")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd upgrade"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliUpgradeMcpDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd install:full"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliInstallFullDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd sync --force"}),e.jsx("span",{className:"text-slate-500 text-xs",children:t("help.cliSyncForceDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-slate-50 px-3 py-2 rounded",children:[e.jsx("code",{children:"asd sync --dry-run"}),e.jsx("span",{className:"text-slate-500 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-slate-700 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 Xr(){const[t,s]=o.useState(null);o.useEffect(()=>{const i=Ks(),u=h=>{s({status:"running",total:h.total,current:0,progress:0,refined:0,failed:0,items:h.candidateIds.map(x=>({candidateId:x,title:"",status:"pending"}))})},p=h=>{s(x=>x&&{...x,current:h.current,progress:h.progress,items:x.items.map(c=>c.candidateId===h.candidateId?{...c,title:h.title,status:"refining"}:c)})},n=h=>{s(x=>x&&{...x,current:h.current,progress:h.progress,refined:h.refinedSoFar,items:x.items.map(c=>c.candidateId===h.candidateId?{...c,title:h.title,status:"done",refined:h.refined}:c)})},g=h=>{s(x=>x&&{...x,current:h.current,progress:h.progress,failed:x.failed+1,items:x.items.map(c=>c.candidateId===h.candidateId?{...c,title:h.title,status:"failed",error:h.error}:c)})},f=h=>{s(x=>x&&{...x,status:"completed",progress:100,refined:h.refined,failed:h.failed})};return i.on("refine:started",u),i.on("refine:item-started",p),i.on("refine:item-completed",n),i.on("refine:item-failed",g),i.on("refine:completed",f),()=>{i.off("refine:started",u),i.off("refine:item-started",p),i.off("refine:item-completed",n),i.off("refine:item-failed",g),i.off("refine:completed",f)}},[]);const a=o.useCallback(()=>s(null),[]),l=(t==null?void 0:t.status)==="running",d=(t==null?void 0:t.status)==="completed";return{refine:t,isRefining:l,isRefineDone:d,resetRefine:a}}const Zr=({refine:t,isRefineDone:s,onDismiss:a})=>{const{t:l}=_e(),d=o.useRef(!1);if(o.useEffect(()=>{if(s&&t&&!d.current){d.current=!0;const p=t.failed>0?l("refineProgress.doneMsgWithFail",{refined:String(t.refined),failed:String(t.failed)}):l("refineProgress.doneMsg",{refined:String(t.refined)});re(p,{title:l("refineProgress.doneTitle"),type:t.failed>0?"error":"success"})}},[s,t]),o.useEffect(()=>{t||(d.current=!1)},[t]),!t)return null;const i=t.items.find(p=>p.status==="refining"),u=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(kt,{className:"w-4 h-4 text-emerald-600"}):e.jsx(Qe,{className:"w-4 h-4 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-slate-800",children:l(s?"refineProgress.doneTitle":"refineProgress.runningTitle")}),e.jsxs("p",{className:"text-xs text-slate-500",children:[s?t.failed>0?l("refineProgress.doneMsgWithFail",{refined:String(t.refined),failed:String(t.failed)}):l("refineProgress.doneMsg",{refined:String(t.refined)}):l("refineProgress.progressMsg",{done:String(u),total:String(t.total)}),i&&!s&&e.jsxs("span",{className:"ml-2 text-blue-600",children:[e.jsx(Fe,{className:"w-3 h-3 inline animate-spin mr-1"}),i.title||i.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:l("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(Xe,{className:"w-3 h-3"}),t.items.filter(p=>p.status==="failed").map(p=>p.title||p.candidateId.slice(0,8)).join("、")]})]})},ms={_watch:"silentLabels.watch",_draft:"silentLabels.draft",_cli:"silentLabels.cli",_pending:"silentLabels.pending",_recipe:"silentLabels.recipe"},hs={architecture:"bootstrap.dimLabels.architecture","best-practice":"bootstrap.dimLabels.bestPractice","event-and-data-flow":"bootstrap.dimLabels.eventAndDataFlow","objc-deep-scan":"bootstrap.dimLabels.objcDeepScan","agent-guidelines":"bootstrap.dimLabels.agentGuidelines",bootstrap:"bootstrap.dimLabels.bootstrap","code-standard":"bootstrap.dimLabels.codeStandard","code-pattern":"bootstrap.dimLabels.codePattern","project-profile":"bootstrap.dimLabels.projectProfile","category-scan":"bootstrap.dimLabels.categoryScan"};function en(t,s,a,l){return[...t].sort(([d],[i])=>{const u=l(d),p=l(i);if(u&&!p)return 1;if(!u&&p)return-1;const n=a(d),g=a(i);if(n&&!g)return-1;if(!n&&g)return 1;const f=s(d),h=s(i);return f&&!h?1:!f&&h?-1:d.localeCompare(i)})}function Wt(t,s){if(!t)return"";const a=typeof t=="number"?t:Number(t),l=a<1e12?a*1e3:a,d=new Date(l);if(isNaN(d.getTime())||d.getFullYear()<2e3)return"";const u=new Date().getTime()-d.getTime();if(u<0)return d.toLocaleDateString();const p=Math.floor(u/6e4);if(p<1)return s("candidates.timeJustNow");if(p<60)return s("candidates.timeMinutesAgo",{n:p});const n=Math.floor(p/60);if(n<24)return s("candidates.timeHoursAgo",{n});const g=Math.floor(n/24);return g<7?s("candidates.timeDaysAgo",{n:g}):d.toLocaleDateString()}function tn(t,s=4){return t?Us(t).split(`
83
+ `).slice(0,s).join(`
84
+ `):""}function sn(t){return t==null?{ring:"stroke-slate-200",text:"text-slate-400",bg:"bg-slate-50",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"}}const ma={"bootstrap-scan":{labelKey:"candidates.sourceAiScanLabel",color:"text-violet-600 bg-violet-50 border-violet-200"},mcp:{labelKey:"candidates.sourceMcpLabel",color:"text-blue-600 bg-blue-50 border-blue-200"},manual:{labelKey:"candidates.sourceManualLabel",color:"text-emerald-600 bg-emerald-50 border-emerald-200"},"file-watcher":{labelKey:"candidates.sourceFileWatcherLabel",color:"text-orange-600 bg-orange-50 border-orange-200"},clipboard:{labelKey:"candidates.sourceClipboardLabel",color:"text-pink-600 bg-pink-50 border-pink-200"},cli:{labelKey:"CLI",color:"text-slate-600 bg-slate-50 border-slate-200"},agent:{labelKey:"AI Agent",color:"text-violet-600 bg-violet-50 border-violet-200"},submit_with_check:{labelKey:"candidates.sourceSubmitCheckLabel",color:"text-teal-600 bg-teal-50 border-teal-200"}},an=({value:t,size:s=36})=>{const a=(s-6)/2,l=2*Math.PI*a,d=t!=null?Math.max(0,Math.min(1,t)):0,i=l*(1-d),{ring:u,text:p}=sn(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-slate-100"}),e.jsx("circle",{cx:s/2,cy:s/2,r:a,fill:"none",strokeWidth:3,strokeLinecap:"round",className:u,strokeDasharray:l,strokeDashoffset:i,style:{transition:"stroke-dashoffset 0.5s ease"}})]}),e.jsx("span",{className:`absolute text-[9px] font-bold ${p}`,children:t!=null?`${Math.round(t*100)}`:"—"})]})},ln=({data:t,isShellTarget:s,isSilentTarget:a=()=>!1,isPendingTarget:l=()=>!1,handleDeleteCandidate:d,handleDeleteAllInTarget:i,onAuditCandidate:u,onAuditAllInTarget:p,onEditRecipe:n,onColdStart:g,isScanning:f,isBootstrapping:h,onRefresh:x})=>{var Ne;const{t:c}=_e(),[j,w]=o.useState(null),{isWide:C,toggle:E}=Vs(),[S,G]=o.useState(new Set),[z,P]=o.useState(new Set),[Z,X]=o.useState(!1),[H,q]=o.useState(!1),R=ds(),{refine:M,isRefining:_,isRefineDone:m,resetRefine:N}=Xr(),[y,W]=o.useState({}),[O,be]=o.useState(null),[we,ye]=o.useState({}),[v,ee]=o.useState(null),[ae,ue]=o.useState({}),[fe,he]=o.useState({sort:"default",onlySimilar:!1}),[ce,je]=o.useState(null),$=o.useRef(new Set),K=o.useCallback(async(r,k)=>{if(!$.current.has(k)){$.current.add(k),ee(k);try{const b=await se.getCandidateSimilarityEx({targetName:r,candidateId:k});ye(B=>({...B,[k]:b.similar||[]}))}catch{ye(B=>({...B,[k]:[]}))}finally{ee(null)}}},[]),xe=o.useCallback(async(r,k,b,B=[])=>{var me,I,V,Ce;const D=b.replace(/\.md$/i,"");let U="";const te=(me=t==null?void 0:t.recipes)==null?void 0:me.find(Ae=>Ae.name===D||Ae.name.endsWith("/"+D));if(te!=null&&te.content)U=[te.content.pattern,te.content.markdown].filter(Boolean).join(`
85
+
86
+ `)||"";else try{U=(await se.getRecipeContentByName(D)).content}catch(Ae){const Re=(I=Ae.response)==null?void 0:I.status,Be=((Ce=(V=Ae.response)==null?void 0:V.data)==null?void 0:Ce.message)||Ae.message;Re===404?re(`"${D}" ${c("common.operationFailed")}`,{title:c("common.operationFailed"),type:"error"}):re(Be,{title:c("common.loadFailed"),type:"error"});return}const de={[D]:U};w(r.id),je({candidate:r,targetName:k,recipeName:D,recipeContent:U,similarList:B.slice(0,3),recipeContents:de})},[t==null?void 0:t.recipes]),L=t!=null&&t.candidates?Object.entries(t.candidates):[],T=en(L,s,a,l),Q=T.map(([r])=>r),ie=O&&Q.includes(O)?O:Q[0]??null;o.useEffect(()=>{Q.length>0&&(!O||!Q.includes(O))&&be(Q[0])},[Q.join(","),O]),o.useEffect(()=>{j&&ie&&K(ie,j)},[j,ie,K]);const ke=o.useMemo(()=>{var U;if(!ie||!((U=t==null?void 0:t.candidates)!=null&&U[ie]))return null;const r=t.candidates[ie].items,k=r.length,b=r.reduce((te,de)=>{var me;return te+(((me=de.reasoning)==null?void 0:me.confidence)??0)},0)/(k||1),B=r.filter(te=>{var de;return((de=te.content)==null?void 0:de.pattern)&&te.content.pattern.trim().length>0}).length,D=new Map;return r.forEach(te=>{const de=te.source||"unknown";D.set(de,(D.get(de)||0)+1)}),{total:k,avgConfidence:b,withCode:B,sources:D}},[ie,t==null?void 0:t.candidates]),Ue=o.useMemo(()=>{const r=new Map;if(t!=null&&t.idTitleMap)for(const[k,b]of Object.entries(t.idTitleMap))r.set(k,b);if(t!=null&&t.candidates)for(const k of Object.values(t.candidates))for(const b of k.items)b.id&&b.title&&r.set(b.id,b.title);if(t!=null&&t.recipes)for(const k of t.recipes)k.id&&k.name&&r.set(k.id,k.name.replace(/\.md$/i,""));return r},[t==null?void 0:t.idTitleMap,t==null?void 0:t.candidates,t==null?void 0:t.recipes]),Ie=o.useCallback(async r=>{var k,b,B,D,U;if(!S.has(r)){G(te=>new Set(te).add(r));try{const te=await se.enrichCandidates([r]);te.enriched>0?re(`${((B=(b=(k=te.results)==null?void 0:k[0])==null?void 0:b.filledFields)==null?void 0:B.length)||0} ${c("candidates.approveSuccess")}`,{title:c("candidates.aiRefine")}):re(c("recipes.noContent"),{title:c("candidates.aiRefine"),type:"info"});try{const de=await se.getCandidate(r);ue(me=>({...me,[r]:de}))}catch{}}catch(te){const de=(U=(D=te.response)==null?void 0:D.data)==null?void 0:U.error;re(typeof de=="string"?de:(de==null?void 0:de.message)||te.message,{title:c("common.operationFailed"),type:"error"})}finally{G(te=>{const de=new Set(te);return de.delete(r),de})}}},[S,x]),ne=o.useCallback(async()=>{var k,b,B;if(Z||!ie||!((k=t==null?void 0:t.candidates)!=null&&k[ie]))return;const r=t.candidates[ie].items;if(r.length!==0){X(!0);try{let D=0;for(let U=0;U<r.length;U+=20){const te=r.slice(U,U+20).map(me=>me.id),de=await se.enrichCandidates(te);D+=de.enriched}re(`${D}/${r.length} ${c("candidates.batchDeleteDone",{count:D})}`,{title:c("candidates.aiRefine")}),x==null||x()}catch(D){const U=(B=(b=D.response)==null?void 0:b.data)==null?void 0:B.error;re(typeof U=="string"?U:(U==null?void 0:U.message)||D.message,{title:c("common.operationFailed"),type:"error"})}finally{X(!1)}}},[Z,ie,t==null?void 0:t.candidates,x]),ve=o.useCallback(async r=>{try{const k=await se.getCandidate(r);ue(b=>({...b,[r]:k}))}catch{}},[]),He=o.useCallback(()=>{var b;if(!ie||!((b=t==null?void 0:t.candidates)!=null&&b[ie]))return;const r=t.candidates[ie].items,k=r.map(B=>B.id);R.openRefine({candidateIds:k,candidates:r,onCandidateUpdated:ve})},[ie,t==null?void 0:t.candidates,R,ve]),Pe=o.useCallback(r=>{var b;if(!ie||!((b=t==null?void 0:t.candidates)!=null&&b[ie]))return;je(null),w(r);const k=t.candidates[ie].items;R.openRefine({candidateIds:[r],candidates:k,onCandidateUpdated:ve})},[ie,t==null?void 0:t.candidates,R,ve]);return e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"mb-4 flex justify-between items-center shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-50 border border-blue-100 flex items-center justify-center",children:e.jsx(Qe,{className:"text-blue-600",size:20})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-slate-800",children:"AI Scan Candidates"}),e.jsx("p",{className:"text-xs text-slate-400 mt-0.5",children:c("candidates.title")})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[g&&!h&&e.jsxs("button",{onClick:g,disabled:f,className:`flex items-center gap-1.5 px-3.5 py-2 rounded-lg text-xs font-bold transition-all ${f?"text-slate-400 bg-slate-100 cursor-not-allowed":"text-white bg-gradient-to-r from-violet-500 to-purple-600 hover:from-violet-600 hover:to-purple-700 shadow-sm hover:shadow"}`,title:c("candidates.coldStartTitle"),children:[f?e.jsx(Fe,{size:14,className:"animate-spin"}):e.jsx(Xt,{size:14}),c(f?"common.loading":"candidates.sourceBootstrap")]}),ke&&ke.total>0&&e.jsxs("button",{onClick:ne,disabled:Z||H,className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-all ${Z||H?"text-slate-400 bg-slate-100 cursor-not-allowed":"text-amber-700 bg-amber-50 border border-amber-200 hover:bg-amber-100"}`,title:c("candidates.enrichTitle"),children:[Z?e.jsx(Fe,{size:14,className:"animate-spin"}):e.jsx(fs,{size:14}),c(Z?"common.loading":"candidates.aiRefine")]}),ke&&ke.total>0&&e.jsxs("button",{onClick:He,disabled:H||Z||_,className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-all ${H||Z||_?"text-slate-400 bg-slate-100 cursor-not-allowed":"text-emerald-700 bg-emerald-50 border border-emerald-200 hover:bg-emerald-100"}`,title:c("candidates.refineTitle"),children:[H||_?e.jsx(Fe,{size:14,className:"animate-spin"}):e.jsx(Qe,{size:14}),c(H||_?"common.loading":"candidates.aiRefine")]}),ke&&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-slate-50 border border-slate-100",children:[e.jsx(La,{size:14,className:"text-slate-400"}),e.jsx("span",{className:"text-slate-500",children:c("candidates.totalCount",{count:ke.total})}),ke.withCode<ke.total&&e.jsx("span",{className:"text-slate-400 ml-1",children:c("candidates.withCode",{count:ke.withCode})})]}),e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-emerald-50 border border-emerald-100",children:[e.jsx("span",{className:"text-emerald-500",children:c("candidates.confidence")}),e.jsxs("strong",{className:"text-emerald-700",children:[Math.round(ke.avgConfidence*100),"%"]})]})]})]})]}),M&&e.jsx(Zr,{refine:M,isRefineDone:m,onDismiss:()=>{N(),x==null||x()}}),L.length>0&&e.jsx("div",{className:"shrink-0 bg-white border border-slate-100 rounded-xl px-3 py-2 mb-4 shadow-sm",children:e.jsx("div",{className:"flex items-center gap-1.5 overflow-x-auto no-scrollbar",children:Q.map(r=>{var de;s(r);const k=a(r),b=ms[r]?c(ms[r]):void 0,B=t.candidates[r],D=((de=B==null?void 0:B.items)==null?void 0:de.length)??0,U=ie===r,te=ct[r]||ct.All;return e.jsxs("button",{onClick:()=>be(r),className:`flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-bold whitespace-nowrap transition-all border
87
+ ${U?`${(te==null?void 0:te.bg)||"bg-blue-50"} ${(te==null?void 0:te.color)||"text-blue-700"} ${(te==null?void 0:te.border)||"border-blue-200"} shadow-sm ring-1 ring-inset ${(te==null?void 0:te.border)||"ring-blue-200"}`:"bg-slate-50/80 text-slate-600 border-slate-100 hover:border-slate-200 hover:bg-slate-100"}`,children:[(()=>{const me=(te==null?void 0:te.icon)||ws;return e.jsx(me,{size:F.sm,className:U?"":"text-slate-400"})})(),e.jsx("span",{children:hs[r]?c(hs[r]):r}),k&&b&&e.jsx("span",{className:"text-[9px] text-amber-600 border border-amber-200 px-1 rounded",children:b}),e.jsx("span",{className:`text-[10px] font-normal rounded-full px-1.5 ${U?"bg-white/60":"bg-slate-200/60 text-slate-400"}`,children:D})]},r)})})}),e.jsxs("div",{className:"flex-1 overflow-y-auto pr-1",children:[(!(t!=null&&t.candidates)||Object.keys(t.candidates).length===0)&&!h&&e.jsxs("div",{className:"h-72 flex flex-col items-center justify-center bg-white rounded-2xl border border-dashed border-slate-200 text-slate-400",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-slate-50 flex items-center justify-center mb-4",children:e.jsx(Ma,{size:32,className:"text-slate-300"})}),e.jsx("p",{className:"text-sm font-medium text-slate-500",children:c("candidates.noResults")}),e.jsx("p",{className:"mt-2 text-xs max-w-sm text-center leading-relaxed text-slate-400",children:c("candidates.emptyHint")}),g&&e.jsxs("button",{onClick:g,disabled:f,className:`mt-4 flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${f?"text-slate-400 bg-slate-100 cursor-not-allowed":"text-white bg-gradient-to-r from-violet-500 to-purple-600 hover:from-violet-600 hover:to-purple-700 shadow-md hover:shadow-lg"}`,children:[f?e.jsx(Fe,{size:16,className:"animate-spin"}):e.jsx(Xt,{size:16}),c(f?"common.loading":"candidates.sourceBootstrap")]}),e.jsxs("p",{className:"mt-3 text-[11px] text-slate-400",children:["或 ",e.jsx("code",{className:"text-blue-600 bg-blue-50 px-1 rounded",children:"asd ais --all"})," ",c("candidates.fullScanBtn"),e.jsx("code",{className:"text-blue-600 bg-blue-50 px-1 rounded ml-1",children:"asd candidate"})," ",c("candidates.clipboardCreate")]})]}),(!(t!=null&&t.candidates)||Object.keys(t.candidates).length===0)&&h&&e.jsxs("div",{className:"h-72 flex flex-col items-center justify-center bg-white rounded-2xl border border-dashed border-violet-200 text-slate-400",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-violet-50 flex items-center justify-center mb-4",children:e.jsx(Fe,{size:32,className:"text-violet-400 animate-spin"})}),e.jsx("p",{className:"text-sm font-medium text-violet-600",children:c("common.loading")}),e.jsx("p",{className:"mt-2 text-xs max-w-sm text-center leading-relaxed text-slate-400",children:c("candidates.scanningHint")})]}),t&&ie&&T.filter(([r])=>r===ie).map(([r,k])=>{const b=s(r),B=a(r),D=ms[r]?c(ms[r]):c("candidates.silent"),U=y[r]||{page:1,pageSize:12},te=U.page,de=U.pageSize,me=k.items.filter(J=>{var Le;if(fe.onlySimilar){const qe=(Le=J.relations)==null?void 0:Le.related;if(!Array.isArray(qe)||qe.length===0)return!1}return!0}).sort((J,Le)=>{var qe,ze,Ve,ge,Oe,We;if(fe.sort==="default")return 0;if(fe.sort==="score-desc")return(((qe=Le.quality)==null?void 0:qe.overall)??0)-(((ze=J.quality)==null?void 0:ze.overall)??0);if(fe.sort==="score-asc")return(((Ve=J.quality)==null?void 0:Ve.overall)??0)-(((ge=Le.quality)==null?void 0:ge.overall)??0);if(fe.sort==="confidence-desc")return(((Oe=Le.reasoning)==null?void 0:Oe.confidence)??0)-(((We=J.reasoning)==null?void 0:We.confidence)??0);if(fe.sort==="date-desc"){const Ge=typeof J.createdAt=="number"?J.createdAt:0;return(typeof Le.createdAt=="number"?Le.createdAt:0)-Ge}return 0}),I=me.length,V=Math.ceil(I/de),Ce=(te-1)*de,Ae=me.slice(Ce,Ce+de),Re=J=>{W(Le=>({...Le,[r]:{...U,page:J}}))},Be=J=>{W(Le=>({...Le,[r]:{page:1,pageSize:J}}))},Ye=ct[r]||ct.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-white border border-slate-100 shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[(()=>{const J=(Ye==null?void 0:Ye.icon)||ws;return e.jsx(J,{size:18,className:(Ye==null?void 0:Ye.color)||"text-blue-600"})})(),e.jsx("span",{className:"text-base font-bold text-slate-800 truncate",children:hs[r]?c(hs[r]):r}),B&&e.jsx("span",{className:"text-[10px] font-bold text-amber-600 border border-amber-200 bg-amber-50 px-1.5 py-0.5 rounded",children:D}),b&&!B&&e.jsx("span",{className:"text-[10px] font-bold text-slate-400 border border-slate-200 bg-slate-50 px-1.5 py-0.5 rounded",children:"SHELL"}),e.jsxs("span",{className:"text-[11px] text-slate-400 flex items-center gap-1",children:[e.jsx(xt,{size:11}),c("candidates.scannedAt",{time:Wt(k.scanTime,c)||new Date(k.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-slate-50 border border-slate-100",children:[e.jsx(Pa,{size:12,className:"text-slate-400"}),e.jsxs("select",{className:"text-[11px] font-medium bg-transparent border-none outline-none text-slate-600 pr-1 cursor-pointer",value:fe.sort,onChange:J=>he(Le=>({...Le,sort:J.target.value})),children:[e.jsx("option",{value:"default",children:c("candidates.sortNewest")}),e.jsxs("option",{value:"score-desc",children:[c("candidates.sortConfidence")," ↓"]}),e.jsxs("option",{value:"score-asc",children:[c("candidates.sortConfidence")," ↑"]}),e.jsxs("option",{value:"confidence-desc",children:[c("candidates.confidence")," ↓"]}),e.jsx("option",{value:"date-desc",children:c("candidates.sortOldest")})]})]}),e.jsxs("label",{className:"text-[11px] font-medium text-slate-500 flex items-center gap-1.5 px-2 py-1 rounded-lg bg-slate-50 border border-slate-100 cursor-pointer hover:bg-slate-100 transition-colors select-none",children:[e.jsx("input",{type:"checkbox",checked:fe.onlySimilar,onChange:J=>he(Le=>({...Le,onlySimilar:J.target.checked})),className:"rounded text-blue-600 w-3 h-3"}),c("candidates.similarOnly")]}),(fe.sort!=="default"||fe.onlySimilar)&&e.jsx("button",{onClick:()=>he({sort:"default",onlySimilar:!1}),className:"text-[11px] font-medium text-slate-500 hover:text-slate-700 px-2 py-1 rounded-lg border border-slate-200 bg-white hover:bg-slate-50 transition-colors",children:c("candidates.resetFilters")})]}),e.jsx("div",{className:"h-5 w-px bg-slate-200"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[11px] text-slate-400 font-medium",children:c("candidates.totalCount",{count:I})}),e.jsx("button",{onClick:()=>p(Ae,r),className:"text-[11px] font-bold text-blue-600 hover:text-blue-700 px-2.5 py-1.5 rounded-lg hover:bg-blue-50 transition-colors",children:c("candidates.approveCurrentPage")}),e.jsx("button",{onClick:async()=>{if(!window.confirm(c("candidates.batchDeleteConfirm",{count:Ae.length})))return;const Le=(await Promise.allSettled(Ae.map(qe=>d(r,qe.id)))).filter(qe=>qe.status==="rejected").length;Le>0&&re(`${Le} ${c("common.deleteFailed")}`,{title:c("common.operationFailed"),type:"error"}),x==null||x()},className:"text-[11px] font-bold text-orange-500 hover:text-orange-600 px-2.5 py-1.5 rounded-lg hover:bg-orange-50 transition-colors",children:c("candidates.removeCurrentPage")}),e.jsx("button",{onClick:()=>i(r),className:"text-[11px] font-bold text-red-500 hover:text-red-600 px-2.5 py-1.5 rounded-lg hover:bg-red-50 transition-colors border border-red-200",children:c("candidates.deleteAll")})]})]}),e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3",children:Ae.map(J=>{var pt,Mt,Ft,zt,$e;const Le=j===J.id,qe=((pt=J.reasoning)==null?void 0:pt.confidence)??null,ze=(((Mt=J.quality)==null?void 0:Mt.overall)??0)>0?J.quality.overall:null,ge=(((Ft=J.relations)==null?void 0:Ft.related)||[])[0],Oe=we[J.id]||[],We=ma[J.source||""]||{labelKey:J.source||"",color:"text-slate-500 bg-slate-50 border-slate-200"},Ge=ct[J.category||""]||ct.All||{};return e.jsxs("div",{onClick:()=>w(Le?null:J.id),className:`bg-white rounded-xl border overflow-hidden hover:shadow-lg transition-all duration-200 flex flex-col group cursor-pointer
88
+ ${b?"opacity-75":""}
89
+ ${Le?"ring-2 ring-blue-300 border-blue-300 shadow-md":"border-slate-200 hover:border-slate-300"}`,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 ${(Ge==null?void 0:Ge.bg)||"bg-slate-50"} ${(Ge==null?void 0:Ge.color)||"text-slate-400"} ${(Ge==null?void 0:Ge.border)||"border-slate-100"}`,children:[(()=>{const Je=(Ge==null?void 0:Ge.icon)||lt;return e.jsx(Je,{size:10})})(),J.category||"general"]}),J.knowledgeType&&e.jsx("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-indigo-50 text-indigo-600 border border-indigo-100",children:J.knowledgeType}),J.source&&J.source!=="unknown"&&e.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border ${We.color}`,children:We.labelKey.startsWith("candidates.")?c(We.labelKey):We.labelKey}),J.complexity&&e.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border
90
+ ${J.complexity==="advanced"?"bg-red-50 text-red-600 border-red-100":J.complexity==="intermediate"?"bg-amber-50 text-amber-600 border-amber-100":"bg-emerald-50 text-emerald-600 border-emerald-100"}`,children:J.complexity==="advanced"?c("candidates.confidenceHigh"):J.complexity==="intermediate"?c("candidates.confidenceMedium"):c("candidates.confidenceLow")})]}),e.jsx("h3",{className:"font-bold text-sm text-slate-800 leading-snug mb-1 line-clamp-1",children:J.title}),e.jsx("p",{className:"text-xs text-slate-500 line-clamp-2 leading-relaxed",children:J.description||""})]}),e.jsxs("div",{className:"flex flex-col items-center gap-1 shrink-0",children:[e.jsx(an,{value:qe}),e.jsx("span",{className:"text-[9px] text-slate-400 font-medium",children:c("candidates.confidence")})]})]})}),((zt=J.reasoning)==null?void 0:zt.whyStandard)&&!/^Submitted via /i.test(J.reasoning.whyStandard)&&e.jsx("div",{className:"px-4 py-2 bg-gradient-to-r from-indigo-50/50 to-transparent border-t border-indigo-50",children:e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx(rs,{size:12,className:"text-indigo-400 mt-0.5 shrink-0"}),e.jsx("p",{className:"text-[11px] text-indigo-600/80 line-clamp-1 leading-relaxed",children:J.reasoning.whyStandard})]})}),(ze!=null||ge)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 px-4 py-2 border-t border-slate-50",children:[ze!=null&&e.jsxs("span",{className:"text-[10px] font-bold px-2 py-0.5 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200 flex items-center gap-1",children:[e.jsx(cs,{size:10}),c("candidates.overallScore",{score:(ze*100).toFixed(0)+"%"})]}),ge&&e.jsxs("button",{onClick:Je=>{Je.stopPropagation();const st=String(ge.target||"").trim();st&&xe(J,r,st,Oe)},className:"text-[10px] font-bold px-2 py-0.5 rounded-full bg-amber-50 text-amber-700 border border-amber-200 hover:bg-amber-100 transition-colors flex items-center gap-1",title:c("candidates.viewDetail"),children:[e.jsx(ys,{size:10}),c("candidates.similarPrefix")," ",Ue.get(String(ge.target||""))||String(ge.target||"").replace(/\.md$/i,"")]})]}),(($e=J.content)==null?void 0:$e.pattern)&&e.jsxs("div",{className:"overflow-hidden border-t border-slate-200/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(Ht,{size:11,className:"text-slate-500"}),e.jsx("span",{className:"text-[10px] text-slate-400 font-mono uppercase tracking-wide",children:J.language||"code"})]}),e.jsx("span",{className:"text-[10px] text-slate-500 font-mono tabular-nums",children:c("candidates.linesCount",{count:J.content.pattern.split(`
91
+ `).length})})]}),e.jsxs("div",{className:"relative max-h-[80px] overflow-hidden",children:[e.jsx(dt,{code:tn(J.content.pattern,3),language:J.language==="objc"?"objectivec":J.language,className:"!rounded-none"}),J.content.pattern.split(`
92
+ `).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-slate-100 bg-slate-50/50 dark:bg-[#252a36] dark:border-slate-700 mt-auto",onClick:Je=>Je.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap min-w-0",children:[J.trigger&&e.jsx("span",{className:"text-[10px] font-mono px-2 py-0.5 rounded-md bg-white border border-slate-200 text-slate-600 font-bold",children:J.trigger}),e.jsx("span",{className:"text-[10px] uppercase font-bold text-slate-400 bg-white border border-slate-200 px-1.5 py-0.5 rounded-md",children:J.language}),J.tags&&J.tags.length>0&&J.tags.slice(0,3).map((Je,st)=>e.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded-md bg-blue-50 text-blue-600 border border-blue-100 font-medium",children:typeof Je=="string"?Je:String(Je)},st)),J.tags&&J.tags.length>3&&e.jsxs("span",{className:"text-[9px] text-slate-400",children:["+",J.tags.length-3]}),J.createdAt&&Wt(J.createdAt,c)&&e.jsxs("span",{className:"text-[9px] text-slate-400 flex items-center gap-0.5",children:[e.jsx(xt,{size:9}),Wt(J.createdAt,c)]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[e.jsx("button",{onClick:()=>Ie(J.id),disabled:S.has(J.id),title:c("candidates.enrichTitleSingle"),className:`p-1.5 rounded-lg transition-colors flex items-center gap-1 text-[11px] font-medium ${S.has(J.id)?"text-slate-300 cursor-not-allowed":"text-amber-500 hover:text-amber-600 hover:bg-amber-50"}`,children:S.has(J.id)?e.jsx(Fe,{size:14,className:"animate-spin"}):e.jsx(fs,{size:14})}),e.jsx("button",{onClick:()=>Pe(J.id),disabled:z.has(J.id),title:c("candidates.refineTitleSingle"),className:`p-1.5 rounded-lg transition-colors flex items-center gap-1 text-[11px] font-medium ${z.has(J.id)?"text-slate-300 cursor-not-allowed":"text-emerald-500 hover:text-emerald-600 hover:bg-emerald-50"}`,children:z.has(J.id)?e.jsx(Fe,{size:14,className:"animate-spin"}):e.jsx(Qe,{size:14})}),e.jsx("button",{onClick:()=>{d(r,J.id),j===J.id&&(w(null),je(null))},title:c("common.delete"),className:"p-1.5 hover:bg-red-50 text-slate-400 hover:text-red-500 rounded-lg transition-colors",children:e.jsx(ot,{size:14})}),e.jsxs("button",{onClick:()=>u(J,r),className:"text-[11px] font-bold text-blue-600 hover:text-blue-700 px-3 py-1.5 rounded-lg bg-blue-50 hover:bg-blue-100 transition-colors flex items-center gap-1",children:[e.jsx(Et,{size:12})," ",c("candidates.approveAndSave")]}),J.lifecycle==="pending"&&e.jsxs("button",{onClick:async()=>{try{await se.promoteCandidateToRecipe(J.id),re(c("candidates.approveSuccess"),{title:c("candidates.approveSuccess")}),x==null||x()}catch(Je){re(Je.message,{title:c("common.operationFailed"),type:"error"})}},className:"text-[11px] font-bold text-emerald-600 hover:text-emerald-700 px-3 py-1.5 rounded-lg bg-emerald-50 hover:bg-emerald-100 transition-colors flex items-center gap-1",title:c("candidates.approve"),children:[e.jsx(Xt,{size:12})," ",c("candidates.approve")]})]})]})]},J.id)})}),I>12&&e.jsx(Js,{currentPage:te,totalPages:V,totalItems:I,pageSize:de,onPageChange:Re,onPageSizeChange:Be})]},r)})]}),j&&ie&&((Ne=t==null?void 0:t.candidates)==null?void 0:Ne[ie])&&(()=>{var Ye,J,Le,qe,ze,Ve;const r=t.candidates[ie].items,k=r.find(ge=>ge.id===j);if(!k)return null;const b=ae[j]||k,B=r.findIndex(ge=>ge.id===j),D=B>0,U=B<r.length-1,te=()=>{D&&(w(r[B-1].id),je(null))},de=()=>{U&&(w(r[B+1].id),je(null))},me=b.reasoning,I=(me==null?void 0:me.whyStandard)&&!/^Submitted via /i.test(me.whyStandard),V=me&&(I||me.sources&&me.sources.length>0||me.confidence!=null),Ce=we[b.id]||[],Ae=v===b.id,Re=ct[b.category||""]||ct.All||{},Be=ma[b.source||""]||{labelKey:b.source||"",color:"text-slate-500 bg-slate-50 border-slate-200"};return e.jsxs(Ze,{className:"z-30 flex justify-end",onClick:()=>{w(null),je(null)},children:[e.jsx(Ze.Backdrop,{className:"bg-black/15 backdrop-blur-[1px]"}),ce&&(()=>{const ge=ce.candidate,Oe=ge.language==="objc"||ge.language==="objective-c"?"objectivec":ge.language||"text",We=()=>{var Je,st;const $e=[];(Je=ge.content)!=null&&Je.pattern&&$e.push("## Snippet / Code Reference\n\n```"+Oe+`
93
+ `+ge.content.pattern+"\n```"),(st=ge.content)!=null&&st.markdown?$e.push(`
94
+ ## `+c("candidates.projectProfile")+`
95
+
96
+ `+ge.content.markdown):ge.doClause&&$e.push(`
97
+ ## AI Context / Usage Guide
98
+
99
+ `+ge.doClause),navigator.clipboard.writeText($e.join(`
100
+ `)||"").then(()=>re(c("common.copied"),{title:c("common.copied")}))},Ge=()=>{const $e=Ws(ce.recipeContent);navigator.clipboard.writeText($e).then(()=>re(c("common.copied"),{title:c("common.copied")}))},pt=async $e=>{var st;if($e===ce.recipeName)return;const Je=ce.recipeContents[$e];if(Je)je(A=>A?{...A,recipeName:$e,recipeContent:Je}:null);else{let A="";const le=(st=t==null?void 0:t.recipes)==null?void 0:st.find(Y=>Y.name===$e||Y.name.endsWith("/"+$e));if(le!=null&&le.content)A=[le.content.pattern,le.content.markdown].filter(Boolean).join(`
101
+
102
+ `)||"";else try{A=(await se.getRecipeContentByName($e)).content}catch{return}je(Y=>Y?{...Y,recipeName:$e,recipeContent:A,recipeContents:{...Y.recipeContents,[$e]:A}}:null)}},Mt=async()=>{if(window.confirm(c("common.areYouSure")))try{await d(ce.targetName,ge.id),je(null)}catch($e){re(($e==null?void 0:$e.message)||c("common.deleteFailed"),{title:c("common.deleteFailed"),type:"error"})}},Ft=()=>{u(ge,ce.targetName),je(null)},zt=()=>{var Je;const $e=(Je=t==null?void 0:t.recipes)==null?void 0:Je.find(st=>st.name===ce.recipeName||st.name.endsWith("/"+ce.recipeName));$e?n==null||n($e):n==null||n({name:ce.recipeName,content:{markdown:ce.recipeContent}}),je(null)};return e.jsxs("div",{className:`relative h-full bg-white dark:bg-[#1e1e1e] shadow-2xl flex flex-col border-l border-slate-200 dark:border-slate-700 ${C?"w-[800px] max-w-[55vw]":"w-[600px] max-w-[45vw]"}`,style:{animation:"slideInRight 0.2s ease-out"},onClick:$e=>$e.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3.5 border-b border-slate-200 dark:border-slate-700 shrink-0 bg-emerald-50/60 dark:bg-emerald-900/20",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-gradient-to-br from-emerald-500 to-teal-600 flex items-center justify-center",children:e.jsx(ys,{size:16,className:"text-white"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-bold text-sm text-emerald-800 truncate",children:c("candidates.recipeCompare")}),e.jsx("span",{className:"text-[11px] text-emerald-600 truncate block",children:ce.recipeName.replace(/\.md$/i,"")})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 ml-2",children:[e.jsx("button",{onClick:()=>Ge(),className:"p-1.5 hover:bg-emerald-100 rounded-lg text-emerald-600 transition-colors",title:c("common.copy"),children:e.jsx(qt,{size:14})}),e.jsx("button",{onClick:zt,className:"text-[11px] font-medium text-emerald-600 hover:bg-emerald-100 px-2 py-1.5 rounded-lg transition-colors",children:c("candidates.approveAndSave")}),e.jsx("button",{onClick:()=>je(null),className:"p-1.5 hover:bg-slate-200 rounded-lg transition-colors text-slate-400",children:e.jsx(Xe,{size:16})})]})]}),ce.similarList.length>1&&e.jsx("div",{className:"flex flex-wrap gap-1 px-5 py-2 border-b border-slate-100 bg-white shrink-0",children:ce.similarList.map($e=>e.jsxs("button",{onClick:()=>pt($e.recipeName),className:`text-[10px] font-bold px-2 py-1 rounded transition-colors ${ce.recipeName===$e.recipeName?"bg-emerald-200 text-emerald-800":"bg-white text-emerald-600 hover:bg-emerald-50 border border-emerald-100"}`,children:[$e.recipeName.replace(/\.md$/i,"")," ",($e.similarity*100).toFixed(0),"%"]},$e.recipeName))}),e.jsxs("div",{className:"flex items-center gap-1.5 px-5 py-2 border-b border-slate-100 bg-white shrink-0",children:[e.jsxs("button",{onClick:Mt,className:"text-xs font-medium text-red-600 hover:bg-red-50 px-2.5 py-1.5 rounded-lg transition-colors flex items-center gap-1",children:[e.jsx(ot,{size:12})," ",c("common.delete")]}),e.jsxs("button",{onClick:Ft,className:"text-xs font-medium text-blue-600 hover:bg-blue-50 px-2.5 py-1.5 rounded-lg transition-colors flex items-center gap-1",children:[e.jsx(Et,{size:12})," ",c("candidates.approveAndSave")]}),e.jsxs("button",{onClick:()=>We(),className:"text-xs font-medium text-slate-500 hover:bg-slate-50 px-2.5 py-1.5 rounded-lg transition-colors flex items-center gap-1",children:[e.jsx(qt,{size:12})," ",c("common.copy")]})]}),e.jsx("div",{className:"flex-1 overflow-auto p-5 min-h-0",children:e.jsx(gt,{content:ce.recipeContent,stripFrontmatter:!0})})]})})(),e.jsxs("div",{className:`relative h-full bg-white dark:bg-[#1e1e1e] shadow-2xl flex flex-col border-l border-slate-200 dark:border-slate-700 ${C?"w-[960px] max-w-[92vw]":"w-[700px] max-w-[92vw]"}`,style:{animation:"slideInRight 0.25s ease-out"},onClick:ge=>ge.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-slate-200 dark:border-slate-700 bg-gradient-to-b from-white to-slate-50/50 dark:from-[#252526] dark:to-[#1e1e1e] shrink-0",children:[e.jsx("div",{className:"flex-1 min-w-0 mr-3",children:e.jsx("h3",{className:"font-bold text-slate-800 text-lg leading-snug break-words",children:b.title})}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx("button",{onClick:te,disabled:!D,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors disabled:opacity-30",title:c("common.back"),children:e.jsx(is,{size:F.md})}),e.jsxs("span",{className:"text-xs text-slate-400 tabular-nums",children:[B+1,"/",r.length]}),e.jsx("button",{onClick:de,disabled:!U,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors disabled:opacity-30",title:c("common.more"),children:e.jsx(rt,{size:F.md})}),e.jsx("div",{className:"w-px h-5 bg-slate-200 mx-1"}),e.jsx("button",{onClick:E,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors text-slate-400",title:c(C?"common.collapse":"common.expand"),children:C?e.jsx(Gs,{size:F.md}):e.jsx(Cs,{size:F.md})}),e.jsx("button",{onClick:()=>{d(ie,b.id),w(null),je(null)},className:"p-1.5 hover:bg-red-50 rounded-lg text-red-500 transition-colors",title:c("common.delete"),children:e.jsx(ot,{size:F.md})}),e.jsx("button",{onClick:()=>{w(null),je(null)},className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors",children:e.jsx(Xe,{size:F.md})})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:`text-[10px] font-bold px-1.5 py-0.5 rounded uppercase flex items-center gap-1 border ${(Re==null?void 0:Re.bg)||"bg-slate-50"} ${(Re==null?void 0:Re.color)||"text-slate-400"} ${(Re==null?void 0:Re.border)||"border-slate-100"}`,children:b.category||"general"}),b.knowledgeType&&e.jsx("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-purple-50 text-purple-700 border border-purple-200",children:b.knowledgeType}),b.language&&e.jsx("span",{className:"text-[10px] uppercase font-bold text-slate-500 bg-slate-50 border border-slate-200 px-1.5 py-0.5 rounded",children:b.language}),b.complexity&&e.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border ${b.complexity==="advanced"?"bg-red-50 text-red-600 border-red-100":b.complexity==="intermediate"?"bg-amber-50 text-amber-600 border-amber-100":"bg-emerald-50 text-emerald-600 border-emerald-100"}`,children:b.complexity==="advanced"?c("candidates.confidenceHigh"):b.complexity==="intermediate"?c("candidates.confidenceMedium"):c("candidates.confidenceLow")}),b.trigger&&e.jsx("span",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-amber-50 text-amber-700 border border-amber-200 font-bold",children:b.trigger}),b.source&&b.source!=="unknown"&&e.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border ${Be.color}`,children:Be.labelKey.startsWith("candidates.")?c(Be.labelKey):Be.labelKey}),b.lifecycle&&b.lifecycle!=="pending"&&e.jsx("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-200",children:b.lifecycle})]}),e.jsx("div",{className:"flex flex-wrap gap-x-5 gap-y-2 text-xs",children:(()=>{const ge=[];return b.scope&&ge.push({icon:Pt,iconClass:"text-teal-400",label:c("candidates.path"),value:b.scope==="universal"?c("common.all"):b.scope==="project-specific"||b.scope==="module-level"?c("candidates.category"):b.scope}),b.source&&b.source!=="unknown"&&ge.push({icon:Pt,iconClass:"text-violet-400",label:c("candidates.source"),value:Be.labelKey.startsWith("candidates.")?c(Be.labelKey):Be.labelKey}),b.createdAt&&Wt(b.createdAt,c)&&ge.push({icon:xt,iconClass:"text-slate-400",label:c("candidates.createdAt"),value:Wt(b.createdAt,c)}),ge.map((Oe,We)=>{const Ge=Oe.icon;return e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ge,{size:11,className:`${Oe.iconClass} shrink-0`}),e.jsx("span",{className:"text-slate-400",children:Oe.label}),e.jsx("span",{className:`font-medium text-slate-600 ${Oe.mono?"font-mono text-[11px]":""}`,children:Oe.value})]},We)})})()})]}),b.tags&&b.tags.length>0&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100 flex flex-wrap items-center gap-1.5",children:[e.jsx(ls,{size:11,className:"text-slate-300 mr-0.5"}),b.tags.slice(0,10).map((ge,Oe)=>e.jsx("span",{className:"text-[9px] px-2 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100 font-medium",children:typeof ge=="string"?ge:String(ge)},Oe))]}),b.description&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-1.5 block",children:c("candidates.description")}),e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:b.description})]}),V&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(jt,{size:11,className:"text-amber-400"})," ",c("knowledge.reasoning")]}),e.jsxs("div",{className:"bg-amber-50/30 dark:bg-amber-900/15 border border-amber-100 dark:border-amber-800/40 rounded-xl p-4 space-y-2.5",children:[me.whyStandard&&!/^Submitted via /i.test(me.whyStandard)&&e.jsx("p",{className:"text-sm text-slate-700 leading-relaxed",children:me.whyStandard}),me.sources&&me.sources.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsxs("span",{className:"text-[10px] text-slate-400 font-bold",children:[c("candidates.source"),":"]}),me.sources.map((ge,Oe)=>e.jsx("code",{className:"text-[10px] px-2 py-0.5 bg-white border border-amber-200 rounded text-amber-700 font-mono",children:ge},Oe))]}),me.confidence!=null&&me.confidence>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-[10px] text-slate-400 font-bold",children:[c("candidates.confidence"),":"]}),e.jsx("div",{className:"flex-1 max-w-[160px] h-1.5 bg-slate-200 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-amber-400 rounded-full",style:{width:`${Math.round((me.confidence??0)*100)}%`}})}),e.jsxs("span",{className:"text-[10px] font-bold text-amber-600",children:[Math.round((me.confidence??0)*100),"%"]})]}),me.alternatives&&me.alternatives.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 pt-1",children:[e.jsxs("span",{className:"text-[10px] text-slate-400 font-bold",children:[c("candidates.viewDetail"),":"]}),me.alternatives.map((ge,Oe)=>e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-slate-100 border border-slate-200 rounded text-slate-600",children:ge},Oe))]})]})]}),b.quality&&b.quality.grade&&b.quality.grade!=="F"&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:c("candidates.qualityDimensions")}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("span",{className:`text-2xl font-black ${b.quality.grade==="A"?"text-emerald-600":b.quality.grade==="B"?"text-blue-600":b.quality.grade==="C"?"text-amber-600":b.quality.grade==="D"?"text-orange-600":"text-slate-400"}`,children:b.quality.grade}),e.jsxs("div",{className:"flex-1 grid grid-cols-3 gap-2 text-[10px]",children:[b.quality.completeness!=null&&b.quality.completeness>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-slate-700",children:b.quality.completeness}),e.jsx("div",{className:"text-slate-400",children:c("candidates.qualityDimensions")})]}),b.quality.adaptation!=null&&b.quality.adaptation>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-slate-700",children:b.quality.adaptation}),e.jsx("div",{className:"text-slate-400",children:c("candidates.qualityDimensions")})]}),b.quality.documentation!=null&&b.quality.documentation>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-slate-700",children:b.quality.documentation}),e.jsx("div",{className:"text-slate-400",children:c("candidates.qualityDimensions")})]})]})]})]}),(()=>{const ge=b.relations?Object.entries(b.relations).flatMap(([We,Ge])=>Array.isArray(Ge)?Ge.map(pt=>({...pt,type:We})):[]):[];return b.agentNotes||b.aiInsight||ge.length>0?e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(Qe,{size:11,className:"text-emerald-400"})," ",c("candidates.refineEnhanced")]}),e.jsxs("div",{className:"bg-emerald-50/30 dark:bg-emerald-900/15 border border-emerald-100 dark:border-emerald-800/40 rounded-xl p-4 space-y-2.5 text-xs",children:[b.aiInsight&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-[10px] text-slate-400 font-bold",children:[c("candidates.viewDetail"),":"]}),e.jsx("p",{className:"text-sm text-slate-700 leading-relaxed mt-0.5",children:b.aiInsight})]}),b.agentNotes&&b.agentNotes.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] text-slate-400 font-bold",children:c("candidates.agentNotes")}),e.jsx("ul",{className:"mt-1 space-y-0.5",children:b.agentNotes.map((We,Ge)=>e.jsxs("li",{className:"flex items-start gap-1.5 text-slate-600",children:[e.jsx("span",{className:"text-emerald-400 mt-0.5",children:"•"}),We]},Ge))})]}),ge.length>0&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-[10px] text-slate-400 font-bold",children:[c("recipes.relations"),":"]}),e.jsx("div",{className:"mt-1 space-y-1",children:ge.map((We,Ge)=>e.jsxs("div",{className:"flex items-start gap-1.5 text-slate-600",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:We.type}),e.jsx("span",{className:"font-medium text-slate-700",children:Ue.get(We.target)||We.target}),We.description&&e.jsxs("span",{className:"text-slate-400",children:["— ",We.description]})]},Ge))})]})]})]}):null})(),Ce.length>0&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[c("candidates.similarRecipe"),Ae&&e.jsx("span",{className:"text-[10px] text-slate-400 animate-pulse",children:c("common.loading")})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:Ce.slice(0,5).map(ge=>e.jsxs("button",{onClick:()=>xe(b,ie,ge.recipeName,Ce),className:"text-[10px] font-bold px-2 py-1 rounded-lg bg-amber-50 text-amber-700 border border-amber-200 hover:bg-amber-100 transition-colors flex items-center gap-1",title:c("candidates.similarWith",{name:ge.recipeName,score:(ge.similarity*100).toFixed(0)}),children:[e.jsx(ys,{size:10}),ge.recipeName.replace(/\.md$/i,"")," ",(ge.similarity*100).toFixed(0),"%"]},ge.recipeName))})]}),((Ye=b.content)==null?void 0:Ye.pattern)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(ht,{size:11,className:"text-emerald-500"})," ",c("knowledge.codePattern")]}),e.jsx(dt,{code:b.content.pattern,language:b.language==="objc"?"objectivec":b.language,showLineNumbers:!0})]}),((J=b.content)==null?void 0:J.markdown)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(nt,{size:11,className:"text-blue-400"})," ",c("knowledge.markdownDoc")]}),e.jsx("div",{className:"bg-blue-50/30 dark:bg-blue-900/15 border border-blue-100 dark:border-blue-800/40 rounded-xl p-4",children:e.jsx("div",{className:"markdown-body text-sm text-slate-700 dark:text-slate-300 leading-relaxed",children:e.jsx(gt,{content:b.content.markdown})})})]}),(b.doClause||b.whenClause||b.dontClause||b.topicHint||b.coreCode)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(lt,{size:11,className:"text-indigo-400"})," Cursor Delivery"]}),e.jsxs("div",{className:"bg-indigo-50/30 dark:bg-indigo-900/15 border border-indigo-100 dark:border-indigo-800/40 rounded-xl p-4 text-xs space-y-1.5",children:[b.topicHint&&e.jsxs("div",{children:[e.jsx("span",{className:"text-indigo-500 font-medium",children:"Topic:"}),e.jsx("span",{className:"text-slate-700",children:b.topicHint})]}),b.whenClause&&e.jsxs("div",{children:[e.jsx("span",{className:"text-blue-500 font-medium",children:"When:"}),e.jsx("span",{className:"text-slate-700",children:b.whenClause})]}),b.doClause&&e.jsxs("div",{children:[e.jsx("span",{className:"text-emerald-500 font-medium",children:"Do:"}),e.jsx("span",{className:"text-slate-700",children:b.doClause})]}),b.dontClause&&e.jsxs("div",{children:[e.jsx("span",{className:"text-red-500 font-medium",children:"Don't:"}),e.jsx("span",{className:"text-slate-700",children:b.dontClause})]}),b.coreCode&&e.jsxs("div",{children:[e.jsx("span",{className:"text-purple-500 font-medium",children:"Core Code:"}),e.jsx("div",{className:"mt-1",children:e.jsx(dt,{code:b.coreCode,language:b.language==="objectivec"||b.language==="objc"?"objectivec":b.language||"text"})})]})]})]}),(b.scope||b.headers&&b.headers.length>0||((Le=b.content)==null?void 0:Le.steps)&&b.content.steps.length>0||((qe=b.content)==null?void 0:qe.rationale))&&e.jsxs(e.Fragment,{children:[((ze=b.content)==null?void 0:ze.rationale)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:c("candidates.rationale")}),e.jsx("div",{className:"bg-slate-50 border border-slate-100 rounded-xl p-4",children:e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:b.content.rationale})})]}),b.headers&&b.headers.length>0&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:c("candidates.headers")}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:b.headers.map((ge,Oe)=>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:ge},Oe))})]}),((Ve=b.content)==null?void 0:Ve.steps)&&b.content.steps.length>0&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:c("recipes.steps")}),e.jsx("div",{className:"space-y-2",children:b.content.steps.map((ge,Oe)=>{if(typeof ge=="string")return e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 border border-slate-100 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:Oe+1}),e.jsx("p",{className:"text-xs text-slate-700 leading-relaxed",children:ge})]},Oe);const We=typeof ge.title=="string"?ge.title:"",Ge=typeof ge.description=="string"?ge.description:"",pt=typeof ge.code=="string"?ge.code:"";return e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 border border-slate-100",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:Oe+1}),We&&e.jsx("span",{className:"text-xs font-bold text-slate-700",children:We})]}),Ge&&e.jsx("p",{className:"text-xs text-slate-600 ml-7 leading-relaxed",children:Ge}),pt&&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:pt})]},Oe)})})]})]})]}),e.jsxs("div",{className:"shrink-0 border-t border-slate-200 dark:border-slate-700 px-5 py-3 bg-gradient-to-b from-slate-50/80 to-white dark:from-[#252526] dark:to-[#1e1e1e] flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:()=>Ie(b.id),disabled:S.has(b.id),title:c("candidates.enrichTitleBottom"),className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium transition-colors ${S.has(b.id)?"text-slate-300 cursor-not-allowed":"text-amber-600 hover:bg-amber-50 border border-amber-200"}`,children:[S.has(b.id)?e.jsx(Fe,{size:14,className:"animate-spin"}):e.jsx(fs,{size:14}),c("candidates.enrichShort")]}),e.jsxs("button",{onClick:()=>Pe(b.id),disabled:z.has(b.id),title:c("candidates.refineTitleBottom"),className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium transition-colors ${z.has(b.id)?"text-slate-300 cursor-not-allowed":"text-emerald-600 hover:bg-emerald-50 border border-emerald-200"}`,children:[z.has(b.id)?e.jsx(Fe,{size:14,className:"animate-spin"}):e.jsx(Qe,{size:14}),c("candidates.refineShort")]}),e.jsxs("button",{onClick:()=>{d(ie,b.id),w(null),je(null)},title:c("common.delete"),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(ot,{size:14})," ",c("common.delete")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[b.lifecycle==="pending"&&e.jsxs("button",{onClick:async()=>{try{await se.promoteCandidateToRecipe(b.id),re(c("candidates.approveSuccess"),{title:c("candidates.approveSuccess")}),x==null||x()}catch(ge){re(ge.message,{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(Xt,{size:14})," ",c("candidates.approve")]}),e.jsxs("button",{onClick:()=>{u(b,ie),w(null),je(null)},className:"flex items-center gap-1.5 px-4 py-2 rounded-lg text-xs font-bold text-white bg-blue-600 hover:bg-blue-700 transition-colors shadow-sm",children:[e.jsx(Et,{size:14})," ",c("candidates.approveAndSave")]})]})]})]})]})})()]})},rn=({isOpen:t,onClose:s,currentFile:a,targetName:l,language:d="",onSelectRecipe:i})=>{var X,H,q,R;const{t:u}=_e(),[p,n]=o.useState(""),[g,f]=o.useState([]),[h,x]=o.useState(null),[c,j]=o.useState(!1),[w,C]=o.useState(null),[E,S]=o.useState(!1),[G,z]=o.useState(null),P=async()=>{if(p.trim()){j(!0);try{const M=await se.search(p,{context:{language:d},limit:10});f((M.items||[]).map(_=>{var m,N,y;return{name:(_.title||_.name||"")+".md",content:((m=_.content)==null?void 0:m.pattern)||((N=_.content)==null?void 0:N.markdown)||((y=_.content)==null?void 0:y.code)||"",similarity:_.score||0,authority:_.authorityScore||0,matchType:_.matchType||"ranked",qualityScore:_.qualityScore||0,usageCount:_.usageCount||0}})),x(null)}catch(M){console.error("Context-aware search failed:",M),alert(u("search.searchFailed"))}finally{j(!1)}}},Z=M=>{M.key==="Enter"&&P()};return t?e.jsxs(Ze,{className:"z-30 flex",children:[e.jsx(Ze.Backdrop,{className:"bg-black/20"}),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:u("search.title")}),e.jsx("button",{onClick:s,className:"p-1 hover:bg-slate-100 rounded-lg transition-colors",children:e.jsx(Xe,{size:F.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(et,{size:F.md,className:"text-blue-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1",children:[((X=h.targetInfo)==null?void 0:X.targetName)&&e.jsxs("div",{className:"text-blue-900 font-medium flex items-center gap-2 mb-1",children:[e.jsx(Xs,{size:F.sm}),"Target: ",h.targetInfo.targetName]}),((H=h.fileInfo)==null?void 0:H.imports)&&h.fileInfo.imports.length>0&&e.jsxs("div",{className:"text-blue-800 text-xs mt-2",children:[e.jsx("strong",{children:u("search.importedFrameworks")})," ",h.fileInfo.imports.slice(0,3).join(", "),h.fileInfo.imports.length>3&&` +${h.fileInfo.imports.length-3}`]}),((q=h.targetInfo)==null?void 0:q.suggestedApis)&&h.targetInfo.suggestedApis.length>0&&e.jsxs("div",{className:"text-blue-800 text-xs mt-1",children:[e.jsx("strong",{children:u("search.relatedApis")})," ",h.targetInfo.suggestedApis.slice(0,3).join(", ")]})]})]})}),e.jsxs("div",{className:"relative",children:[e.jsx(ft,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-400",size:F.md}),e.jsx("input",{type:"text",placeholder:u("search.searchPlaceholder"),value:p,onChange:M=>n(M.target.value),onKeyDown:Z,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:P,disabled:!p.trim()||c,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:[c&&e.jsx(Fe,{size:F.sm,className:"animate-spin"}),u(c?"search.searching":"search.searchBtn")]})]}),e.jsxs("div",{className:"flex-1 overflow-auto",children:[g.length===0&&!c&&e.jsx("div",{className:"flex items-center justify-center h-full text-slate-500",children:e.jsxs("div",{className:"text-center",children:[e.jsx($s,{size:F.xxl,className:"mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:u("search.emptyHint")})]})}),g.map((M,_)=>e.jsxs("div",{className:"border-b border-slate-200 p-4 hover:bg-slate-50 transition-colors cursor-pointer",onClick:()=>{C(w===_?null:_),M.name&&(i==null||i(M.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:M.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(et,{size:F.xs}),Math.round(M.similarity*100),"%"]}),M.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(Xs,{size:F.xs}),u("search.contextRelevant")]}),M.matchType&&e.jsx("span",{className:"text-xs text-slate-500",children:M.matchType==="semantic"?u("search.matchSemantic"):u("search.matchKeyword")})]})]}),e.jsx("button",{onClick:m=>{m.stopPropagation(),C(w===_?null:_)},className:"p-1 hover:bg-slate-200 rounded transition-colors",children:w===_?"▼":"▶"})]}),M.stats&&e.jsxs("div",{className:"text-xs text-slate-500 mb-2 flex gap-3",children:[M.stats.authorityScore!==void 0&&e.jsxs("span",{children:[u("search.authorityScore"),": ",M.stats.authorityScore]}),M.usageCount!==void 0&&e.jsxs("span",{children:[u("search.usage"),": ",u("search.usageCount",{count:M.usageCount})]})]}),w===_&&e.jsxs("div",{className:"mt-3 pt-3 border-t border-slate-200",children:[M.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:u("search.recommendReason")}),e.jsx("p",{children:M.recommendReason})]}),e.jsxs("div",{className:"text-xs text-slate-600 max-h-[200px] overflow-auto bg-slate-50 p-3 rounded",children:[M.content.substring(0,500),"..."]}),e.jsx("button",{onClick:m=>{m.stopPropagation(),z(M),S(!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:u("search.viewFullContent")})]})]},_)),c&&e.jsx("div",{className:"flex items-center justify-center h-32",children:e.jsx(Fe,{size:F.lg,className:"animate-spin text-blue-600"})}),g.length===0&&p&&!c&&e.jsx("div",{className:"flex items-center justify-center h-32",children:e.jsxs("div",{className:"text-center text-slate-500",children:[e.jsx(Ot,{size:F.xl,className:"mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:u("search.noResults")})]})})]})]}),E&&G&&e.jsxs(Ze,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx(Ze.Backdrop,{className:"bg-black/40"}),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:G.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:[u("search.similarity"),": ",Math.round(G.similarity*100),"%"]}),G.isContextRelevant&&e.jsxs("span",{className:"text-xs bg-green-100 text-green-700 px-2 py-1 rounded",children:["✓ ",u("search.contextRelevant")]}),G.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:["🤖 ",u("search.quality"),": ",(G.qualityScore*100).toFixed(0),"%"]}),((R=G.stats)==null?void 0:R.authorityScore)!==void 0&&e.jsxs("span",{className:"text-xs bg-purple-100 text-purple-700 px-2 py-1 rounded",children:[u("search.authorityScore"),": ",Math.round(G.stats.authorityScore*100)/100]})]})]}),e.jsx("button",{onClick:()=>S(!1),className:"p-1 hover:bg-slate-100 rounded transition-colors shrink-0",children:e.jsx(Xe,{size:F.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:G.content?e.jsx(dt,{code:G.content,language:"markdown"}):e.jsx("p",{className:"text-slate-500 text-sm",children:u("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:()=>S(!1),className:"px-4 py-2 text-slate-700 hover:bg-slate-200 rounded transition-colors text-sm font-medium",children:u("common.close")}),i&&e.jsxs("button",{onClick:()=>{i(G.name),S(!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(rt,{size:F.md}),u("search.useSnippet")]})]})]})]})]}):null},ha=t=>Os(t.language)||"text";function nn(t){const s=[],a=t.match(/#import\s+"([^"]+)"/);if(a){const u=a[1].replace(/\.h$/,"");s.push(u)}const l=t.match(/#import\s+<([^>]+)>/);if(l){const u=l[1].replace(/\.h$/,"").split("/");s.push(...u)}const d=t.match(/^import\s+(\w+)/);d&&s.push(d[1]);const i=t.match(/@import\s+(\w+)/);return i&&s.push(i[1]),[...new Set(s.filter(Boolean))]}function Vt(t,s){if(!s||!s.trim())return"unknown";const a=nn(t);return a.length===0?"unknown":a.some(l=>s.includes(l))?"used":"unused"}function on(t){return t.startsWith("#import ")||t.startsWith("import ")||t.startsWith("@import ")?t.trim():t.startsWith("<")||t.startsWith('"')?`#import ${t.trim()}`:t.trim()}const cn=[{value:"",label:"—"},{value:"networking",label:"Networking"},{value:"ui",label:"UI"},{value:"data",label:"Data"},{value:"architecture",label:"Architecture"},{value:"conventions",label:"Conventions"}],dn=t=>{var d;const s=(((d=t.content)==null?void 0:d.pattern)||"").trim();if(!s)return!1;const a=s.split(`
103
+ `).filter(i=>i.trim());return!(a.filter(i=>/^\s*(#{1,6}\s|[-*>]\s|\d+\.\s)/.test(i)).length>a.length*.3)},un=({res:t,index:s,editingCodeIndex:a,setEditingCodeIndex:l,expandedEditIndex:d,setExpandedEditIndex:i,similarityMap:u,handleUpdateScanResult:p,handleSaveExtracted:n,handlePromoteToCandidate:g,openCompare:f,isSavingRecipe:h=!1})=>{var X,H,q;const{t:x}=_e(),[c,j]=o.useState(!1),w=d===s,C=t.headers||[],E=((X=t.content)==null?void 0:X.pattern)||"",S=((H=t.content)==null?void 0:H.markdown)||"",G=t.description||"",z=t.tags||[],P=dn(t),Z=(R,M)=>{p(s,{content:{...t.content||{},[R]:M}})};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(lt,{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(et,{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:R=>p(s,{title:R.target.value})})]}),e.jsxs("div",{className:"flex gap-2 shrink-0 pt-3",children:[g&&e.jsxs("button",{onClick:()=>g(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(Rl,{size:F.md}),"Candidate"]}),e.jsxs("button",{onClick:()=>n(t),disabled:h,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:[h?e.jsx(Fe,{size:F.md,className:"animate-spin"}):e.jsx(Fa,{size:F.md}),x(h?"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:R=>p(s,{trigger:R.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.jsxs("select",{className:"font-bold text-slate-600 dark:text-slate-300 bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 px-2 py-1 rounded-md outline-none text-[11px] focus:ring-2 focus:ring-blue-500/20",value:t.kind||"pattern",onChange:R=>p(s,{kind:R.target.value}),children:[e.jsx("option",{value:"rule",children:"Rule"}),e.jsx("option",{value:"pattern",children:"Pattern"}),e.jsx("option",{value:"fact",children:"Fact"})]})]}),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("select",{className:"font-bold text-slate-600 dark:text-slate-300 bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 px-2 py-1 rounded-md outline-none text-[11px] focus:ring-2 focus:ring-blue-500/20",value:t.topicHint||"",onChange:R=>p(s,{topicHint:R.target.value}),children:cn.map(R=>e.jsx("option",{value:R.value,children:R.label},R.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:x("scanResult.category")}),e.jsx("select",{className:"font-bold text-slate-600 dark:text-slate-300 bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 px-2 py-1 rounded-md outline-none text-[11px] focus:ring-2 focus:ring-blue-500/20",value:t.category||"",onChange:R=>p(s,{category:R.target.value}),children:tr.filter(R=>R!=="All").map(R=>e.jsx("option",{value:R,children:R},R))})]}),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("select",{className:"font-bold text-slate-600 dark:text-slate-300 bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 px-2 py-1 rounded-md outline-none text-[11px] focus:ring-2 focus:ring-blue-500/20",value:Os(t.language),onChange:R=>p(s,{language:R.target.value}),children:Bt.map(R=>e.jsx("option",{value:R.id,children:R.label},R.id))})]})]}),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:()=>p(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:"Snippet+Recipe"}),e.jsx("button",{onClick:()=>p(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.jsxs("select",{className:"font-bold text-slate-600 dark:text-slate-300 bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 px-2 py-1 rounded-md outline-none text-[11px] focus:ring-2 focus:ring-purple-500/20",value:t.difficulty||"intermediate",onChange:R=>p(s,{difficulty:R.target.value,complexity:R.target.value}),children:[e.jsx("option",{value:"beginner",children:x("scanResult.difficultyBeginner")}),e.jsx("option",{value:"intermediate",children:x("scanResult.difficultyIntermediate")}),e.jsx("option",{value:"advanced",children:x("scanResult.difficultyAdvanced")})]})]}),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.jsxs("select",{className:"font-bold text-amber-600 bg-amber-50/60 border border-amber-100 px-2 py-1 rounded-md outline-none text-[11px] focus:ring-2 focus:ring-amber-500/20",value:t.authority??((q=t.stats)==null?void 0:q.authority)??3,onChange:R=>p(s,{authority:parseInt(R.target.value)}),children:[e.jsx("option",{value:"1",children:"⭐ 1"}),e.jsx("option",{value:"2",children:"⭐⭐ 2"}),e.jsx("option",{value:"3",children:"⭐⭐⭐ 3"}),e.jsx("option",{value:"4",children:"⭐⭐⭐⭐ 4"}),e.jsx("option",{value:"5",children:"⭐⭐⭐⭐⭐ 5"})]})]})]}),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:[z.map((R,M)=>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:[R,e.jsx("button",{onClick:()=>{const _=[...z];_.splice(M,1),p(s,{tags:_})},className:"text-blue-400 hover:text-red-500 transition-colors leading-none text-[10px]",title:"{t('scanResult.removeTag')}",children:"×"})]},M)),e.jsx("input",{className:"flex-1 min-w-[80px] text-[11px] text-slate-600 outline-none bg-transparent py-0.5",placeholder:z.length===0?x("scanResult.tagsPlaceholder"):"",onKeyDown:R=>{const M=R.currentTarget,_=M.value.trim();if((R.key==="Enter"||R.key===","||R.key===",")&&_){R.preventDefault();const m=_.replace(/[,,]/g,"").trim();m&&!z.includes(m)&&p(s,{tags:[...z,m]}),M.value=""}else if(R.key==="Backspace"&&!M.value&&z.length>0){const m=[...z];m.pop(),p(s,{tags:m})}},onBlur:R=>{const M=R.currentTarget.value.trim().replace(/[,,]/g,"").trim();M&&!z.includes(M)&&p(s,{tags:[...z,M]}),R.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:()=>i(d===s?null:s),className:`text-[10px] font-bold px-2 py-0.5 rounded-md transition-colors border ${w?"text-blue-700 bg-blue-100 border-blue-300":"text-blue-600 bg-blue-50 border-blue-100 hover:bg-blue-100"}`,children:[x(w?"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:"Snippet:"}),e.jsx("button",{onClick:()=>p(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 R=C.filter(_=>Vt(_,E)==="used").length,M=C.filter(_=>Vt(_,E)==="unused").length;return e.jsxs("span",{className:"text-[9px] text-slate-400",children:[R>0&&e.jsxs("span",{className:"text-green-600 font-bold",children:[R," ",x("scanResult.referenced")]}),R>0&&M>0&&" · ",M>0&&e.jsxs("span",{className:"text-amber-600 font-bold",children:[M," ",x("scanResult.unreferenced")]})]})})()]}),w&&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 R=C.map(M=>on(M));p(s,{headers:R})},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(R=>Vt(R,E)==="unused")&&e.jsx("button",{onClick:()=>{const R=C.filter(M=>Vt(M,E)!=="unused");p(s,{headers:R})},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 R=[...C,sa(t.language)];p(s,{headers:R})},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((R,M)=>{const _=Vt(R,E);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:R,onChange:m=>{const N=[...C];N[M]=m.target.value,p(s,{headers:N})},placeholder:sa(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 m=C.filter((N,y)=>y!==M);p(s,{headers:m})},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")})]},M)})})]})]})]}),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(et,{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:R=>p(s,{doClause:R.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:R=>p(s,{dontClause:R.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:R=>p(s,{whenClause:R.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:G,onChange:R=>p(s,{description:R.target.value,summary:R.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:()=>j(!c),className:`flex items-center gap-1 text-[10px] font-bold px-2 py-1 rounded transition-colors ${c?"text-blue-600 hover:text-blue-700 bg-blue-50":"text-slate-500 hover:text-slate-700 hover:bg-slate-100"}`,children:c?e.jsxs(e.Fragment,{children:[e.jsx(kt,{size:F.xs})," ",x("scanResult.done")]}):e.jsxs(e.Fragment,{children:[e.jsx(Ms,{size:F.xs})," ",x("common.edit")]})})]}),c?e.jsx("textarea",{rows:Math.max(6,(S||"").split(`
104
+ `).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:R=>Z("markdown",R.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:()=>l(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(kt,{size:F.xs})," ",x("scanResult.done")]}):e.jsxs("button",{type:"button",onClick:()=>l(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(Ms,{size:F.xs})," ",x("common.edit")]})]}),a===s?e.jsx("div",{className:"rounded-xl overflow-hidden",children:e.jsx(ks,{value:E,onChange:R=>Z("pattern",R),language:ha(t),height:`${Math.min(12,E.split(`
105
+ `).length)*20+16}px`})}):E?e.jsx(dt,{code:E,language:ha(t),showLineNumbers:!0}):e.jsx("p",{className:"text-xs text-slate-400 italic py-4",children:x("scanResult.noCode")})]}),(()=>{const R=t.candidateId??t.id??`scan-${s}`,M=u[R],_=(M||[]).filter(y=>y.similarity>=.6);if(_.length===0)return null;const m=_.filter(y=>y.similarity>=.85),N=m.length>0;return e.jsxs("div",{className:"space-y-1.5",children:[N&&e.jsxs("div",{className:"flex items-center gap-2 bg-red-50 border border-red-200 rounded-lg px-3 py-2",children:[e.jsx("span",{className:"text-red-500 text-sm",children:"⚠️"}),e.jsx("span",{className:"text-[11px] font-bold text-red-700",children:x("scanResult.highDuplicateRisk")}),m.map(y=>e.jsxs("button",{onClick:()=>f(t,y.recipeName,M||[]),className:"text-[11px] font-bold px-2 py-0.5 rounded bg-red-100 text-red-800 border border-red-300 hover:bg-red-200 transition-colors",children:[y.recipeName.replace(/\.md$/i,"")," ",(y.similarity*100).toFixed(0),"%"]},y.recipeName)),e.jsx("span",{className:"text-[10px] text-red-500",children:x("scanResult.compareBeforeSave")})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 items-center",children:[e.jsx("span",{className:"text-[10px] text-slate-400 font-bold",children:x("scanResult.similarRecipes")}),_.slice(0,5).map(y=>e.jsxs("button",{onClick:()=>f(t,y.recipeName,M||[]),className:`text-[10px] font-bold px-2 py-1 rounded border transition-colors flex items-center gap-1 ${y.similarity>=.85?"bg-red-50 text-red-700 border-red-200 hover:bg-red-100":"bg-amber-50 text-amber-700 border-amber-200 hover:bg-amber-100"}`,title:x("scanResultCard.similarWithClick",{name:y.recipeName,score:(y.similarity*100).toFixed(0)}),children:[e.jsx(ys,{size:F.xs}),y.recipeName.replace(/\.md$/i,"")," ",(y.similarity*100).toFixed(0),"%"]},y.recipeName))]})]})})()]})]})},pn=t=>{const s=(t.language||"").toLowerCase();return["objectivec","objc","objective-c","obj-c"].includes(s)?"objectivec":t.language||"text"},xn=({data:t,onClose:s,onDataChange:a,recipes:l,handleSaveExtracted:d,handleDeleteCandidate:i,onEditRecipe:u,isSavingRecipe:p=!1})=>{var E,S,G,z;const{t:n}=_e(),g=t.candidate,f=pn(g),h=()=>{var H,q;const P=[],Z=((H=g.content)==null?void 0:H.pattern)||"",X=((q=g.content)==null?void 0:q.markdown)||g.doClause||"";Z&&P.push("## Snippet / Code Reference\n\n```"+f+`
106
+ `+Z+"\n```"),X&&P.push(`
107
+ ## AI Context / Usage Guide
108
+
109
+ `+X),navigator.clipboard.writeText(P.join(`
110
+ `)||"").then(()=>re(n("spmCompare.candidateCopied"),{title:n("spmCompare.copied")}))},x=()=>{const P=Ws(t.recipeContent);navigator.clipboard.writeText(P).then(()=>re(n("spmCompare.recipeCopied"),{title:n("spmCompare.copied")}))},c=async P=>{if(P===t.recipeName)return;const Z=t.recipeContents[P];if(Z)a({...t,recipeName:P,recipeContent:Z});else{let X="";const H=l==null?void 0:l.find(q=>q.name===P||q.name.endsWith("/"+P));if(H!=null&&H.content)X=[H.content.pattern,H.content.markdown].filter(Boolean).join(`
111
+
112
+ `)||"";else try{X=(await se.getRecipeContentByName(P)).content}catch{return}a({...t,recipeName:P,recipeContent:X,recipeContents:{...t.recipeContents,[P]:X}})}},j=async()=>{if(!(!g.candidateId||!t.targetName||!i)&&window.confirm(n("spmCompare.deleteConfirm")))try{await i(t.targetName,g.candidateId),s()}catch(P){re((P==null?void 0:P.message)||n("spmCompare.deleteFailed"),{title:n("spmCompare.deleteFailed"),type:"error"})}},w=()=>{d(g),s()},C=()=>{const P=l==null?void 0:l.find(Z=>Z.name===t.recipeName||Z.name.endsWith("/"+t.recipeName));P?u==null||u(P):u==null||u({name:t.recipeName,content:{markdown:t.recipeContent}}),s()};return e.jsxs(Ze,{className:"z-30 flex justify-end",onClick:s,children:[e.jsx(Ze.Backdrop,{className:"bg-black/30 backdrop-blur-[1px]"}),e.jsxs("div",{className:"relative w-[min(96vw,1280px)] h-full bg-white shadow-2xl flex flex-col",style:{animation:"slideInRight 0.25s ease-out"},onClick:P=>P.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-slate-200 shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx("h3",{className:"font-bold text-slate-800",children:n("spmCompare.compareTitle")}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[g.candidateId&&t.targetName&&e.jsx("button",{onClick:j,className:"text-xs text-red-600 hover:bg-red-50 px-2 py-1 rounded transition-colors",children:n("spmCompare.deleteCandidate")}),e.jsxs("button",{onClick:w,disabled:p,className:"text-xs text-blue-600 hover:bg-blue-50 px-2 py-1 rounded disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1 transition-colors",children:[p?e.jsx(Fe,{size:F.xs,className:"animate-spin"}):null,n("spmCompare.auditCandidate")]}),e.jsx("button",{onClick:C,className:"text-xs text-emerald-600 hover:bg-emerald-50 px-2 py-1 rounded transition-colors",children:n("spmCompare.editRecipe")})]})]}),e.jsx("button",{onClick:s,className:"p-2 hover:bg-slate-100 rounded-lg transition-colors shrink-0 ml-2",children:e.jsx(Xe,{size:F.md})})]}),t.similarList.length>1&&e.jsxs("div",{className:"flex flex-wrap gap-1.5 px-5 py-2 border-b border-slate-100 bg-slate-50/50 shrink-0",children:[e.jsx("span",{className:"text-[10px] text-slate-400 font-bold self-center",children:n("spmCompare.switchRecipe")}),t.similarList.map(P=>e.jsxs("button",{onClick:()=>c(P.recipeName),className:`text-[10px] font-bold px-2 py-1 rounded transition-colors ${t.recipeName===P.recipeName?"bg-emerald-200 text-emerald-800":"bg-white text-emerald-600 hover:bg-emerald-100 border border-emerald-200"}`,children:[P.recipeName.replace(/\.md$/i,"")," ",(P.similarity*100).toFixed(0),"%"]},P.recipeName))]}),e.jsxs("div",{className:"flex-1 flex min-h-0",children:[e.jsxs("div",{className:"flex-1 flex flex-col min-w-0 border-r border-slate-200",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-slate-100 bg-blue-50/40 shrink-0",children:[e.jsx("span",{className:"text-xs font-bold text-blue-700 truncate",children:n("spmCompare.candidateTitle",{title:g.title||""})}),e.jsx("button",{onClick:h,className:"p-1 hover:bg-blue-100 rounded text-blue-500 shrink-0",title:n("spmCompare.copyCandidate"),children:e.jsx(qt,{size:F.xs})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e.jsxs("div",{className:"markdown-body text-slate-700 space-y-4",children:[e.jsx("h3",{className:"text-sm font-bold",children:"Snippet / Code Reference"}),(E=g.content)!=null&&E.pattern?e.jsx(dt,{code:((S=g.content)==null?void 0:S.pattern)||"",language:f,className:"!overflow-visible"}):e.jsx("p",{className:"text-slate-400 italic text-xs",children:n("spmCompare.noCode")}),e.jsx("h3",{className:"text-sm font-bold mt-4",children:n("spmCompare.aiContextProfile")}),(G=g.content)!=null&&G.markdown||g.doClause?e.jsx(gt,{content:((z=g.content)==null?void 0:z.markdown)||g.doClause||""}):e.jsx("p",{className:"text-slate-400 italic text-xs",children:n("spmCompare.noGuide")})]})})]}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-slate-100 bg-emerald-50/40 shrink-0",children:[e.jsxs("span",{className:"text-xs font-bold text-emerald-700 truncate",children:["Recipe:",t.recipeName.replace(/\.md$/i,"")]}),e.jsx("button",{onClick:x,className:"p-1 hover:bg-emerald-100 rounded text-emerald-500 shrink-0",title:n("spmCompare.copyRecipe"),children:e.jsx(qt,{size:F.xs})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e.jsx(gt,{content:t.recipeContent,stripFrontmatter:!0})})]})]})]})]})},ga={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"},ba={swift:"Swift",objectivec:"ObjC",go:"Go",python:"Py",java:"Java",kotlin:"KT",javascript:"JS",typescript:"TS",rust:"RS",ruby:"RB",c:"C",cpp:"C++"},mn=({targets:t,filteredTargets:s,selectedTargetName:a,isScanning:l,scanProgress:d,scanFileList:i,scanResults:u,guardAudit:p,handleScanTarget:n,handleScanProject:g,handleUpdateScanResult:f,handleSaveExtracted:h,handlePromoteToCandidate:x,handleDeleteCandidate:c,onEditRecipe:j,isShellTarget:w,recipes:C=[],isSavingRecipe:E=!1,handleRefreshProject:S,onAddCustomFolder:G,onRemoveCustomFolder:z})=>{var Ue,Ie;const{t:P}=_e(),[Z,X]=o.useState(null),[H,q]=o.useState(null),[R,M]=o.useState({}),[_,m]=o.useState(null),[N,y]=o.useState(null),[W,O]=o.useState(!1),[be,we]=o.useState(),[ye,v]=o.useState(),ee=o.useRef(new Set),ae=o.useRef([]),[ue,fe]=o.useState([]),[he,ce]=o.useState(!1),je=o.useRef(!1),$=3,[K,xe]=o.useState("modules"),L=o.useRef(!1),T=o.useMemo(()=>s.filter(ne=>!w(ne.name)).length,[s,w]);o.useEffect(()=>{L.current||t.length!==0&&(L.current=!0,T<$?xe("folders"):xe("modules"))},[t.length,T]),o.useEffect(()=>{K!=="folders"||je.current||(je.current=!0,ce(!0),se.browseDirectories("",3).then(ne=>{fe(ne)}).catch(()=>{fe([])}).finally(()=>{ce(!1)}))},[K]);const Q=o.useCallback(ne=>{const ve={name:ne.name,packageName:ne.name,packagePath:ne.path,targetDir:ne.path,path:ne.path,type:"directory",language:ne.language||"unknown",discovererId:"folder-scan",discovererName:P("moduleExplorer.discovererFolderScan"),info:{source:"manual-folder-scan",originalPath:ne.path},isVirtual:!0};G==null||G(ve),n(ve),xe("modules")},[n,G,P]),ie=o.useCallback(async(ne,ve)=>{if(!ee.current.has(ne)){ee.current.add(ne),m(ne);try{const He=ve.candidateId&&ve.targetName?{targetName:ve.targetName,candidateId:ve.candidateId}:{candidate:ve.candidate||{}},Pe=await se.getCandidateSimilarityEx(He);M(Ne=>({...Ne,[ne]:Pe.similar||[]}))}catch{M(Pe=>({...Pe,[ne]:[]}))}finally{m(null)}}},[]),ke=o.useCallback(async(ne,ve,He=[])=>{var B,D,U;const Pe=ne.candidateTargetName||"",Ne=ve.replace(/\.md$/i,"");let r="";const k=C==null?void 0:C.find(te=>te.name===Ne||te.name.endsWith("/"+Ne));if(k!=null&&k.content)r=[k.content.pattern,k.content.markdown].filter(Boolean).join(`
113
+
114
+ `)||"";else try{r=(await se.getRecipeContentByName(Ne)).content}catch(te){const de=(B=te.response)==null?void 0:B.status,me=((U=(D=te.response)==null?void 0:D.data)==null?void 0:U.message)||te.message;de===404?re(P("moduleExplorer.recipeNotExist",{name:Ne}),{title:P("moduleExplorer.recipeNotExistTitle"),type:"error"}):re(me,{title:P("moduleExplorer.loadRecipeFailed"),type:"error"});return}const b={[Ne]:r};y({candidate:ne,targetName:Pe,recipeName:Ne,recipeContent:r,similarList:He.slice(0,3),recipeContents:b})},[C]);return o.useEffect(()=>{const ne=u.map((Ne,r)=>Ne.candidateId??`scan-${r}`),ve=ae.current;(ne.length!==ve.length||ne.some((Ne,r)=>Ne!==ve[r]))&&(ee.current.clear(),ae.current=ne);const Pe=setTimeout(()=>{u.forEach((Ne,r)=>{var b,B;const k=Ne.candidateId??Ne.id??`scan-${r}`;Ne.candidateId&&Ne.candidateTargetName?ie(k,{targetName:Ne.candidateTargetName,candidateId:Ne.candidateId}):ie(k,{candidate:{title:Ne.title,summary:Ne.description||"",code:((b=Ne.content)==null?void 0:b.pattern)||"",usageGuide:((B=Ne.content)==null?void 0:B.markdown)||""}})})},800);return()=>clearTimeout(Pe)},[u,ie]),e.jsxs("div",{className:"flex gap-8 h-full",children:[e.jsxs("div",{className:"w-80 bg-white rounded-xl border border-slate-200 flex flex-col overflow-hidden shrink-0",children:[e.jsx("div",{className:"p-3 bg-slate-50 border-b border-slate-200",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-0.5 bg-slate-200/60 rounded-lg p-0.5",children:[e.jsx("button",{onClick:()=>xe("modules"),className:`text-[11px] px-2.5 py-1.5 rounded-md font-bold transition-all ${K==="modules"?"bg-white text-blue-700 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:P("moduleExplorer.modulesTabLabel",{count:T})}),e.jsx("button",{onClick:()=>xe("folders"),className:`text-[11px] px-2.5 py-1.5 rounded-md font-bold transition-all ${K==="folders"?"bg-white text-blue-700 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:P("moduleExplorer.foldersTabLabel")})]}),S&&e.jsx("button",{onClick:S,title:P("moduleExplorer.refreshProject"),className:"p-1.5 rounded-md hover:bg-blue-50 text-slate-500 hover:text-blue-600 border border-transparent hover:border-blue-200 transition-all",children:e.jsx(yt,{size:F.md})})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto p-2 space-y-1",children:K==="modules"?e.jsx(e.Fragment,{children:s.map(ne=>{const ve=w(ne.name),He=a===ne.name,Pe=ne.isVirtual||ne.discovererId==="folder-scan",Ne=ne.language||"",r=ga[Ne]||"bg-slate-100 text-slate-500 border-slate-200",k=ne.packageName&&ne.packageName!==ne.name?ne.packageName:ne.discovererName||"";return e.jsxs("button",{onClick:()=>n(ne),disabled:l,className:`w-full text-left p-3 rounded-lg flex items-center justify-between group transition-all border ${l?"opacity-50 cursor-not-allowed":"hover:bg-slate-50"} ${He?"bg-blue-50 border-blue-200 ring-1 ring-blue-200":"bg-white border-transparent"} ${ve?"opacity-90":""}`,children:[e.jsxs("div",{className:`flex flex-col max-w-[85%] ${ve?"opacity-60":""}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[!ve&&e.jsx("div",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${Pe?"bg-emerald-500":"bg-blue-600"}`}),e.jsx("span",{className:`text-sm truncate ${ve?"font-medium":"font-bold"} ${He?"text-blue-700":""}`,children:ne.name}),Ne&&!ve&&e.jsx("span",{className:`text-[9px] font-bold px-1.5 py-0.5 rounded border shrink-0 ${r}`,children:ba[Ne]||Ne.toUpperCase()}),Pe&&e.jsx("span",{className:"text-[9px] font-bold px-1.5 py-0.5 rounded border shrink-0 bg-emerald-50 text-emerald-600 border-emerald-200",children:"FOLDER"})]}),k&&e.jsx("span",{className:"text-[10px] text-slate-400 truncate pl-3",children:k})]}),ve?e.jsx("span",{className:"text-[9px] font-bold text-slate-300 border border-slate-100 px-1 rounded",children:"SHELL"}):Pe&&z?e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[e.jsx(et,{size:F.sm,className:`${He?"text-blue-500 opacity-100":"text-blue-500 opacity-0 group-hover:opacity-100"} transition-opacity`}),e.jsx("button",{onClick:b=>{b.stopPropagation(),z(ne.path||"")},title:P("moduleExplorer.removeFolder"),className:"p-0.5 rounded text-slate-300 hover:text-red-500 hover:bg-red-50 opacity-0 group-hover:opacity-100 transition-all",children:e.jsx(ot,{size:12})})]}):e.jsx(et,{size:F.sm,className:`shrink-0 ${He?"text-blue-500 opacity-100":"text-blue-500 opacity-0 group-hover:opacity-100"} transition-opacity`})]},`${ne.discovererId||"default"}::${ne.name}`)})}):e.jsxs(e.Fragment,{children:[he?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-slate-400",children:[e.jsx(Fe,{size:F.lg,className:"animate-spin mb-3 opacity-40"}),e.jsx("p",{className:"text-xs",children:P("moduleExplorer.scanningDirs")})]}):ue.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-slate-400",children:[e.jsx(wt,{size:F.xl,className:"mb-3 opacity-20"}),e.jsx("p",{className:"text-xs text-center px-4 leading-relaxed",children:P("moduleExplorer.noDirs")})]}):ue.map(ne=>{const ve=ga[ne.language]||"bg-slate-100 text-slate-500 border-slate-200";return e.jsxs("button",{onClick:()=>Q(ne),disabled:l||!ne.hasSourceFiles,className:`w-full text-left p-2.5 rounded-lg flex items-center gap-2.5 transition-all border border-transparent
115
+ ${ne.hasSourceFiles?l?"opacity-50 cursor-not-allowed":"hover:bg-emerald-50 hover:border-emerald-200 cursor-pointer":"opacity-40 cursor-not-allowed"}
116
+ `,style:{paddingLeft:`${ne.depth*14+10}px`},children:[e.jsx(wt,{size:F.sm,className:ne.hasSourceFiles?"text-emerald-500 shrink-0":"text-slate-300 shrink-0"}),e.jsx("span",{className:"text-sm font-medium flex-1 truncate",children:ne.name}),ne.hasSourceFiles&&ne.language!=="unknown"&&e.jsx("span",{className:`text-[9px] font-bold px-1.5 py-0.5 rounded border shrink-0 ${ve}`,children:ba[ne.language]||ne.language.toUpperCase()}),ne.hasSourceFiles&&e.jsx("span",{className:"text-[10px] text-slate-400 shrink-0",children:P("moduleExplorer.sourceFileCount",{count:ne.sourceFileCount})}),e.jsx(rt,{size:12,className:"text-slate-300 shrink-0"})]},ne.path)}),e.jsx("div",{className:"px-3 py-2 text-[10px] text-slate-400 text-center",children:P("moduleExplorer.selectFolderHint")})]})})]}),e.jsxs("div",{className:"flex-1 bg-white rounded-xl border border-slate-200 flex flex-col overflow-hidden relative",children:[e.jsx("div",{className:"p-4 bg-slate-50 border-b border-slate-200 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(lt,{size:F.md,className:"text-indigo-500"}),e.jsx("span",{children:P("moduleExplorer.fullProjectResults")}),u.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(et,{size:F.md,className:"text-blue-500"}),e.jsx("span",{children:P("moduleExplorer.moduleLabel",{name:a})}),u.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(Et,{size:F.md,className:"text-slate-400"}),e.jsx("span",{children:P("moduleExplorer.reviewResults")})]}),u.length>0&&e.jsxs("span",{className:"text-slate-400 font-normal text-xs ml-1",children:["(",P("moduleExplorer.resultsCount",{count:u.length}),(Ue=u[0])!=null&&Ue.trigger?P("moduleExplorer.candidateSuffix"):"",")"]})]})}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-8 relative",children:[l&&e.jsxs("div",{className:"absolute inset-0 bg-white/90 backdrop-blur-[2px] z-10 flex flex-col items-center justify-center text-blue-600 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(ns,{size:F.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__"?P("moduleExplorer.fullProjectScanning"):P("moduleExplorer.moduleScanLabel",{name:a||"..."})}),e.jsx("p",{className:"text-sm text-slate-500 mb-4",children:d.status}),e.jsx("div",{className:"w-full max-w-md bg-slate-100 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(d.total?d.current/d.total*100:0,98)}%`}})}),e.jsx("p",{className:"text-xs text-slate-400 mt-3",children:d.total?`${Math.round(d.current/d.total*100)}%`:"0%"})]}),!l&&u.length===0&&e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-slate-400 text-center",children:[e.jsx(ws,{size:F.xxxl,className:"mb-4 opacity-20"}),e.jsx("p",{className:"font-medium text-slate-600",children:P("moduleExplorer.knowledgeExtract")}),e.jsx("p",{className:"text-xs mt-2 max-w-sm leading-relaxed",children:P("moduleExplorer.knowledgeExtractHint")})]}),!l&&a==="__project__"&&(p==null?void 0: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(ut,{size:F.md,className:p.summary.totalViolations>0?"text-amber-600":"text-emerald-600"}),e.jsx("span",{className:"text-sm font-bold text-slate-700",children:P("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 gap-6 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-slate-500",children:P("moduleExplorer.auditedFiles")}),e.jsx("span",{className:"font-bold text-slate-700",children:p.summary.totalFiles})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-slate-500",children:P("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(Rt,{size:F.sm,className:"text-red-500"}),e.jsx("span",{className:"font-bold text-red-700",children:P("moduleExplorer.errorsCount",{count:p.summary.errors})})]}),p.summary.warnings>0&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Rt,{size:F.sm,className:"text-amber-500"}),e.jsx("span",{className:"font-bold text-amber-700",children:P("moduleExplorer.warningsCount",{count:p.summary.warnings})})]})]})]}),u.map((ne,ve)=>e.jsx(un,{res:ne,index:ve,editingCodeIndex:Z,setEditingCodeIndex:X,expandedEditIndex:H,setExpandedEditIndex:q,similarityMap:R,handleUpdateScanResult:f,handleSaveExtracted:h,handlePromoteToCandidate:x,openCompare:ke,isSavingRecipe:E},ve))]})]}),N&&e.jsx(xn,{data:N,onClose:()=>y(null),onDataChange:y,recipes:C,handleSaveExtracted:h,handleDeleteCandidate:c,onEditRecipe:j,isSavingRecipe:E}),e.jsx(rn,{isOpen:W,onClose:()=>O(!1),targetName:ye,currentFile:be,language:((Ie=s.find(ne=>ne.name===a))==null?void 0:Ie.language)||"unknown",onSelectRecipe:ne=>{}})]})},hn=72,gn=52,Ns=24,es=40,Xa=36,Tt=140,Zt=40,ts=8;function bn(t,s){const a=new Set(t.map(p=>p.id)),l=new Map;for(const p of s)!a.has(p.from)||!a.has(p.to)||(l.has(p.from)||l.set(p.from,[]),l.get(p.from).push(p.to));const d=new Map,i=new Set;function u(p){if(d.has(p))return d.get(p);if(i.has(p))return 0;i.add(p);const n=l.get(p);if(!n||n.length===0)return d.set(p,0),i.delete(p),0;const g=1+Math.max(...n.map(u));return d.set(p,g),i.delete(p),g}return t.forEach(p=>u(p.id)),d}function fn(t){return Math.ceil(t/ts)}function yn(t,s){const a=bn(t,s),l=new Map;for(const h of t){const x=a.get(h.id)??0;l.has(x)||l.set(x,[]),l.get(x).push(h.id)}const d=[...new Set(a.values())].sort((h,x)=>h-x),i=[...d].reverse(),u=new Map,p=new Map,n=Math.min(ts,Math.max(...d.map(h=>(l.get(h)??[]).length),1)),g=(n-1)*Ns+n*Tt;let f=es;return i.forEach(h=>{const x=l.get(h)??[],c=fn(x.length),j=f;for(let C=0;C<c;C++){const E=x.slice(C*ts,(C+1)*ts),S=(E.length-1)*Ns+E.length*Tt,G=(g-S)/2;E.forEach((z,P)=>{const Z=es+Xa+G+P*(Tt+Ns)+Tt/2,X=f+Zt/2;u.set(z,{x:Z,y:X})}),f+=C<c-1?gn:hn}const w=f-j;p.set(h,{y:j,h:w})}),{positions:u,tiers:a,tierOrder:d,tierYRanges:p}}const jn=()=>{const{t}=_e(),{isDark:s}=St(),[a,l]=o.useState(null),[d,i]=o.useState(!0),[u,p]=o.useState(null),[n,g]=o.useState(null),[f,h]=o.useState("package"),[x,c]=o.useState("all"),j=async()=>{var v,ee;i(!0),p(null);try{const ae=await se.getDepGraph(f);l({nodes:Array.isArray(ae==null?void 0:ae.nodes)?ae.nodes:[],edges:Array.isArray(ae==null?void 0:ae.edges)?ae.edges:[],projectRoot:(ae==null?void 0:ae.projectRoot)??null,generatedAt:ae==null?void 0:ae.generatedAt})}catch(ae){p(((ee=(v=ae.response)==null?void 0:v.data)==null?void 0:ee.error)||ae.message||"Failed to load dependency graph")}finally{i(!1)}};o.useEffect(()=>{j()},[f]);const w=Array.isArray(a==null?void 0:a.nodes)?a.nodes:[],C=Array.isArray(a==null?void 0:a.edges)?a.edges:[],E=w.some(v=>v.type==="internal"||v.type==="external"),S=o.useMemo(()=>!E||x==="all"?w:x==="internal"?w.filter(v=>v.type!=="external"):w.filter(v=>v.type!=="internal"),[w,x,E]),G=o.useMemo(()=>new Set(S.map(v=>v.id)),[S]),z=o.useMemo(()=>C.filter(v=>G.has(v.from)||G.has(v.to)),[C,G]),{positions:P,tiers:Z,tierOrder:X,tierYRanges:H}=o.useMemo(()=>yn(S,z),[S,z]),q=o.useMemo(()=>{const v=new Map;return S.forEach(ee=>{const ae=Z.get(ee.id)??0;v.has(ae)||v.set(ae,[]),v.get(ae).push(ee.id)}),v},[S,Z]),R=o.useMemo(()=>[...X].reverse(),[X]),{dependsOn:M,dependedBy:_}=o.useMemo(()=>{const v=new Map,ee=new Map;return z.forEach(ae=>{v.has(ae.from)||v.set(ae.from,[]),v.get(ae.from).push(ae.to),ee.has(ae.to)||ee.set(ae.to,[]),ee.get(ae.to).push(ae.from)}),{dependsOn:v,dependedBy:ee}},[z]),m=Math.min(ts,Math.max(...X.map(v=>(q.get(v)??[]).length),1)),y=(m-1)*Ns+m*Tt+Xa*2,W=Math.max(600,es*2+y),O=Math.max(...[...P.values()].map(v=>v.y),0),be=Math.max(420,O+Zt/2+es+20),we=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)"}],ye=v=>we[Math.min(v,we.length-1)]??we[0];return d?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"})}):u?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:u}),e.jsx("button",{type:"button",onClick:j,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||w.length===0?e.jsxs("div",{className:"rounded-xl border border-slate-200 bg-slate-50 p-8 text-slate-600 shadow-sm",children:[e.jsx("p",{className:"font-medium text-slate-700",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:"mb-4 flex justify-between items-center shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-50 border border-blue-100 flex items-center justify-center",children:e.jsx(lt,{className:"text-blue-600",size:20})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-slate-800",children:t("depGraph.title")}),e.jsxs("p",{className:"text-xs text-slate-400 mt-0.5",children:[t("depGraph.visualization"),a.projectRoot&&e.jsxs("span",{className:"ml-1",children:["· ",a.projectRoot]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[E&&e.jsx("div",{className:"flex items-center border border-slate-200 rounded-lg overflow-hidden text-xs",children:["all","internal","external"].map(v=>e.jsx("button",{type:"button",onClick:()=>c(v),className:`px-3 py-1.5 font-medium transition-colors ${x===v?"bg-blue-600 text-white":"bg-white text-slate-600 hover:bg-slate-50"}`,children:t(v==="all"?"depGraph.filterAll":v==="internal"?"depGraph.filterInternal":"depGraph.filterExternal")},v))}),e.jsxs("button",{type:"button",onClick:()=>{j()},className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-all text-slate-600 bg-slate-50 border border-slate-200 hover:bg-slate-100",children:[e.jsx(yt,{size:14})," ",t("depGraph.refresh")]}),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-slate-50 border border-slate-100",children:[e.jsx(lt,{size:14,className:"text-slate-400"}),e.jsxs("span",{className:"text-slate-500",children:[t("depGraph.packages")," ",e.jsx("strong",{className:"text-slate-700",children:S.length})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-emerald-50 border border-emerald-100",children:[e.jsx("span",{className:"text-emerald-500",children:t("depGraph.dependencies")}),e.jsx("strong",{className:"text-emerald-700",children:z.length})]}),a.generatedAt&&e.jsx("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-blue-50 border border-blue-100",children:e.jsx("span",{className:"text-blue-500",children:new Date(a.generatedAt).toLocaleString("zh-CN")})})]})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto pr-1 space-y-6",children:[E&&e.jsxs("div",{className:"flex items-center gap-4 text-xs text-slate-500 px-1",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-slate-300 bg-white"})," ",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:`rounded-xl border overflow-auto shadow-sm min-h-[480px] flex items-center justify-center relative ${s?"border-slate-700 bg-[#13151c]":"border-slate-200 bg-slate-50/50"}`,children:[e.jsxs("svg",{width:"100%",height:be,viewBox:`0 0 ${W} ${be}`,className:"block min-h-[480px] w-full",style:{maxHeight:640},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"})})}),R.map((v,ee)=>{const ae=ye(ee),ue=H.get(v);return ue?e.jsx("rect",{x:es,y:ue.y-Zt/2-4,width:y,height:ue.h+8,rx:8,fill:ae.bg,stroke:ae.border,strokeWidth:s?1.5:1,opacity:s?1:.6},v):null}),S.map(v=>{const ee=P.get(v.id);if(!ee)return null;const ae=Z.get(v.id)??0,ue=ye(R.indexOf(ae)),fe=v.label.length>14?v.label.slice(0,13)+"…":v.label,he=n===v.id,ce=n?(M.get(n)??[]).includes(v.id):!1,je=n?(_.get(n)??[]).includes(v.id):!1,$=n&&!he&&!ce&&!je,K=v.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"}:v.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:ue.border,text:ue.text,badge:""}:{fill:"white",stroke:ue.border,text:ue.text,badge:""},xe=n?he?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}:ce?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}:je?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:K.fill,stroke:K.stroke,text:K.text,strokeWidth:2,opacity:v.indirect?.55:1};return e.jsxs("g",{style:{cursor:"pointer",opacity:xe.opacity},onClick:()=>g(he?null:v.id),children:[e.jsx("rect",{x:ee.x-Tt/2,y:ee.y-Zt/2,width:Tt,height:Zt,rx:10,ry:10,fill:xe.fill,stroke:xe.stroke,strokeWidth:xe.strokeWidth,filter:$?void 0:"url(#nodeShadow)",strokeDasharray:v.type==="external"?"4 2":void 0}),e.jsx("text",{x:ee.x,y:ee.y+(K.badge?-2:0),textAnchor:"middle",dominantBaseline:"middle",fontSize:"12",fontWeight:"600",fill:xe.text,pointerEvents:"none",children:fe}),K.badge&&e.jsx("text",{x:ee.x,y:ee.y+12,textAnchor:"middle",dominantBaseline:"middle",fontSize:"8",fontWeight:"500",fill:K.text,opacity:.6,pointerEvents:"none",children:K.badge})]},v.id)})]}),n&&e.jsxs("div",{className:"absolute top-4 right-4 w-72 rounded-xl border border-slate-200 bg-white 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-slate-100",children:[e.jsx("span",{className:"font-bold text-slate-800",children:n}),e.jsx("button",{type:"button",onClick:()=>g(null),className:"text-slate-400 hover:text-slate-600 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-slate-600 mb-1",children:t("depGraph.dependencies")}),e.jsx("ul",{className:"text-slate-700 space-y-0.5",children:(M.get(n)??[]).length===0?e.jsx("li",{className:"text-slate-400",children:t("depGraph.none")}):(M.get(n)??[]).map(v=>e.jsxs("li",{children:["→ ",v]},v))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-slate-600 mb-1",children:t("depGraph.dependents")}),e.jsx("ul",{className:"text-slate-700 space-y-0.5",children:(_.get(n)??[]).length===0?e.jsx("li",{className:"text-slate-400",children:t("depGraph.none")}):(_.get(n)??[]).map(v=>e.jsxs("li",{children:["← ",v]},v))})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"rounded-xl border border-slate-200 bg-white p-5 shadow-sm",children:[e.jsxs("h3",{className:"text-sm font-bold text-slate-800 mb-3 pb-2 border-b border-slate-100",children:[t("depGraph.packageList")," (",S.length,")"]}),e.jsx("ul",{className:"text-sm space-y-3 max-h-[280px] overflow-y-auto pr-1",children:S.map(v=>e.jsxs("li",{className:"pb-3 border-b border-slate-100 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-slate-800",children:v.label||v.id}),v.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")}),v.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")}),v.indirect&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-slate-50 text-slate-500 border border-slate-200 font-medium",children:t("depGraph.labelIndirect")}),v.packageDir&&e.jsxs("span",{className:"text-slate-500 text-xs",children:["· ",v.packageDir]})]}),v.fullPath&&e.jsx("div",{className:"mt-1 text-slate-400 text-xs truncate",children:v.fullPath}),v.targets&&v.targets.length>0&&e.jsxs("div",{className:"mt-1.5 text-slate-500 text-xs pl-0",children:["Targets: ",e.jsx("span",{className:"text-slate-600",children:v.targets.join(", ")})]})]},v.id))})]}),e.jsxs("div",{className:"rounded-xl border border-slate-200 bg-white p-5 shadow-sm",children:[e.jsxs("h3",{className:"text-sm font-bold text-slate-800 mb-3 pb-2 border-b border-slate-100",children:[t("depGraph.depRelations")," (",z.length,")"]}),e.jsx("p",{className:"text-xs text-slate-500 mb-2",children:t("depGraph.depRelationsDesc")}),e.jsx("ul",{className:"text-sm space-y-2 max-h-[280px] overflow-y-auto pr-1",children:z.map((v,ee)=>e.jsxs("li",{className:"flex items-center gap-2 text-slate-700",children:[e.jsx("span",{className:"font-semibold text-slate-800",children:v.from}),e.jsx("span",{className:"text-slate-400 shrink-0",children:"→"}),e.jsx("span",{className:"font-semibold text-slate-800",children:v.to})]},`${v.from}-${v.to}-${ee}`))})]}),f==="target"&&e.jsxs("p",{className:"text-xs text-slate-500 mt-2",children:[t("depGraph.targetHint"),e.jsx("span",{className:"font-mono",children:"Package::Target"})]})]})]})]})},vn=({onRefresh:t})=>{const{t:s}=_e(),[a,l]=o.useState({}),[d,i]=o.useState([]),[u,p]=o.useState([]),[n,g]=o.useState(null),[f,h]=o.useState(!0),[x,c]=o.useState(!1),[j,w]=o.useState(!1),[C,E]=o.useState(""),[S,G]=o.useState(!1),[z,P]=o.useState({ruleId:"",message:"",severity:"warning",pattern:"",languages:[],note:"",dimension:""}),[Z,X]=o.useState(!1),[H,q]=o.useState(""),R=async()=>{try{const[$,K]=await Promise.all([se.getGuardRules(),se.getGuardViolations()]);l(($==null?void 0:$.rules)||{}),p(($==null?void 0:$.projectLanguages)||[]),i((K==null?void 0:K.runs)||[])}catch{l({}),i([])}finally{h(!1)}};o.useEffect(()=>{R()},[]);const M=async()=>{if(window.confirm(s("guard.clearConfirm")))try{await se.clearViolations(),R(),t==null||t()}catch($){re(($==null?void 0:$.message)||s("common.operationFailed"),{title:s("common.operationFailed"),type:"error"})}},_=$=>{P(K=>({...K,languages:K.languages.includes($)?K.languages.filter(xe=>xe!==$):[...K.languages,$]}))},m=async()=>{var $,K;if(!C.trim()){q(s("guard.aiGenPlaceholder"));return}q(""),G(!0);try{const L=await se.generateGuardRule({description:C.trim()}),T=L.dimension;P({ruleId:L.ruleId||"",message:L.message||"",severity:L.severity==="error"?"error":"warning",pattern:L.pattern||"",languages:Array.isArray(L.languages)&&L.languages.length>0?L.languages:[],note:L.note!=null?String(L.note):"",dimension:T==="file"||T==="target"||T==="project"?T:""}),w(!0)}catch(xe){q(((K=($=xe==null?void 0:xe.response)==null?void 0:$.data)==null?void 0:K.error)||(xe==null?void 0:xe.message)||s("guard.aiGenFailed"))}finally{G(!1)}},N=async $=>{var K,xe;if($.preventDefault(),q(""),!z.ruleId.trim()||!z.message.trim()||!z.pattern.trim()||z.languages.length===0){q(s("guard.addRuleValidation"));return}X(!0);try{await se.saveGuardRule({ruleId:z.ruleId.trim(),message:z.message.trim(),severity:z.severity,pattern:z.pattern.trim(),languages:z.languages,note:z.note.trim()||void 0,...z.dimension?{dimension:z.dimension}:{}}),P({ruleId:"",message:"",severity:"warning",pattern:"",languages:[],note:"",dimension:""}),E(""),w(!1),R(),t==null||t()}catch(L){q(((xe=(K=L==null?void 0:L.response)==null?void 0:K.data)==null?void 0:xe.error)||(L==null?void 0:L.message)||s("common.saveFailed"))}finally{X(!1)}},W=o.useMemo(()=>{const $=Object.entries(a);return u.length===0?$:$.filter(([,K])=>!K.languages||K.languages.length===0?!0:K.languages.some(xe=>u.includes(xe)))},[a,u]),O=d.reduce(($,K)=>$+K.violations.length,0),[be,we]=o.useState("all"),[ye,v]=o.useState("all"),ee=o.useMemo(()=>{const $=new Set;for(const[,xe]of W)(xe.languages||[]).forEach(L=>$.add(L));const K=Bt.filter(xe=>$.has(xe.id)).map(xe=>xe.id);for(const xe of $)K.includes(xe)||K.push(xe);return K},[W]),ae=$=>{var K;return((K=Bt.find(xe=>xe.id===$))==null?void 0:K.label)||$},ue=o.useMemo(()=>{const $={error:0,warning:0,info:0};for(const[,K]of W){const xe=K.severity;$[xe]!==void 0&&$[xe]++}return $},[W]),fe=$=>{const K={safety:s("guard.categorySafety"),correctness:s("guard.categoryCorrectness"),performance:s("guard.categoryPerformance"),style:s("guard.categoryStyle")};return $?K[$]||$:"—"},he=($,K)=>{const xe=`guardRuleMessages.${$}`,L=s(xe);return L!==xe?L:K},ce=($,K)=>{if(!K)return K;const xe=`guardRuleFixSuggestions.${$}`,L=s(xe);return L!==xe?L:K},je=o.useMemo(()=>W.filter(([,$])=>!(be!=="all"&&!($.languages||[]).includes(be)||ye!=="all"&&$.severity!==ye)),[W,be,ye]);return f?e.jsx("div",{className:"p-6 text-slate-500",children:s("common.loading")}):e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"mb-4 flex justify-between items-center shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-50 border border-blue-100 flex items-center justify-center",children:e.jsx(ut,{className:"text-blue-600",size:20})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-slate-800",children:s("guard.title")}),e.jsxs("p",{className:"text-xs text-slate-400 mt-0.5",children:[s("guard.summary"),u.length>0&&e.jsxs("span",{className:"ml-1.5",children:["· ",s("guard.currentProject"),":",u.map($=>ae($)).join(" / ")]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("a",{href:ar,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-slate-600 bg-slate-50 border border-slate-200 hover:bg-slate-100",children:[e.jsx(Tl,{size:14})," ",s("guard.reportIssue")]}),e.jsxs("button",{type:"button",onClick:()=>c(!x),className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-all text-blue-700 bg-blue-50 border border-blue-200 hover:bg-blue-100",children:[x?e.jsx(Gt,{size:14}):e.jsx(rt,{size:14}),s("guard.aiGenRule")]}),d.length>0&&e.jsxs("button",{type:"button",onClick:M,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(ot,{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-slate-50 border border-slate-100",children:[e.jsx(ut,{size:14,className:"text-slate-400"}),e.jsxs("span",{className:"text-slate-500",children:[s("guard.tableHeaders.rule")," ",e.jsx("strong",{className:"text-slate-700",children:W.length})]})]}),O>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(Rt,{size:14,className:"text-amber-400"}),e.jsx("span",{className:"text-amber-600",children:s("guard.totalViolations",{count:O})})]})]})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto pr-1",children:[x&&e.jsxs("section",{className:"mb-6",children:[e.jsxs("div",{className:"p-4 bg-slate-50 border border-slate-200 rounded-xl space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"semantic-input",className:"block text-xs font-medium text-slate-600 mb-1",children:s("guard.aiGenRuleDesc")}),e.jsx("textarea",{id:"semantic-input",name:"semanticInput",value:C,onChange:$=>{E($.target.value),q("")},className:"w-full px-3 py-2 border border-slate-200 rounded-lg text-sm resize-y min-h-[80px]",placeholder:s("guard.aiGenPlaceholder"),rows:3}),e.jsx("button",{type:"button",onClick:m,disabled:S||!C.trim(),className:"mt-2 px-4 py-2 bg-slate-600 text-white text-sm rounded-lg hover:bg-slate-700 disabled:opacity-50",children:s(S?"guard.aiGenerating":"guard.aiGenRule")}),H&&e.jsx("p",{className:"mt-2 text-sm text-red-600",children:H})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{type:"button",onClick:()=>w(!j),className:"text-sm font-medium text-blue-600 hover:text-blue-700",children:s(j?"common.collapse":"common.expand")}),z.ruleId&&e.jsxs("span",{className:"text-xs text-slate-500",children:[s("guard.generatedRuleId"),":",z.ruleId]})]})]}),j&&e.jsxs("form",{onSubmit:N,className:"mt-3 p-4 bg-white border border-slate-200 rounded-xl space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"rule-id",className:"block text-xs font-medium text-slate-600 mb-1",children:s("guard.ruleId")}),e.jsx("input",{id:"rule-id",name:"ruleId",type:"text",value:z.ruleId,onChange:$=>P(K=>({...K,ruleId:$.target.value})),className:"w-full px-3 py-2 border border-slate-200 rounded-lg text-sm",placeholder:"my-rule-id"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"rule-severity",className:"block text-xs font-medium text-slate-600 mb-1",children:s("guard.severity")}),e.jsxs("select",{id:"rule-severity",name:"severity",value:z.severity,onChange:$=>P(K=>({...K,severity:$.target.value})),className:"w-full px-3 py-2 border border-slate-200 rounded-lg text-sm",children:[e.jsx("option",{value:"warning",children:"warning"}),e.jsx("option",{value:"error",children:"error"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"rule-message",className:"block text-xs font-medium text-slate-600 mb-1",children:s("guard.message")}),e.jsx("input",{id:"rule-message",name:"message",type:"text",value:z.message,onChange:$=>P(K=>({...K,message:$.target.value})),className:"w-full px-3 py-2 border border-slate-200 rounded-lg text-sm",placeholder:s("guard.aiGenPlaceholder")})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"rule-pattern",className:"block text-xs font-medium text-slate-600 mb-1",children:s("guard.patternLabel")}),e.jsx("input",{id:"rule-pattern",name:"pattern",type:"text",value:z.pattern,onChange:$=>P(K=>({...K,pattern:$.target.value})),className:"w-full px-3 py-2 border border-slate-200 rounded-lg text-sm font-mono",placeholder:"dispatch_sync\\\\s*\\\\([^)]*main"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-medium text-slate-600 mb-1",children:s("guard.languagesLabel")}),e.jsx("div",{className:"flex gap-3 flex-wrap",children:(u.length>0?Bt.filter($=>u.includes($.id)):Bt.slice(0,8)).map($=>e.jsxs("label",{htmlFor:`lang-${$.id}`,className:"flex items-center gap-1.5 text-sm",children:[e.jsx("input",{id:`lang-${$.id}`,name:"languages",type:"checkbox",checked:z.languages.includes($.id),onChange:()=>_($.id)}),$.label]},$.id))})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"rule-dimension",className:"block text-xs font-medium text-slate-600 mb-1",children:s("guard.dimensionLabel")}),e.jsxs("select",{id:"rule-dimension",name:"dimension",value:z.dimension,onChange:$=>P(K=>({...K,dimension:$.target.value})),className:"w-full px-3 py-2 border border-slate-200 rounded-lg text-sm",children:[e.jsx("option",{value:"",children:s("guard.dimNoLimit")}),e.jsx("option",{value:"file",children:s("guard.dimFile")}),e.jsx("option",{value:"target",children:s("guard.dimTarget")}),e.jsx("option",{value:"project",children:s("guard.dimProject")})]})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"rule-note",className:"block text-xs font-medium text-slate-600 mb-1",children:s("guard.noteLabel")}),e.jsx("input",{id:"rule-note",name:"note",type:"text",value:z.note,onChange:$=>P(K=>({...K,note:$.target.value})),className:"w-full px-3 py-2 border border-slate-200 rounded-lg text-sm",placeholder:s("guard.notePlaceholder")})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{type:"submit",disabled:Z,className:"px-4 py-2 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700 disabled:opacity-50",children:s(Z?"common.saving":"common.confirm")}),e.jsx("button",{type:"button",onClick:()=>w(!1),className:"px-4 py-2 text-slate-600 text-sm rounded-lg hover:bg-slate-100",children:s("common.collapse")})]})]})]}),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-slate-700 flex items-center gap-1.5",children:[e.jsx(za,{size:14,className:"text-slate-400"}),s("guard.tableHeaders.rule"),e.jsxs("span",{className:"text-slate-400 font-normal",children:["(",je.length,"/",W.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:()=>v("all"),className:`px-2 py-1 rounded-md border transition-all ${ye==="all"?"bg-slate-700 text-white border-slate-700":"bg-white text-slate-600 border-slate-200 hover:bg-slate-50"}`,children:s("common.all")}),e.jsxs("button",{onClick:()=>v("error"),className:`px-2 py-1 rounded-md border transition-all flex items-center gap-1 ${ye==="error"?"bg-red-600 text-white border-red-600":"bg-white text-red-600 border-red-200 hover:bg-red-50"}`,children:[e.jsx(Ot,{size:12})," error ",e.jsxs("span",{className:"opacity-70",children:["(",ue.error,")"]})]}),e.jsxs("button",{onClick:()=>v("warning"),className:`px-2 py-1 rounded-md border transition-all flex items-center gap-1 ${ye==="warning"?"bg-amber-500 text-white border-amber-500":"bg-white text-amber-600 border-amber-200 hover:bg-amber-50"}`,children:[e.jsx(Rt,{size:12})," warning ",e.jsxs("span",{className:"opacity-70",children:["(",ue.warning,")"]})]}),e.jsxs("button",{onClick:()=>v("info"),className:`px-2 py-1 rounded-md border transition-all flex items-center gap-1 ${ye==="info"?"bg-blue-500 text-white border-blue-500":"bg-white text-blue-600 border-blue-200 hover:bg-blue-50"}`,children:[e.jsx(_a,{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:()=>we("all"),className:`px-2.5 py-1 rounded-full text-xs font-medium border transition-all ${be==="all"?"bg-slate-700 text-white border-slate-700":"bg-white text-slate-600 border-slate-200 hover:bg-slate-50"}`,children:s("guard.allLanguages")}),ee.map($=>{const K=W.filter(([,xe])=>(xe.languages||[]).includes($)).length;return e.jsxs("button",{onClick:()=>we(be===$?"all":$),className:`px-2.5 py-1 rounded-full text-xs font-medium border transition-all ${be===$?"bg-indigo-600 text-white border-indigo-600":"bg-white text-slate-600 border-slate-200 hover:bg-slate-50"}`,children:[ae($)," ",e.jsxs("span",{className:"opacity-60",children:["(",K,")"]})]},$)})]}),e.jsx("div",{className:"bg-white border border-slate-200 rounded-xl overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 border-b border-slate-200",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left py-2 px-4 font-medium text-slate-600",children:s("guard.ruleId")}),e.jsx("th",{className:"text-left py-2 px-4 font-medium text-slate-600 w-20",children:s("guard.severity")}),e.jsx("th",{className:"text-left py-2 px-4 font-medium text-slate-600",children:s("guard.message")}),e.jsx("th",{className:"text-left py-2 px-4 font-medium text-slate-600 w-28",children:s("guard.languagesLabel")}),e.jsx("th",{className:"text-left py-2 px-4 font-medium text-slate-600 w-20",children:s("guard.category")})]})}),e.jsx("tbody",{children:je.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:5,className:"py-4 px-4 text-slate-500 text-center",children:W.length===0?s("common.noData"):s("guard.noMatchingRules")})}):je.map(([$,K])=>e.jsxs("tr",{className:"border-b border-slate-100 last:border-0 hover:bg-slate-50/50",children:[e.jsx("td",{className:"py-2 px-4 font-mono text-xs text-slate-700",children:$}),e.jsx("td",{className:"py-2 px-4",children:e.jsx("span",{className:`text-xs font-medium px-1.5 py-0.5 rounded ${K.severity==="error"?"bg-red-100 text-red-700":K.severity==="info"?"bg-blue-100 text-blue-700":"bg-amber-100 text-amber-700"}`,children:K.severity})}),e.jsxs("td",{className:"py-2 px-4 text-slate-700",children:[he($,K.message),K.fixSuggestion&&e.jsx("span",{className:"ml-1.5 text-xs text-emerald-600",title:ce($,K.fixSuggestion),children:"💡"})]}),e.jsx("td",{className:"py-2 px-4",children:e.jsx("div",{className:"flex flex-wrap gap-1",children:(K.languages||[]).map(xe=>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:ae(xe)},xe))})}),e.jsx("td",{className:"py-2 px-4 text-xs text-slate-500",children:fe(K.category)})]},$))})]})})]}),e.jsxs("section",{children:[e.jsx("h3",{className:"text-sm font-semibold text-slate-700 mb-3",children:s("guard.violationRecords",{runs:d.length,count:O})}),d.length===0?e.jsx("div",{className:"bg-slate-50 border border-slate-200 rounded-xl py-12 text-center text-slate-500",children:s("guard.noViolations")}):e.jsx("div",{className:"space-y-2",children:d.map($=>{const K=n===$.id,xe=$.violations.length>0;return e.jsxs("div",{className:"bg-white border border-slate-200 rounded-xl overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>g(K?null:$.id),className:"w-full flex items-center gap-2 py-3 px-4 text-left hover:bg-slate-50 transition-colors",children:[K?e.jsx(Gt,{size:F.md}):e.jsx(rt,{size:F.md}),e.jsx("span",{className:"font-mono text-sm text-slate-700",children:$.filePath}),e.jsx("span",{className:"text-xs text-slate-400",children:new Date($.triggeredAt).toLocaleString()}),xe?e.jsxs("span",{className:"ml-auto flex items-center gap-1 text-amber-600 text-xs font-medium",children:[e.jsx(Rt,{size:F.sm})," ",s("guard.totalViolations",{count:$.violations.length})]}):e.jsx("span",{className:"ml-auto text-slate-400 text-xs",children:s("guard.noViolations")})]}),K&&e.jsx("div",{className:"border-t border-slate-100 bg-slate-50/50 dark:bg-[#283040] p-4",children:$.violations.length===0?e.jsx("p",{className:"text-sm text-slate-500",children:s("guard.noViolations")}):e.jsx("ul",{className:"space-y-2",children:$.violations.map((L,T)=>{var ie;const Q=a[L.ruleId];return e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[L.severity==="error"?e.jsx(Ot,{size:F.md,className:"text-red-500 shrink-0 mt-0.5"}):e.jsx(Rt,{size:F.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-slate-500",children:["[",L.ruleId,"] ",L.filePath?`${L.filePath}:${L.line}`:`L${L.line}`]}),L.dimension&&e.jsx("span",{className:"ml-1.5 text-xs px-1.5 py-0.5 rounded bg-slate-200 text-slate-600",children:L.dimension==="file"?s("guard.dimFile"):L.dimension==="target"?s("guard.dimTarget"):s("guard.dimProject")}),e.jsx("span",{className:"text-slate-700 ml-2",children:he(L.ruleId,L.message)})]}),L.snippet&&e.jsx("pre",{className:"text-xs text-slate-600 bg-[#f1f5f9] dark:bg-[#0f1219] dark:text-slate-400 dark:border dark:border-slate-700 p-2 rounded overflow-x-auto",children:L.snippet}),Q&&(Q.rationale||((ie=Q.fixSuggestions)==null?void 0:ie.length)||Q.sourceRecipe||Q.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:[Q.rationale&&e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx(tt,{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-slate-600",children:Q.rationale})]})]}),Q.fixSuggestions&&Q.fixSuggestions.length>0&&e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx($a,{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-slate-600",children:Q.fixSuggestions.map((ke,Ue)=>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:ke}),e.jsx("button",{className:"ml-1 text-blue-500 hover:text-blue-700",title:s("guard.copyFixSuggestion"),onClick:()=>navigator.clipboard.writeText(ke),children:"⎘"})]},Ue))})]})]}),Q.sourceRecipe&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Hs,{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:Q.sourceRecipe})]}),!Q.rationale&&Q.note&&e.jsxs("div",{className:"text-slate-500 italic",children:[s("guard.noteLabel"),":",Q.note]})]})]})]},T)})})})]},$.id)})})]})]})]})},fa=()=>Math.random().toString(36).substring(2,10),Nn=({d:t})=>{const{t:s}=_e();return e.jsxs("div",{className:"border border-slate-200 rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-2.5 py-1 bg-slate-50 border-b border-slate-200 flex items-center gap-1.5",children:[e.jsx(Ta,{size:10,className:"text-emerald-500"}),e.jsx("span",{className:"text-[10px] font-bold text-slate-600",children:t.label})]}),e.jsxs("div",{className:"p-2.5 bg-red-50/30 border-b border-slate-200",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-slate-600 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-slate-300",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-slate-700 whitespace-pre-wrap break-words max-h-48 overflow-auto font-mono leading-relaxed scrollbar-light",children:t.after})]})]})};function wn(t,s){const a=new Date(t),d=new Date().getTime()-a.getTime(),i=Math.floor(d/6e4);if(i<1)return s("aiChat.timeJustNow");if(i<60)return s("aiChat.timeMinutesAgo",{n:i});const u=Math.floor(i/60);if(u<24)return s("aiChat.timeHoursAgo",{n:u});const p=Math.floor(u/24);return p<7?s("aiChat.timeDaysAgo",{n:p}):a.toLocaleDateString("zh-CN",{month:"short",day:"numeric"})}const kn=()=>{const{t,lang:s}=_e(),{close:a,isOpen:l}=ds(),[d,i]=o.useState([]),[u,p]=o.useState(!1),n=o.useRef([]),g=o.useRef(null),f=Ua(),{topics:h,activeTopicId:x,activeTopic:c,createTopic:j,deleteTopic:w,saveTopic:C,switchTopic:E,setActiveTopicId:S}=f,G=o.useRef(null),z=o.useRef(null),[P,Z]=o.useState(""),[X,H]=o.useState(!1),q=o.useRef(!1);o.useEffect(()=>{l&&a()},[]),o.useEffect(()=>{var y;(y=G.current)==null||y.scrollIntoView({behavior:"smooth"})},[d,u]),o.useEffect(()=>{setTimeout(()=>{var y;return(y=z.current)==null?void 0:y.focus()},200)},[]),o.useEffect(()=>{q.current||x&&d.length>0&&C(x,d)},[d,x,C]);const R=o.useCallback(()=>{q.current=!0,j(),i([]),n.current=[],setTimeout(()=>{q.current=!1},50)},[j,i,n]),M=o.useCallback(y=>{if(y===x)return;q.current=!0,E(y);const W=f.getTopic(y);W?(i(W.messages),n.current=W.messages.filter(O=>O.role==="user"||O.role==="assistant").map(O=>({role:O.role==="assistant"?"model":O.role,content:O.content}))):(i([]),n.current=[]),setTimeout(()=>{q.current=!1},50)},[x,E,f,i,n]),_=o.useCallback((y,W)=>{y.stopPropagation(),w(W),W===x&&(q.current=!0,i([]),n.current=[],setTimeout(()=>{q.current=!1},50))},[w,x,i,n]),m=o.useCallback(async()=>{const y=P.trim();if(!y||u)return;let W=x;W||(q.current=!0,W=j(),setTimeout(()=>{q.current=!1},50)),Z(""),i(we=>[...we,{id:fa(),role:"user",content:y,timestamp:Date.now()}]),p(!0);const O=fa();i(we=>[...we,{id:O,role:"assistant",content:`🔄 ${t("aiChat.thinking")}`,timestamp:Date.now()}]),n.current.push({role:"user",content:y});const be=new AbortController;g.current=be;try{const{onEvent:we,getState:ye}=Wa(O,i,t),ee=(await se.chatStream(y,n.current,ae=>{we(ae)},be.signal,s)).text||ye().answerText;n.current.push({role:"model",content:ee}),i(ae=>ae.map(ue=>ue.id===O?{...ue,content:ee}:ue))}catch(we){if(we.name==="AbortError"){const ye=t("aiChat.cancelled");i(v=>v.map(ee=>ee.id===O?{...ee,content:ye}:ee))}else i(ye=>ye.map(v=>v.id===O?{...v,content:t("aiChat.requestFailed",{error:we.message})}:v))}finally{g.current=null}p(!1)},[P,u,x,j]),N=o.useCallback(y=>{y.key==="Enter"&&!y.shiftKey&&(y.preventDefault(),m())},[m]);return e.jsxs("div",{className:"flex-1 flex h-full bg-slate-50",children:[e.jsx("div",{className:`${X?"w-10":"w-64"} shrink-0 bg-white border-r border-slate-200 flex flex-col transition-all duration-200`,children:X?e.jsxs("div",{className:"flex flex-col items-center py-3 gap-2",children:[e.jsx("button",{onClick:()=>H(!1),className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors text-slate-400 hover:text-slate-600",title:t("aiChat.expandTopics"),children:e.jsx(rt,{size:16})}),e.jsx("button",{onClick:R,className:"p-1.5 hover:bg-blue-50 rounded-lg transition-colors text-blue-500",title:t("aiChat.newTopic"),children:e.jsx(Nt,{size:16})})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"px-3 py-2.5 border-b border-slate-100 flex items-center justify-between shrink-0",children:[e.jsx("span",{className:"text-xs font-bold text-slate-500 uppercase tracking-wider",children:t("aiChat.topicRecords")}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx("button",{onClick:R,className:"p-1.5 hover:bg-blue-50 rounded-lg transition-colors text-slate-400 hover:text-blue-600",title:t("aiChat.newTopic"),children:e.jsx(Nt,{size:14})}),e.jsx("button",{onClick:()=>H(!0),className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors text-slate-400 hover:text-slate-600",title:t("common.collapse"),children:e.jsx(is,{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(Lt,{size:24,className:"text-slate-200 mx-auto mb-2"}),e.jsx("p",{className:"text-xs text-slate-400",children:t("aiChat.noHistory")}),e.jsx("p",{className:"text-[10px] text-slate-300 mt-1",children:t("aiChat.autoSaveHint")})]}):e.jsx("div",{className:"py-1",children:h.map(y=>{const W=y.id===x,O=y.messages.filter(be=>be.role==="user").length;return e.jsx("div",{onClick:()=>M(y.id),className:`group mx-1.5 mb-0.5 px-3 py-2 rounded-lg cursor-pointer transition-colors ${W?"bg-blue-50 border border-blue-200":"hover:bg-slate-50 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 ${W?"text-blue-700":"text-slate-700"}`,children:y.title}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsxs("span",{className:"text-[10px] text-slate-400 flex items-center gap-0.5",children:[e.jsx(xt,{size:9}),wn(y.updatedAt,t)]}),O>0&&e.jsx("span",{className:"text-[10px] text-slate-300",children:t("aiChat.messageCount",{n:O})})]})]}),e.jsx("button",{onClick:be=>_(be,y.id),className:`p-1 rounded transition-colors shrink-0 ${W?"text-blue-400 hover:text-red-500 hover:bg-red-50":"text-transparent group-hover:text-slate-300 hover:!text-red-500 hover:!bg-red-50"}`,title:t("aiChat.deleteTopic"),children:e.jsx(ot,{size:12})})]})},y.id)})})}),h.length>0&&e.jsx("div",{className:"px-3 py-2 border-t border-slate-100 shrink-0",children:e.jsx("span",{className:"text-[10px] text-slate-400",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-slate-200 bg-white 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(Lt,{className:"text-blue-600",size:18})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm font-bold text-slate-800",children:c?c.title:"AI Chat"}),e.jsx("p",{className:"text-[11px] text-slate-400",children:t("aiChat.askAnything")})]})]}),d.length>0&&e.jsxs("button",{onClick:R,className:"flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-slate-500 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors border border-slate-200 hover:border-blue-200",children:[e.jsx(Nt,{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:[d.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(Qe,{className:"text-blue-500",size:28})}),e.jsx("h3",{className:"text-base font-bold text-slate-700 mb-2",children:t("aiChat.startChat")}),e.jsx("p",{className:"text-sm text-slate-400 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(y=>e.jsx("button",{onClick:()=>{var W;Z(y.label),(W=z.current)==null||W.focus()},className:"text-xs px-3.5 py-2 rounded-lg bg-white border border-slate-200 text-slate-600 hover:bg-blue-50 hover:text-blue-700 hover:border-blue-200 transition-colors shadow-sm",children:y.label},y.key))})]}),d.map(y=>e.jsx("div",{className:`flex ${y.role==="user"?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[80%] ${y.role==="user"?"bg-blue-600 text-white rounded-2xl rounded-tr-md px-4 py-2.5":y.role==="system"?"bg-slate-100 border border-slate-200 text-slate-600 rounded-2xl px-4 py-2.5 w-full":"bg-white border border-slate-200 rounded-2xl rounded-tl-md px-4 py-3 shadow-sm w-full"}`,children:[y.role==="assistant"&&e.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[e.jsx(rs,{size:13,className:"text-blue-500"}),e.jsx("span",{className:"text-[11px] font-bold text-blue-600",children:t("aiChat.aiAssistant")})]}),y.role==="assistant"&&!y.diff?e.jsx(gt,{content:y.content,className:"text-sm text-slate-700"}):e.jsx("p",{className:`text-sm leading-relaxed whitespace-pre-wrap ${y.role==="user"?"":"text-slate-600"}`,children:y.content}),y.diff&&y.diff.length>0&&e.jsx("div",{className:"space-y-2 mt-2",children:y.diff.map(W=>e.jsx(Nn,{d:W},W.field))})]})},y.id)),u&&e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"bg-white border border-slate-200 rounded-2xl rounded-tl-md px-4 py-3 shadow-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fe,{size:14,className:"animate-spin text-blue-500"}),e.jsx("span",{className:"text-sm text-slate-500",children:t("aiChat.thinking")}),g.current&&e.jsx("button",{onClick:()=>{var y;return(y=g.current)==null?void 0:y.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:G})]})}),e.jsx("div",{className:"border-t border-slate-200 bg-white 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:z,value:P,onChange:y=>Z(y.target.value),onKeyDown:N,placeholder:t("aiChat.inputPlaceholder"),rows:2,className:"flex-1 px-4 py-2.5 text-sm border border-slate-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-200 focus:border-blue-400 resize-none placeholder:text-slate-300",disabled:u}),e.jsx("button",{onClick:m,disabled:!P.trim()||u,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(Bs,{size:16})})]}),e.jsx("p",{className:"text-[10px] text-slate-400 mt-1.5",children:t("aiChat.inputHint")})]})})]})]})},Cn=28,Sn=22,An=50,Dn=11,In=10,bt={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"},Rn={depends_on:"依赖",requires:"需要",extends:"扩展",implements:"实现",inherits:"继承",enforces:"约束",related:"关联",conflicts:"冲突",calls:"调用",prerequisite:"前置",data_flow_to:"数据流",references:"引用",alternative:"替代",deprecated_by:"废弃",solves:"解决"},Ts=[{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"}],Tn=[{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 It(t){return Math.min(An,Math.max(Sn,Cn+t*2))}function ya(t,s){return t.length<=s?t:t.substring(0,s-1)+"…"}function En(t,s,a,l){const d=new Map;for(const f of t)d.set(f.fromId,(d.get(f.fromId)||0)+1),d.set(f.toId,(d.get(f.toId)||0)+1);const i=[...d.keys()],u=[...new Set(i.map(f=>l[f]||"general"))].sort(),p=new Map,n=Math.ceil(Math.sqrt(u.length)),g=400;return u.forEach((f,h)=>{const x=h%n,c=Math.floor(h/n);p.set(f,{x:450+(x-(n-1)/2)*g,y:350+(c-(Math.ceil(u.length/n)-1)/2)*g})}),i.map(f=>{const h=l[f]||"general",x=p.get(h)||{x:450,y:350},c=Math.random()*2*Math.PI,j=40+Math.random()*80;return{id:f,label:s[f]||f,type:a[f]||"recipe",group:h,x:x.x+j*Math.cos(c),y:x.y+j*Math.sin(c),vx:0,vy:0,degree:d.get(f)||1}})}function Pn(t,s,a=200){const l=t.map(u=>({...u})),d=new Map(l.map(u=>[u.id,u]));function i(){const u=new Map;for(const p of l){const n=u.get(p.group);n?(n.x+=p.x,n.y+=p.y,n.count++):u.set(p.group,{x:p.x,y:p.y,count:1})}for(const[,p]of u)p.x/=p.count,p.y/=p.count;return u}for(let u=0;u<a;u++){const p=1-u/a,n=18e3*p,g=.015,f=.8,h=i();for(let c=0;c<l.length;c++)for(let j=c+1;j<l.length;j++){const w=l[c],C=l[j];let E=C.x-w.x,S=C.y-w.y,G=Math.sqrt(E*E+S*S)||1;const z=It(w.degree)+It(C.degree)+60,P=Math.max(G,1),Z=w.group===C.group?.6:1.4,X=n*Z/(P*P),H=G<z?(z-G)*.5:0,q=X+H,R=E/P*q,M=S/P*q;w.vx-=R,w.vy-=M,C.vx+=R,C.vy+=M}for(const c of s){const j=d.get(c.fromId),w=d.get(c.toId);if(!j||!w)continue;let C=w.x-j.x,E=w.y-j.y,S=Math.sqrt(C*C+E*E)||1;const G=j.group===w.group?140:280,z=g*(S-G),P=C/S*z,Z=E/S*z;j.vx+=P,j.vy+=Z,w.vx-=P,w.vy-=Z}const x=.008*p;for(const c of l){const j=h.get(c.group);j&&(c.vx+=(j.x-c.x)*x,c.vy+=(j.y-c.y)*x)}for(const c of l)c.vx*=f,c.vy*=f,c.x+=c.vx,c.y+=c.vy}return l}function Ln(t,s,a,l,d,i,u=0){const p=a-t,n=l-s,g=Math.sqrt(p*p+n*n)||1,f=p/g,h=n/g,x=t+f*d,c=s+h*d,j=a-f*i,w=l-h*i;if(u===0)return`M${x},${c}L${j},${w}`;const C=(x+j)/2+-h*u,E=(c+w)/2+f*u;return`M${x},${c}Q${C},${E},${j},${w}`}const Mn=()=>{const{t}=_e(),{isDark:s}=St(),a=s?Tn:Ts,l=r=>{const k={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 k[r]?t(k[r]):Rn[r]||r},[d,i]=o.useState([]),[u,p]=o.useState({}),[n,g]=o.useState({}),[f,h]=o.useState({}),[x,c]=o.useState(null),[j,w]=o.useState(!0),[C,E]=o.useState(null),[S,G]=o.useState(null),[z,P]=o.useState(null),[Z,X]=o.useState(null),[H,q]=o.useState(!1),[R,M]=o.useState(null),[_,m]=o.useState(!1),[N,y]=o.useState(1),[W,O]=o.useState({x:0,y:0}),be=o.useRef(null),we=o.useRef(null),ye=o.useRef(!1),v=o.useRef({x:0,y:0}),ee=async()=>{var r,k;w(!0),E(null);try{const[b,B]=await Promise.all([se.getKnowledgeGraph(),se.getGraphStats()]);i(b.edges||[]),p(b.nodeLabels||{}),g(b.nodeTypes||{}),h(b.nodeCategories||{}),c(B)}catch(b){E(((k=(r=b.response)==null?void 0:r.data)==null?void 0:k.error)||b.message||t("knowledgeGraph.loadFailed"))}finally{w(!1)}};o.useEffect(()=>{ee()},[]),o.useEffect(()=>{se.getDiscoverRelationsStatus().then(r=>{r.status==="running"&&(q(!0),M(t("knowledgeGraph.discoverAnalyzing",{elapsed:r.elapsed??0})))}).catch(()=>{})},[]),o.useEffect(()=>{if(!H)return;let r=0;const k=240,b=setInterval(async()=>{if(r++,r>k){clearInterval(b),q(!1),m(!0),M(t("knowledgeGraph.discoverPollTimeout"));return}try{const B=await se.getDiscoverRelationsStatus();if(B.status==="done"){q(!1);const D=B.discovered??0,U=B.totalPairs??0,te=B.batchErrors??0;if(D===0&&te===0)m(!1),M(t("knowledgeGraph.discoverNoResults",{pairs:U}));else if(D===0&&te>0)m(!0),M(t("knowledgeGraph.discoverBatchErrors",{errors:te}));else{m(!1);const de=te>0?t("knowledgeGraph.discoverBatchFailed",{count:te}):"";M(t("knowledgeGraph.discoverSuccess",{count:D,pairs:U,failMsg:de}))}ee()}else if(B.status==="error"){q(!1),m(!0);const D=B.error||t("knowledgeGraph.unknownError");D.includes("AI Provider")||D.includes("API Key")?M(t("knowledgeGraph.discoverAiNotConfigured",{error:D})):D.includes("超时")||D.includes("timeout")?M(t("knowledgeGraph.discoverTimeout",{error:D})):M(t("knowledgeGraph.discoverFailed",{error:D}))}else B.status==="running"&&M(t("knowledgeGraph.discoverAnalyzing",{elapsed:B.elapsed??0}))}catch{}},3e3);return()=>clearInterval(b)},[H]);const ae=o.useCallback(async()=>{var r,k,b;M(null),m(!1);try{const B=await se.discoverRelations();if(B.status==="empty"){M(B.message||t("knowledgeGraph.discoverInsufficientRecipes"));return}if(B.status==="timeout"){m(!0),M(B.error||t("knowledgeGraph.discoverPreviousTimeout"));return}if(B.status==="running"){q(!0),M(t("knowledgeGraph.discoverRunning"));return}q(!0),M(t("knowledgeGraph.discoverStarted"))}catch(B){m(!0);const D=((b=(k=(r=B==null?void 0:B.response)==null?void 0:r.data)==null?void 0:k.error)==null?void 0:b.message)||B.message||t("knowledgeGraph.unknownError");D.includes("ChatAgent")||D.includes("AI Provider")?M(t("knowledgeGraph.discoverAiUnavailable",{error:D})):M(t("knowledgeGraph.discoverStartFailed",{error:D}))}},[t]),ue=o.useMemo(()=>{if(d.length===0)return[];const r=En(d,u,n,f);return Pn(r,d)},[d,u,n,f]),fe=o.useMemo(()=>{const r=new Map;for(const B of ue){const D=r.get(B.group)||[];D.push(B),r.set(B.group,D)}const k=[],b=[...r.keys()].sort();for(const B of b){const D=r.get(B);if(D.length===0)continue;let U=0,te=0;for(const I of D)U+=I.x,te+=I.y;U/=D.length,te/=D.length;let de=0,me=0;for(const I of D){const V=It(I.degree);de=Math.max(de,Math.abs(I.x-U)+V+35),me=Math.max(me,Math.abs(I.y-te)+V+35)}k.push({group:B,cx:U,cy:te,rx:Math.max(de,60),ry:Math.max(me,60),count:D.length})}return k},[ue]),he=o.useMemo(()=>{const r=[...new Set(ue.map(b=>b.group))].sort(),k={};return r.forEach((b,B)=>{k[b]=a[B%a.length]}),k},[ue,a]),ce=o.useMemo(()=>{if(ue.length===0)return{x:0,y:0,w:900,h:700};let r=1/0,k=1/0,b=-1/0,B=-1/0;for(const D of ue){const U=It(D.degree);r=Math.min(r,D.x-U-80),k=Math.min(k,D.y-U-40),b=Math.max(b,D.x+U+80),B=Math.max(B,D.y+U+40)}return{x:r,y:k,w:b-r,h:B-k}},[ue]),je=o.useMemo(()=>new Map(ue.map(r=>[r.id,r])),[ue]),{connectedEdgeIds:$,connectedNodeIds:K}=o.useMemo(()=>{const r=S||z;if(!r)return{connectedEdgeIds:new Set,connectedNodeIds:new Set};const k=new Set,b=new Set([r]);for(const B of d)(B.fromId===r||B.toId===r)&&(k.add(B.id),b.add(B.fromId),b.add(B.toId));return{connectedEdgeIds:k,connectedNodeIds:b}},[S,z,d]),xe=o.useMemo(()=>{const r=new Map,k=new Map;for(const B of d){const D=[B.fromId,B.toId].sort().join("|"),U=r.get(D)||0;k.set(B.id,U),r.set(D,U+1)}const b=new Map;for(const B of d){const D=[B.fromId,B.toId].sort().join("|"),U=r.get(D)||1;if(U<=1){b.set(B.id,0);continue}const te=k.get(B.id)||0;b.set(B.id,(te-(U-1)/2)*40)}return b},[d]),[L,T]=o.useState(new Set);o.useEffect(()=>{T(new Set(d.map(r=>r.relation)))},[d]);const Q=o.useMemo(()=>d.filter(r=>L.has(r.relation)),[d,L]),ie=r=>{T(k=>{const b=new Set(k);return b.has(r)?b.delete(r):b.add(r),b})},ke=o.useCallback(r=>{r.button===0&&(ye.current=!0,v.current={x:r.clientX,y:r.clientY})},[]),Ue=o.useCallback(r=>{if(!ye.current)return;const k=r.clientX-v.current.x,b=r.clientY-v.current.y;v.current={x:r.clientX,y:r.clientY},O(B=>({x:B.x+k,y:B.y+b}))},[]),Ie=o.useCallback(()=>{ye.current=!1},[]),ne=o.useCallback(r=>{r.preventDefault();const k=r.deltaY>0?-.1:.1;y(b=>Math.min(3,Math.max(.2,b+k)))},[]),ve=r=>`kg-arrow-${r.replace(/[^a-z_]/g,"")}`;if(j)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(C)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:C}),e.jsx("button",{onClick:ee,className:"px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors",children:t("knowledgeGraph.retry")})]});if(d.length===0)return e.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-slate-500",children:[e.jsx(Ls,{size:48,className:"text-slate-300"}),e.jsx("p",{className:"text-lg font-medium",children:t("knowledgeGraph.empty")}),e.jsx("p",{className:"text-sm text-center max-w-md",children:t("knowledgeGraph.emptyDesc")}),R&&e.jsx("p",{className:`text-sm ${_?"text-red-500":"text-green-600"}`,children:R}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:ae,disabled:H,className:"px-4 py-2 bg-violet-600 text-white rounded-lg hover:bg-violet-700 transition-colors flex items-center gap-2 disabled:opacity-50",children:H?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-white"})," ",t("knowledgeGraph.discovering")]}):e.jsxs(e.Fragment,{children:[e.jsx(Qe,{size:F.sm})," ",t("knowledgeGraph.discoverRelations")]})}),e.jsxs("button",{onClick:ee,className:"px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center gap-2",children:[e.jsx(yt,{size:F.sm})," ",t("knowledgeGraph.refresh")]})]})]});const He=[...new Set(d.map(r=>r.relation))].sort(),Ne=!!(S||z);return e.jsxs("div",{className:"h-full flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ls,{size:F.lg,className:"text-blue-600"}),e.jsx("h2",{className:`text-lg font-bold ${s?"text-slate-100":"text-slate-800"}`,children:t("knowledgeGraph.title")}),x&&e.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${s?"text-slate-400 bg-slate-700/60":"text-slate-500 bg-slate-100"}`,children:t("knowledgeGraph.statsLabel",{nodes:ue.length,edges:x.totalEdges})})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{onClick:()=>y(r=>Math.min(r+.2,3)),className:`p-1.5 rounded-lg transition-colors ${s?"bg-slate-700 hover:bg-slate-600 text-slate-300":"bg-slate-100 hover:bg-slate-200"}`,title:t("knowledgeGraph.zoomIn"),children:e.jsx(El,{size:F.sm})}),e.jsx("button",{onClick:()=>y(r=>Math.max(r-.2,.2)),className:`p-1.5 rounded-lg transition-colors ${s?"bg-slate-700 hover:bg-slate-600 text-slate-300":"bg-slate-100 hover:bg-slate-200"}`,title:t("knowledgeGraph.zoomOut"),children:e.jsx(Pl,{size:F.sm})}),e.jsx("button",{onClick:()=>{y(1),O({x:0,y:0})},className:`p-1.5 rounded-lg transition-colors ${s?"bg-slate-700 hover:bg-slate-600 text-slate-300":"bg-slate-100 hover:bg-slate-200"}`,title:t("knowledgeGraph.resetView"),children:e.jsx(Cs,{size:F.sm})}),e.jsx("button",{onClick:ee,className:`p-1.5 rounded-lg transition-colors ${s?"bg-slate-700 hover:bg-slate-600 text-slate-300":"bg-slate-100 hover:bg-slate-200"}`,title:t("knowledgeGraph.refresh"),children:e.jsx(yt,{size:F.sm})}),e.jsx("button",{onClick:ae,disabled:H,className:`flex items-center gap-1 px-2.5 py-1 rounded-lg text-xs font-medium transition-colors disabled:opacity-50 ${s?"bg-violet-500/15 hover:bg-violet-500/25 text-violet-400":"bg-violet-50 hover:bg-violet-100 text-violet-700"}`,title:t("knowledgeGraph.discoverTooltip"),children:H?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"animate-spin rounded-full h-3 w-3 border-b-2 border-violet-600"})," ",t("knowledgeGraph.discovering")]}):e.jsxs(e.Fragment,{children:[e.jsx(Qe,{size:F.sm})," ",t("knowledgeGraph.discoverRelations")]})})]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-3 flex-shrink-0",children:He.map(r=>{var k;return e.jsxs("button",{onClick:()=>ie(r),className:`flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-medium transition-all border ${L.has(r)?"border-transparent shadow-sm":s?"border-slate-600 bg-slate-800 text-slate-500 opacity-40":"border-slate-200 bg-white text-slate-400 opacity-40"}`,style:L.has(r)?{backgroundColor:(bt[r]||"#6b7280")+"18",color:bt[r]||"#6b7280"}:{},children:[e.jsx("span",{className:"w-2 h-2 rounded-full",style:{backgroundColor:bt[r]||"#6b7280"}}),l(r),((k=x==null?void 0:x.byRelation)==null?void 0:k[r])!=null&&e.jsxs("span",{className:"opacity-60",children:["(",x.byRelation[r],")"]})]},r)})}),e.jsxs("div",{ref:we,className:`flex-1 rounded-xl border overflow-hidden relative min-h-0 ${s?"border-slate-700 bg-[#13151c]":"border-slate-200 bg-gradient-to-br from-slate-50 to-white"}`,style:{cursor:ye.current?"grabbing":"grab"},onWheel:ne,children:[e.jsxs("svg",{ref:be,width:"100%",height:"100%",viewBox:`${ce.x} ${ce.y} ${ce.w} ${ce.h}`,onMouseDown:ke,onMouseMove:Ue,onMouseUp:Ie,onMouseLeave:Ie,style:{transform:`scale(${N}) translate(${W.x/N}px, ${W.y/N}px)`},children:[e.jsxs("defs",{children:[He.map(r=>e.jsx("marker",{id:ve(r),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:bt[r]||"#6b7280"})},r)),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:fe.map(r=>{const k=he[r.group]||Ts[0];return e.jsxs("g",{children:[e.jsx("ellipse",{cx:r.cx,cy:r.cy,rx:r.rx,ry:r.ry,fill:k.bg,stroke:k.border,strokeWidth:1.5,strokeDasharray:"6,4",opacity:.6}),e.jsxs("text",{x:r.cx,y:r.cy-r.ry+14,textAnchor:"middle",fontSize:11,fontWeight:600,fill:k.text,opacity:.8,style:{pointerEvents:"none",userSelect:"none"},children:[r.group||"general"," (",r.count,")"]})]},r.group)})}),e.jsx("g",{children:Q.map(r=>{const k=je.get(r.fromId),b=je.get(r.toId);if(!k||!b)return null;const B=Ne?$.has(r.id):!1,D=Z===r.id,U=Ne?B?.85:.06:D?.9:.35,te=It(k.degree),de=It(b.degree),me=xe.get(r.id)||0,I=Ln(k.x,k.y,b.x,b.y,te,de,me);return e.jsxs("g",{children:[e.jsx("path",{d:I,fill:"none",stroke:"transparent",strokeWidth:12,onMouseEnter:()=>X(r.id),onMouseLeave:()=>X(null),style:{cursor:"pointer"}}),e.jsx("path",{d:I,fill:"none",stroke:bt[r.relation]||"#6b7280",strokeWidth:D||B?2:1.2,opacity:U,markerEnd:`url(#${ve(r.relation)})`,strokeDasharray:r.relation==="related"?"6,3":void 0,style:{transition:"opacity 0.25s, stroke-width 0.15s",pointerEvents:"none"}}),D&&(()=>{const V=(k.x+b.x)/2,Ce=(k.y+b.y)/2;return e.jsxs("g",{children:[e.jsx("rect",{x:V-24,y:Ce-16,width:48,height:18,rx:4,fill:s?"#252526":"white",stroke:bt[r.relation]||"#6b7280",strokeWidth:.8,opacity:.95}),e.jsx("text",{x:V,y:Ce-4,textAnchor:"middle",fontSize:9,fontWeight:600,fill:bt[r.relation]||"#6b7280",children:l(r.relation)})]})})()]},r.id)})}),e.jsx("g",{children:ue.map(r=>{const k=It(r.degree),b=S===r.id,B=Ne&&K.has(r.id),D=b||r.id===z,U=Ne&&!B,te=U?.12:1,de=he[r.group]||Ts[0],me=D?de.border:de.bg,I=D?de.text:de.border,V=D?"#ffffff":de.text,Ce=D?de.text:s?"#9ca3af":"#64748b";return e.jsxs("g",{onClick:Ae=>{Ae.stopPropagation(),G(b?null:r.id)},onMouseEnter:()=>P(r.id),onMouseLeave:()=>P(null),style:{cursor:"pointer",transition:"opacity 0.25s"},opacity:te,filter:D?"url(#kg-glow)":void 0,children:[e.jsx("circle",{cx:r.x,cy:r.y,r:k,fill:me,stroke:I,strokeWidth:D?2.5:1.5}),e.jsx("text",{x:r.x,y:r.y+4,textAnchor:"middle",fontSize:Math.min(Dn,k*.7),fill:V,fontWeight:700,style:{pointerEvents:"none",userSelect:"none"},children:ya(r.label,4).toUpperCase()}),e.jsx("text",{x:r.x,y:r.y+k+14,textAnchor:"middle",fontSize:In,fill:Ce,fontWeight:D?600:400,style:{pointerEvents:"none",userSelect:"none"},children:ya(r.label,18)}),r.degree>=3&&!U&&e.jsxs("g",{children:[e.jsx("circle",{cx:r.x+k*.7,cy:r.y-k*.7,r:8,fill:"#3b82f6",stroke:s?"#1e1e1e":"white",strokeWidth:1.5}),e.jsx("text",{x:r.x+k*.7,y:r.y-k*.7+3.5,textAnchor:"middle",fontSize:8,fill:"white",fontWeight:700,style:{pointerEvents:"none"},children:r.degree})]})]},r.id)})})]}),S&&e.jsx("button",{className:`absolute top-2 right-2 text-xs px-2 py-1 rounded-md shadow-sm border ${s?"text-slate-400 hover:text-slate-200 bg-[#252526]/90 border-slate-600":"text-slate-400 hover:text-slate-600 bg-white/90 border-slate-200"}`,onClick:()=>G(null),children:t("knowledgeGraph.cancelSelection")})]}),S&&e.jsxs("div",{className:`mt-3 p-4 rounded-xl border shadow-sm flex-shrink-0 max-h-48 overflow-y-auto scrollbar-light ${s?"bg-[#1e1e1e] border-slate-700":"bg-white border-slate-200"}`,children:[e.jsxs("div",{className:`flex items-center gap-2 mb-3 pb-2 border-b ${s?"border-slate-700":"border-slate-100"}`,children:[e.jsx(_a,{size:14,className:"text-blue-500"}),e.jsx("h3",{className:`font-semibold text-sm ${s?"text-slate-200":"text-slate-800"}`,children:u[S]||S}),e.jsxs("span",{className:"text-[10px] text-slate-400 ml-auto",children:["ID: ",S]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-xs",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-500 font-medium",children:t("knowledgeGraph.outEdges")}),e.jsxs("ul",{className:"mt-1.5 space-y-1",children:[d.filter(r=>r.fromId===S&&L.has(r.relation)).map(r=>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:bt[r.relation]||"#6b7280"}}),e.jsx("span",{className:"text-slate-500",children:l(r.relation)}),e.jsx("span",{className:"text-slate-400",children:"→"}),e.jsx("button",{className:"text-blue-600 hover:underline truncate",onClick:()=>G(r.toId),children:u[r.toId]||r.toId.substring(0,16)})]},r.id)),d.filter(r=>r.fromId===S&&L.has(r.relation)).length===0&&e.jsx("li",{className:"text-slate-400",children:t("knowledgeGraph.none")})]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-slate-500 font-medium",children:t("knowledgeGraph.inEdges")}),e.jsxs("ul",{className:"mt-1.5 space-y-1",children:[d.filter(r=>r.toId===S&&L.has(r.relation)).map(r=>e.jsxs("li",{className:"flex items-center gap-1.5",children:[e.jsx("button",{className:"text-blue-600 hover:underline truncate",onClick:()=>G(r.fromId),children:u[r.fromId]||r.fromId.substring(0,16)}),e.jsx("span",{className:"text-slate-400",children:"→"}),e.jsx("span",{className:"text-slate-500",children:l(r.relation)}),e.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:bt[r.relation]||"#6b7280"}})]},r.id)),d.filter(r=>r.toId===S&&L.has(r.relation)).length===0&&e.jsx("li",{className:"text-slate-400",children:t("knowledgeGraph.none")})]})]})]})]})]})},mt={pending:{labelKey:"lifecycle.pending",color:"text-amber-700",bg:"bg-amber-50",border:"border-amber-200",icon:xt},active:{labelKey:"lifecycle.active",color:"text-green-700",bg:"bg-green-50",border:"border-green-200",icon:cs},deprecated:{labelKey:"lifecycle.deprecated",color:"text-orange-600",bg:"bg-orange-50",border:"border-orange-200",icon:Fs}},Jt={rule:{labelKey:"kind.rule",color:"text-red-700",bg:"bg-red-50",border:"border-red-200",icon:ut},pattern:{labelKey:"kind.pattern",color:"text-violet-700",bg:"bg-violet-50",border:"border-violet-200",icon:jt},fact:{labelKey:"kind.fact",color:"text-cyan-700",bg:"bg-cyan-50",border:"border-cyan-200",icon:tt}},Fn={pending:[{action:"publish",labelKey:"knowledge.actionPublish",color:"text-green-700",bg:"bg-green-50 hover:bg-green-100",icon:cs},{action:"deprecate",labelKey:"knowledge.actionDeprecate",color:"text-orange-700",bg:"bg-orange-50 hover:bg-orange-100",icon:Fs,needsReason:!0}],active:[{action:"deprecate",labelKey:"knowledge.actionDeprecate",color:"text-orange-700",bg:"bg-orange-50 hover:bg-orange-100",icon:Fs,needsReason:!0}],deprecated:[{action:"reactivate",labelKey:"knowledge.actionReactivate",color:"text-green-700",bg:"bg-green-50 hover:bg-green-100",icon:Ra}]};function Yt(t,s){if(!t)return"";const a=t<1e12?t*1e3:t,l=new Date(a);if(isNaN(l.getTime())||l.getFullYear()<2e3)return"";const i=Date.now()-a;if(i<0)return l.toLocaleDateString();const u=Math.floor(i/6e4);if(u<1)return s("candidates.timeJustNow");if(u<60)return s("candidates.timeMinutesAgo",{n:u});const p=Math.floor(u/60);if(p<24)return s("candidates.timeHoursAgo",{n:p});const n=Math.floor(p/24);return n<7?s("candidates.timeDaysAgo",{n}):l.toLocaleDateString()}function zn(t){return t==null?{ring:"stroke-slate-200",text:"text-slate-400",bg:"bg-slate-50",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 _n(t,s=4){return t?Us(t).split(`
117
+ `).slice(0,s).join(`
118
+ `):""}const Es={"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-slate-600 bg-slate-50 border-slate-200"},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"}},$n=({onRefresh:t,idTitleMap:s})=>{const{t:a}=_e(),l=T=>({pending:a("knowledge.lifecyclePending"),active:a("knowledge.lifecycleActive"),deprecated:a("knowledge.lifecycleDeprecated")})[T]||T,d=T=>({publish:a("knowledge.actionPublish"),deprecate:a("knowledge.actionDeprecate"),reactivate:a("knowledge.actionReactivate")})[T]||T,[i,u]=o.useState([]),[p,n]=o.useState(null),[g,f]=o.useState(!0),[h,x]=o.useState(1),[c,j]=o.useState(20),[w,C]=o.useState(0),[E,S]=o.useState(""),[G,z]=o.useState(""),[P,Z]=o.useState(""),[X,H]=o.useState(""),[q,R]=o.useState(""),{isWide:M,toggle:_}=Vs(),[m,N]=o.useState(null),[y,W]=o.useState(!1),[O,be]=o.useState(new Set),[we,ye]=o.useState(!1),v=o.useRef(!0);o.useEffect(()=>(v.current=!0,()=>{v.current=!1}),[]);const ee=o.useCallback(async()=>{var T;f(!0);try{const Q=await se.knowledgeList({page:h,limit:c,lifecycle:E||void 0,kind:G||void 0,category:P||void 0,keyword:X||void 0});v.current&&(u(Q.data||[]),C(((T=Q.pagination)==null?void 0:T.total)||0))}catch(Q){re((Q==null?void 0:Q.message)||a("knowledge.loadFailed"),{title:a("common.loadFailed"),type:"error"})}finally{v.current&&f(!1)}},[h,c,E,G,P,X]),ae=o.useCallback(async()=>{try{const T=await se.knowledgeStats();v.current&&n(T)}catch{}},[]);o.useEffect(()=>{ee()},[ee]),o.useEffect(()=>{ae()},[ae]),o.useEffect(()=>{const T=setTimeout(()=>{H(q),x(1)},300);return()=>clearTimeout(T)},[q]),o.useEffect(()=>{x(1)},[E,G,P]);const ue=o.useCallback(()=>{ee(),ae(),t==null||t()},[ee,ae,t]),fe=o.useMemo(()=>{const T=new Map;if(s)for(const[Q,ie]of Object.entries(s))T.set(Q,ie);for(const Q of i)Q.id&&Q.title&&T.set(Q.id,Q.title);return T},[i,s]),he=async(T,Q,ie)=>{var ke,Ue,Ie,ne;W(!0);try{const ve=await se.knowledgeLifecycle(T.id,Q,ie);re(`${T.title} → ${a(((ke=mt[ve.lifecycle])==null?void 0:ke.labelKey)||"")||ve.lifecycle}`,{title:a("knowledge.operationSuccess")}),u(He=>He.map(Pe=>Pe.id===T.id?ve:Pe)),(m==null?void 0:m.id)===T.id&&N(ve),ae()}catch(ve){re(((ne=(Ie=(Ue=ve==null?void 0:ve.response)==null?void 0:Ue.data)==null?void 0:Ie.error)==null?void 0:ne.message)||(ve==null?void 0:ve.message)||a("common.operationFailed"),{title:a("common.operationFailed"),type:"error"})}finally{v.current&&W(!1)}},ce=async T=>{if(confirm(a("knowledge.deleteConfirmMsg",{title:T.title})))try{await se.knowledgeDelete(T.id),re(a("knowledge.deleteSuccess",{title:T.title}),{title:a("common.delete")}),u(Q=>Q.filter(ie=>ie.id!==T.id)),(m==null?void 0:m.id)===T.id&&N(null),ae()}catch(Q){re((Q==null?void 0:Q.message)||a("knowledge.deleteFailed"),{title:a("knowledge.deleteFailed"),type:"error"})}},je=async()=>{if(O.size!==0){ye(!0);try{const T=await se.knowledgeBatchPublish([...O]);re(a("knowledge.batchPublishResult",{success:T.successCount,fail:T.failureCount}),{title:a("knowledge.batchPublish")}),be(new Set),ue()}catch(T){re((T==null?void 0:T.message)||a("knowledge.batchPublishFailed"),{title:a("common.operationFailed"),type:"error"})}finally{ye(!1)}}},$=async()=>{ye(!0);try{const Q=((await se.knowledgeList({lifecycle:"pending",limit:500})).data||[]).filter(ke=>ke.autoApprovable).map(ke=>ke.id);if(Q.length===0){re(a("knowledge.noAutoApprovable"),{title:a("knowledge.noPublishable")});return}const ie=await se.knowledgeBatchPublish(Q);re(a("knowledge.autoPublishResult",{count:ie.successCount}),{title:a("knowledge.batchPublishComplete")}),ue()}catch(T){re((T==null?void 0:T.message)||a("knowledge.batchPublishFailed"),{title:a("common.operationFailed"),type:"error"})}finally{ye(!1)}},K=T=>{be(Q=>{const ie=new Set(Q);return ie.has(T)?ie.delete(T):ie.add(T),ie})},xe=()=>{O.size===i.length?be(new Set):be(new Set(i.map(T=>T.id)))},L=(T,Q)=>{const ie=prompt(a("knowledge.deprecateReasonPrompt"));ie&&he(T,Q,ie)};return e.jsxs("div",{className:"space-y-4",children:[p&&e.jsx("div",{className:"grid grid-cols-3 gap-3",children:Object.entries(mt).map(([T,Q])=>{const ie=p[T]||0,ke=Q.icon;return e.jsxs("button",{onClick:()=>{S(E===T?"":T)},className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-all text-left ${E===T?`${Q.bg} ${Q.border} ${Q.color} ring-1 ring-current`:"bg-white dark:bg-[#252a36] border-slate-200 dark:border-slate-600 text-slate-600 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-[#2a3040]"}`,children:[e.jsx(ke,{size:14}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium",children:l(T)}),e.jsx("div",{className:"text-lg font-bold",children:ie})]})]},T)})}),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(ft,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-400",size:16}),e.jsx("input",{type:"text",placeholder:a("knowledge.searchPlaceholder"),value:q,onChange:T=>R(T.target.value),className:"w-full pl-9 pr-3 py-2 rounded-lg border border-slate-200 text-sm focus:outline-none focus:ring-2 focus:ring-blue-300"})]}),e.jsx("div",{className:"flex gap-1",children:Object.entries(Jt).map(([T,Q])=>{const ie=Q.icon;return e.jsxs("button",{onClick:()=>z(G===T?"":T),className:`flex items-center gap-1 px-2.5 py-1.5 rounded-md text-xs font-medium border transition-all ${G===T?`${Q.bg} ${Q.border} ${Q.color}`:"bg-white dark:bg-[#252a36] border-slate-200 dark:border-slate-600 text-slate-500 dark:text-slate-400 hover:bg-slate-50 dark:hover:bg-[#2a3040]"}`,children:[e.jsx(ie,{size:12}),a(Q.labelKey)]},T)})}),e.jsxs("select",{value:P,onChange:T=>Z(T.target.value),className:"px-2.5 py-1.5 rounded-md text-xs border border-slate-200 dark:border-slate-600 bg-white dark:bg-[#252a36] text-slate-600 dark:text-slate-300 focus:outline-none",children:[e.jsx("option",{value:"",children:a("knowledge.allCategories")}),["View","Service","Tool","Model","Network","Storage","UI","Utility"].map(T=>e.jsx("option",{value:T,children:T},T))]}),e.jsx("button",{onClick:ue,className:"p-2 rounded-md text-slate-400 hover:bg-slate-100",title:a("common.refresh"),children:e.jsx(yt,{size:16})}),O.size>0&&e.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[e.jsx("span",{className:"text-xs text-slate-500",children:a("knowledge.selectedCount",{count:O.size})}),e.jsx("button",{onClick:je,disabled:we,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:we?e.jsx(Fe,{size:12,className:"animate-spin"}):a("knowledge.batchPublish")}),e.jsx("button",{onClick:()=>be(new Set),className:"p-1 text-slate-400 hover:text-slate-600",children:e.jsx(Xe,{size:14})})]}),O.size===0&&e.jsxs("button",{onClick:$,disabled:we,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:[we?e.jsx(Fe,{size:12,className:"animate-spin"}):e.jsx(et,{size:12}),a("knowledge.quickBatchPublish")]})]}),g?e.jsxs("div",{className:"flex items-center justify-center py-20 text-slate-400",children:[e.jsx(Fe,{size:24,className:"animate-spin mr-2"}),e.jsx("span",{children:a("common.loading")})]}):i.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-slate-400",children:[e.jsx(tt,{size:48,className:"mb-4 opacity-30"}),e.jsx("p",{className:"text-sm",children:a("knowledge.noResults")}),(X||E||G||P)&&e.jsx("button",{onClick:()=>{R(""),S(""),z(""),Z("")},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:O.size===i.length&&i.length>0,onChange:xe,className:"rounded border-slate-300"}),e.jsx("span",{className:"text-xs text-slate-400",children:a("knowledge.selectAll")}),e.jsx("span",{className:"text-xs text-slate-400 ml-auto",children:a("knowledge.totalCount",{count:w})})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:i.map(T=>{var ne,ve,He,Pe,Ne,r;const Q=mt[T.lifecycle]||mt.pending,ie=Jt[T.kind]||Jt.pattern,ke=Q.icon,Ue=ie.icon,Ie=zn((ne=T.reasoning)==null?void 0:ne.confidence);return e.jsxs("div",{onClick:()=>N(T),className:`group bg-white dark:bg-[#1e2028] rounded-xl border shadow-sm hover:shadow-md cursor-pointer transition-all overflow-hidden ${(m==null?void 0:m.id)===T.id?"ring-2 ring-blue-300 border-blue-200 dark:border-blue-700":"border-slate-200 dark:border-slate-700"}`,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:O.has(T.id),onChange:k=>{k.stopPropagation(),K(T.id)},onClick:k=>k.stopPropagation(),className:"rounded border-slate-300"}),e.jsxs("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium ${Q.bg} ${Q.color} ${Q.border} border`,children:[e.jsx(ke,{size:10}),l(T.lifecycle)]}),e.jsxs("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium ${ie.bg} ${ie.color} ${ie.border} border`,children:[e.jsx(Ue,{size:10}),a(ie.labelKey)]}),T.category&&e.jsx("span",{className:"text-[10px] text-slate-400",children:T.category}),e.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded ${Ie.bg} ${Ie.text}`,children:((ve=T.reasoning)==null?void 0:ve.confidence)!=null?`${Math.round(T.reasoning.confidence*100)}%`:"—"}),T.autoApprovable&&T.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(et,{size:9}),a("knowledge.autoApprovable")]})]}),e.jsx("h3",{className:"text-sm font-bold text-slate-900 mb-1 break-words leading-snug",children:T.title}),(T.description||((He=T.content)==null?void 0:He.rationale))&&e.jsx("p",{className:"text-xs text-slate-500 line-clamp-2 leading-relaxed",children:T.description||((Pe=T.content)==null?void 0:Pe.rationale)||""}),((Ne=T.content)==null?void 0:Ne.pattern)&&e.jsx("pre",{className:"mt-1.5 text-[10px] text-slate-500 bg-slate-50 rounded p-1.5 line-clamp-3 font-mono overflow-hidden",children:_n(T.content.pattern,3)})]}),e.jsxs("div",{className:"px-4 py-2 bg-slate-50/80 dark:bg-[#252a36] border-t border-slate-100 dark:border-slate-700 flex items-center gap-2",children:[(r=T.tags)==null?void 0:r.slice(0,3).map(k=>e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100",children:k},k)),T.tags&&T.tags.length>3&&e.jsxs("span",{className:"text-[10px] text-slate-400",children:["+",T.tags.length-3]}),e.jsxs("span",{className:"text-[10px] text-slate-300 ml-auto",children:[T.trigger&&e.jsx("span",{className:"text-blue-400 mr-2",children:T.trigger}),T.source&&e.jsx("span",{className:"mr-2",children:T.source}),Yt(T.updatedAt,a)]})]})]},T.id)})}),e.jsx(Js,{currentPage:h,totalPages:Math.ceil(w/c),onPageChange:x,pageSize:c,onPageSizeChange:T=>{j(T),x(1)},totalItems:w})]}),m&&(()=>{var k,b,B,D,U,te,de,me;const T=mt[m.lifecycle]||mt.pending,Q=T.icon,ie=Jt[m.kind]||Jt.pattern,ke=ct[m.category||""]||ct.All||{},Ue=Es[m.source||""]||{labelKey:""};Ue.labelKey?a(Ue.labelKey):m.source;const Ie=m.reasoning,ne=Ie&&(Ie.whyStandard||Ie.sources&&Ie.sources.length>0||Ie.confidence!=null),ve=i.findIndex(I=>I.id===m.id),He=ve>0,Pe=ve<i.length-1,Ne=()=>{He&&N(i[ve-1])},r=()=>{Pe&&N(i[ve+1])};return e.jsxs(Ze,{className:"z-30 flex justify-end",onClick:()=>N(null),children:[e.jsx(Ze.Backdrop,{className:"bg-black/15 backdrop-blur-[1px]"}),e.jsxs("div",{className:`relative h-full bg-white dark:bg-[#1e1e1e] shadow-2xl flex flex-col border-l border-slate-200 dark:border-slate-700 ${M?"w-[960px] max-w-[92vw]":"w-[700px] max-w-[92vw]"}`,style:{animation:"slideInRight 0.25s ease-out"},onClick:I=>I.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-slate-200 dark:border-slate-700 bg-gradient-to-b from-white to-slate-50/50 dark:from-[#252526] dark:to-[#1e1e1e] shrink-0",children:[e.jsx("div",{className:"flex-1 min-w-0 mr-3",children:e.jsx("h3",{className:"font-bold text-slate-800 text-lg leading-snug break-words",children:m.title})}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx("button",{onClick:Ne,disabled:!He,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors disabled:opacity-30",title:a("knowledge.prev"),children:e.jsx(is,{size:F.md})}),e.jsxs("span",{className:"text-xs text-slate-400 tabular-nums",children:[ve+1,"/",i.length]}),e.jsx("button",{onClick:r,disabled:!Pe,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors disabled:opacity-30",title:a("knowledge.next"),children:e.jsx(rt,{size:F.md})}),e.jsx("div",{className:"w-px h-5 bg-slate-200 mx-1"}),e.jsx("button",{onClick:_,className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors text-slate-400",title:a(M?"knowledge.narrow":"knowledge.widen"),children:M?e.jsx(Gs,{size:F.md}):e.jsx(Cs,{size:F.md})}),e.jsx("button",{onClick:()=>{ce(m),N(null)},className:"p-1.5 hover:bg-red-50 rounded-lg text-red-500 transition-colors",title:a("common.delete"),children:e.jsx(ot,{size:F.md})}),e.jsx("button",{onClick:()=>N(null),className:"p-1.5 hover:bg-slate-100 rounded-lg transition-colors",children:e.jsx(Xe,{size:F.md})})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[m.rejectionReason&&e.jsxs("div",{className:"px-6 py-3 border-b border-red-200 dark:border-red-800/40 bg-red-50/80 dark:bg-red-900/15",children:[e.jsx("label",{className:"text-[10px] font-bold text-red-500 uppercase mb-1.5 block",children:a("knowledge.rejectionReason")}),e.jsx("p",{className:"text-xs text-red-600",children:m.rejectionReason})]}),e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsxs("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium ${T.bg} ${T.color} ${T.border} border`,children:[e.jsx(Q,{size:10}),l(m.lifecycle)]}),e.jsxs("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium ${ie.bg} ${ie.color} ${ie.border} border`,children:[Ct.createElement(ie.icon,{size:10}),a(ie.labelKey)]}),e.jsx("span",{className:`text-[10px] font-bold px-1.5 py-0.5 rounded uppercase flex items-center gap-1 border ${(ke==null?void 0:ke.bg)||"bg-slate-50"} ${(ke==null?void 0:ke.color)||"text-slate-400"} ${(ke==null?void 0:ke.border)||"border-slate-100"}`,children:m.category||"general"}),m.knowledgeType&&e.jsx("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded bg-purple-50 text-purple-700 border border-purple-200",children:m.knowledgeType}),m.language&&e.jsx("span",{className:"text-[10px] uppercase font-bold text-slate-500 bg-slate-50 border border-slate-200 px-1.5 py-0.5 rounded",children:m.language}),m.trigger&&e.jsx("span",{className:"text-[10px] font-mono px-1.5 py-0.5 rounded bg-amber-50 text-amber-700 border border-amber-200 font-bold",children:m.trigger})]}),e.jsxs("div",{className:"flex flex-wrap gap-x-5 gap-y-2 text-xs",children:[(()=>{const I=[];return m.scope&&I.push({icon:Pt,iconClass:"text-teal-400",label:a("knowledge.scope"),value:m.scope==="universal"?a("knowledge.scopeUniversal"):m.scope==="project-specific"?a("knowledge.scopeProject"):m.scope==="module-level"?a("knowledge.scopeModule"):m.scope}),m.complexity&&I.push({icon:lt,iconClass:"text-orange-400",label:a("knowledge.complexity"),value:m.complexity==="advanced"?a("knowledge.complexityAdvanced"):m.complexity==="intermediate"?a("knowledge.complexityIntermediate"):m.complexity==="beginner"?a("knowledge.complexityBeginner"):m.complexity}),m.source&&m.source!=="unknown"&&I.push({icon:Pt,iconClass:"text-violet-400",label:a("knowledge.source"),value:Es[m.source||""]?a(Es[m.source||""].labelKey):m.source||"-"}),m.createdAt&&I.push({icon:xt,iconClass:"text-slate-400",label:a("knowledge.createdAt"),value:Yt(m.createdAt,a)}),m.updatedAt&&I.push({icon:xt,iconClass:"text-slate-400",label:a("knowledge.updatedAt"),value:Yt(m.updatedAt,a)}),m.publishedAt&&I.push({icon:cs,iconClass:"text-emerald-400",label:a("knowledge.published"),value:Yt(m.publishedAt,a)}),I.map((V,Ce)=>{const Ae=V.icon;return e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ae,{size:11,className:`${V.iconClass} shrink-0`}),e.jsx("span",{className:"text-slate-400",children:V.label}),e.jsx("span",{className:`font-medium text-slate-600 ${V.mono?"font-mono text-[11px]":""}`,children:V.value})]},Ce)})})(),e.jsxs("div",{className:"flex items-center gap-1.5 basis-full mt-0.5",children:[e.jsx(as,{size:11,className:"text-slate-300 shrink-0"}),e.jsx("span",{className:"text-slate-400",children:"ID"}),e.jsx("code",{className:"font-mono text-[11px] text-slate-500 break-all",children:m.id})]}),m.sourceFile&&e.jsxs("div",{className:"flex items-center gap-1.5 basis-full",children:[e.jsx(wt,{size:11,className:"text-slate-300 shrink-0"}),e.jsx("span",{className:"text-slate-400",children:a("knowledge.sourceFile")}),e.jsx("code",{className:"font-mono text-[11px] text-slate-500 break-all",children:m.sourceFile})]})]})]}),m.tags&&m.tags.length>0&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100 flex flex-wrap items-center gap-1.5",children:[e.jsx(ls,{size:11,className:"text-slate-300 mr-0.5"}),m.tags.map((I,V)=>e.jsx("span",{className:"text-[9px] px-2 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100 font-medium",children:I},V))]}),m.relations&&Object.entries(m.relations).some(([,I])=>Array.isArray(I)&&I.length>0)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[e.jsx(Hs,{size:12,className:"text-purple-400"}),e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase",children:a("knowledge.relatedKnowledge")}),(()=>{const I=Object.values(m.relations).flat().length;return I>0?e.jsx("span",{className:"text-[9px] bg-purple-100 text-purple-600 px-1.5 py-0.5 rounded-full font-bold",children:I}):null})()]}),e.jsx("div",{className:"space-y-1.5",children:Object.entries(m.relations).map(([I,V])=>!Array.isArray(V)||V.length===0?null:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-[10px] font-mono text-slate-500 w-14 shrink-0 pt-0.5 uppercase",children:I}),e.jsx("div",{className:"flex flex-wrap gap-1",children:V.map((Ce,Ae)=>{const Re=Ce.target||(typeof Ce=="string"?Ce:JSON.stringify(Ce)),Be=fe.get(Re)||Re;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:Re,children:Be},Ae)})})]},I))})]}),m.stats&&Object.values(m.stats).some(I=>I>0)&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"bg-amber-50/60 dark:bg-amber-900/20 rounded-xl p-3 text-center border border-amber-100 dark:border-amber-800/40",children:[e.jsx("div",{className:"text-lg font-bold text-amber-700",children:((k=m.stats)==null?void 0:k.authority)??"—"}),e.jsx("div",{className:"text-[10px] text-amber-500 font-medium",children:a("knowledge.authorityScore")})]}),e.jsxs("div",{className:"bg-slate-50 rounded-xl p-3 text-center border border-slate-100",children:[e.jsx("div",{className:"text-lg font-bold text-slate-800",children:((b=m.stats)==null?void 0:b.guardHits)??0}),e.jsx("div",{className:"text-[10px] text-slate-400 font-medium",children:a("knowledge.guardHits")})]}),e.jsxs("div",{className:"bg-slate-50 rounded-xl p-3 text-center border border-slate-100",children:[e.jsx("div",{className:"text-lg font-bold text-slate-800",children:((B=m.stats)==null?void 0:B.adoptions)??0}),e.jsx("div",{className:"text-[10px] text-slate-400 font-medium",children:a("knowledge.adoptions")})]}),e.jsxs("div",{className:"bg-blue-50/60 dark:bg-blue-900/20 rounded-xl p-3 text-center border border-blue-100 dark:border-blue-800/40",children:[e.jsx("div",{className:"text-lg font-bold text-blue-700",children:((D=m.stats)==null?void 0:D.searchHits)??0}),e.jsx("div",{className:"text-[10px] text-blue-500 font-medium",children:a("knowledge.searchHits")})]})]}),(m.stats.views>0||m.stats.applications>0)&&e.jsxs("div",{className:"flex items-center gap-4 mt-2 text-[10px] text-slate-400",children:[e.jsxs("span",{children:[a("knowledge.statViews"),": ",m.stats.views]}),e.jsxs("span",{children:[a("knowledge.statApplications"),": ",m.stats.applications]})]})]}),ne&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(jt,{size:11,className:"text-amber-400"})," ",a("knowledge.reasoning")]}),e.jsxs("div",{className:"bg-amber-50/30 dark:bg-amber-900/15 border border-amber-100 dark:border-amber-800/40 rounded-xl p-4 space-y-2.5",children:[Ie.whyStandard&&!/^Submitted via /i.test(Ie.whyStandard)&&e.jsx("p",{className:"text-sm text-slate-700 leading-relaxed",children:Ie.whyStandard}),Ie.sources&&Ie.sources.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsxs("span",{className:"text-[10px] text-slate-400 font-bold",children:[a("knowledge.source"),":"]}),Ie.sources.map((I,V)=>e.jsx("code",{className:"text-[10px] px-2 py-0.5 bg-white dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800/40 rounded text-amber-700 dark:text-amber-400 font-mono",children:I},V))]}),Ie.confidence!=null&&Ie.confidence>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-[10px] text-slate-400 font-bold",children:[a("knowledge.confidence"),":"]}),e.jsx("div",{className:"flex-1 max-w-[160px] h-1.5 bg-slate-200 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-amber-400 rounded-full",style:{width:`${Math.round((Ie.confidence??0)*100)}%`}})}),e.jsxs("span",{className:"text-[10px] font-bold text-amber-600",children:[Math.round((Ie.confidence??0)*100),"%"]})]}),Ie.alternatives&&Ie.alternatives.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 pt-1",children:[e.jsxs("span",{className:"text-[10px] text-slate-400 font-bold",children:[a("knowledge.alternatives"),":"]}),Ie.alternatives.map((I,V)=>e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-slate-100 border border-slate-200 rounded text-slate-600",children:I},V))]})]})]}),m.quality&&m.quality.grade&&m.quality.grade!=="F"&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:a("knowledge.qualityGrade")}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("span",{className:`text-2xl font-black ${m.quality.grade==="A"?"text-emerald-600":m.quality.grade==="B"?"text-blue-600":m.quality.grade==="C"?"text-amber-600":m.quality.grade==="D"?"text-orange-600":"text-slate-400"}`,children:m.quality.grade}),e.jsxs("div",{className:"flex-1 grid grid-cols-3 gap-2 text-[10px]",children:[m.quality.completeness!=null&&m.quality.completeness>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-slate-700",children:m.quality.completeness.toFixed(2)}),e.jsx("div",{className:"text-slate-400",children:a("knowledge.qualityCompletionLabel")})]}),m.quality.adaptation!=null&&m.quality.adaptation>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-slate-700",children:m.quality.adaptation.toFixed(2)}),e.jsx("div",{className:"text-slate-400",children:a("knowledge.qualityAdaptation")})]}),m.quality.documentation!=null&&m.quality.documentation>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-bold text-slate-700",children:m.quality.documentation.toFixed(2)}),e.jsx("div",{className:"text-slate-400",children:a("knowledge.qualityDocumentation")})]})]})]})]}),m.description&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-1.5 block",children:a("knowledge.summary")}),e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:m.description})]}),((U=m.content)==null?void 0:U.markdown)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(nt,{size:11,className:"text-blue-400"})," ",a("knowledge.markdownDoc")]}),e.jsx("div",{className:"bg-blue-50/30 dark:bg-blue-900/15 border border-blue-100 dark:border-blue-800/40 rounded-xl p-4",children:e.jsx("div",{className:"markdown-body text-sm text-slate-700 leading-relaxed",children:e.jsx(gt,{content:m.content.markdown})})})]}),m.headers&&m.headers.length>0&&e.jsxs("div",{className:"px-6 py-3 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:a("knowledge.importHeaders")}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:m.headers.map((I,V)=>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:I},V))})]}),((te=m.content)==null?void 0:te.pattern)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(ht,{size:11,className:"text-emerald-500"})," ",a("knowledge.codePattern")]}),e.jsx(dt,{code:m.content.pattern,language:m.language==="objc"?"objectivec":m.language,showLineNumbers:!0})]}),(m.doClause||m.whenClause||m.dontClause||m.topicHint||m.coreCode)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(lt,{size:11,className:"text-indigo-400"})," Cursor Delivery"]}),e.jsxs("div",{className:"bg-indigo-50/30 dark:bg-indigo-900/15 border border-indigo-100 dark:border-indigo-800/40 rounded-xl p-4 space-y-1.5 text-xs",children:[m.topicHint&&e.jsxs("div",{children:[e.jsx("span",{className:"text-indigo-500 font-medium",children:"Topic:"}),e.jsx("span",{className:"text-slate-700",children:m.topicHint})]}),m.whenClause&&e.jsxs("div",{children:[e.jsx("span",{className:"text-blue-500 font-medium",children:"When:"}),e.jsx("span",{className:"text-slate-700",children:m.whenClause})]}),m.doClause&&e.jsxs("div",{children:[e.jsx("span",{className:"text-emerald-500 font-medium",children:"Do:"}),e.jsx("span",{className:"text-slate-700",children:m.doClause})]}),m.dontClause&&e.jsxs("div",{children:[e.jsx("span",{className:"text-red-500 font-medium",children:"Don't:"}),e.jsx("span",{className:"text-slate-700",children:m.dontClause})]}),m.coreCode&&e.jsxs("div",{children:[e.jsx("span",{className:"text-purple-500 font-medium",children:"Core Code:"}),e.jsx("div",{className:"mt-1",children:e.jsx(dt,{code:m.coreCode,language:m.language==="objc"?"objectivec":m.language||"text"})})]})]})]}),((de=m.content)==null?void 0:de.rationale)&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:a("knowledge.designRationale")}),e.jsx("div",{className:"bg-slate-50 border border-slate-100 rounded-xl p-4",children:e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:m.content.rationale})})]}),((me=m.content)==null?void 0:me.steps)&&m.content.steps.length>0&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:a("knowledge.implementSteps")}),e.jsx("div",{className:"space-y-2",children:m.content.steps.map((I,V)=>{if(typeof I=="string")return e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 border border-slate-100 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:V+1}),e.jsx("p",{className:"text-xs text-slate-700 leading-relaxed",children:I})]},V);const Ce=typeof I.title=="string"?I.title:"",Ae=typeof I.description=="string"?I.description:"",Re=typeof I.code=="string"?I.code:"";return e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 border border-slate-100",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:V+1}),Ce&&e.jsx("span",{className:"text-xs font-bold text-slate-700",children:Ce})]}),Ae&&e.jsx("p",{className:"text-xs text-slate-600 ml-7 leading-relaxed",children:Ae}),Re&&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:Re})]},V)})})]}),m.constraints&&(()=>{var Ce,Ae,Re,Be,Ye,J,Le,qe;const I=m.constraints,V=(((Ce=I.guards)==null?void 0:Ce.length)||0)+(((Ae=I.boundaries)==null?void 0:Ae.length)||0)+(((Re=I.preconditions)==null?void 0:Re.length)||0)+(((Be=I.sideEffects)==null?void 0:Be.length)||0);return V?e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(ut,{size:11,className:"text-amber-500"})," ",a("knowledge.constraintsLabel")," ",e.jsx("span",{className:"text-amber-500 font-mono",children:V})]}),e.jsxs("div",{className:"space-y-1.5 text-xs text-slate-600",children:[(Ye=I.guards)==null?void 0:Ye.map((ze,Ve)=>e.jsxs("div",{className:"flex gap-1.5 items-start",children:[e.jsx("span",{className:`text-xs mt-0.5 ${ze.severity==="error"?"text-red-500":"text-yellow-500"}`,children:"●"}),e.jsx("code",{className:"font-mono text-[10px] bg-slate-100 px-1.5 py-0.5 rounded",children:ze.pattern}),ze.message&&e.jsxs("span",{className:"text-[10px] text-slate-400",children:["— ",ze.message]})]},Ve)),(J=I.boundaries)==null?void 0:J.map((ze,Ve)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("span",{className:"text-orange-400",children:"●"}),ze]},Ve)),(Le=I.preconditions)==null?void 0:Le.map((ze,Ve)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("span",{className:"text-blue-400",children:"◆"}),ze]},Ve)),(qe=I.sideEffects)==null?void 0:qe.map((ze,Ve)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("span",{className:"text-pink-400",children:"⚡"}),ze]},Ve))]})]}):null})(),m.aiInsight&&e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(jt,{size:11,className:"text-cyan-400"})," ",a("knowledge.aiInsight")]}),e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:m.aiInsight})]}),(()=>{const I=Array.isArray(m.lifecycleHistory)?m.lifecycleHistory:(()=>{try{const V=typeof m.lifecycleHistory=="string"?JSON.parse(m.lifecycleHistory):null;return Array.isArray(V)?V:[]}catch{return[]}})();return I.length>0?e.jsxs("div",{className:"px-6 py-4 border-b border-slate-100",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(xt,{size:11,className:"text-slate-400"})," ",a("knowledge.lifecycleHistoryLabel")]}),e.jsx("div",{className:"space-y-1",children:I.map((V,Ce)=>{const Ae=mt[V.from]||mt.pending,Re=mt[V.to]||mt.pending;return e.jsxs("div",{className:"flex items-center gap-2 text-[10px]",children:[e.jsx("span",{className:"text-slate-400 w-20 shrink-0",children:Yt(V.at,a)}),e.jsx("span",{className:`${Ae.color}`,children:l(V.from)}),e.jsx("span",{className:"text-slate-300",children:"→"}),e.jsx("span",{className:`${Re.color} font-medium`,children:l(V.to)}),e.jsxs("span",{className:"text-slate-400 ml-auto",children:["by ",V.by]})]},Ce)})})]}):null})()]}),e.jsxs("div",{className:"shrink-0 border-t border-slate-200 dark:border-slate-700 px-5 py-3 bg-gradient-to-b from-slate-50/80 to-white dark:from-[#252526] dark:to-[#1e1e1e] flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("button",{onClick:()=>{ce(m),N(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(ot,{size:14})," ",a("common.delete")]})}),e.jsx("div",{className:"flex items-center gap-2",children:(Fn[m.lifecycle]||[]).map(I=>{const V=I.icon;return e.jsxs("button",{onClick:()=>I.needsReason?L(m,I.action):he(m,I.action),disabled:y,className:`flex items-center gap-1.5 px-4 py-2 rounded-lg text-xs font-bold border transition-colors disabled:opacity-50 ${I.bg} ${I.color} border-current/20`,children:[y?e.jsx(Fe,{size:14,className:"animate-spin"}):e.jsx(V,{size:14}),d(I.action)]},I.action)})})]})]})]})})()]})},gs={manual:{label:"manual",color:"bg-slate-100 text-slate-600",icon:Ia},"user-ai":{label:"user-ai",color:"bg-violet-100 text-violet-600",icon:Qe},"system-ai":{label:"system-ai",color:"bg-amber-100 text-amber-600",icon:ns},"external-ai":{label:"external-ai",color:"bg-cyan-100 text-cyan-600",icon:qs}},Bn=({onRefresh:t,signalSuggestionCount:s=0,onSuggestionCountChange:a})=>{const{t:l}=_e(),[d,i]=o.useState([]),[u,p]=o.useState(!0),[n,g]=o.useState(null),[f,h]=o.useState(!1),[x,c]=o.useState(!1),[j,w]=o.useState("all"),[C,E]=o.useState(!1),[S,G]=o.useState([]),[z,P]=o.useState(!1),[Z,X]=o.useState(!1),[H,q]=o.useState(null),[R,M]=o.useState(!1),[_,m]=o.useState(""),[N,y]=o.useState(!1),[W,O]=o.useState(!1),[be,we]=o.useState(!1),ye=o.useCallback(async()=>{var L;p(!0);try{const T=await se.listSkills();i(T.skills||[])}catch(T){((L=T.response)==null?void 0:L.status)!==404&&re(T.message||"",{title:l("skills.fetchFailed"),type:"error"}),i([])}finally{p(!1)}},[]);o.useEffect(()=>{ye()},[ye]);const v=async L=>{if((n==null?void 0:n.skillName)===L){g(null);return}M(!1),O(!1),h(!0);try{const T=await se.loadSkill(L);g(T)}catch{re(`"${L}" ${l("skills.loadError")}`,{title:l("skills.loadSkillFailed"),type:"error"})}finally{h(!1)}},ee=()=>{n!=null&&n.content&&(navigator.clipboard.writeText(n.content),E(!0),setTimeout(()=>E(!1),2e3))},ae=()=>{n&&(m(n.content),M(!0))},ue=()=>{M(!1),m("")},fe=async()=>{if(!(!n||!_.trim())){y(!0);try{await se.updateSkill(n.skillName,{content:_}),re(l("skills.saveSuccess"),{title:`Skill "${n.skillName}" ${l("skills.updateSuccess")}`}),M(!1);const L=await se.loadSkill(n.skillName);g(L)}catch(L){re(L.message||"",{title:l("skills.updateFailed"),type:"error"})}finally{y(!1)}}},he=async()=>{if(n){we(!0);try{await se.deleteSkill(n.skillName),re(l("skills.deleteSuccess"),{title:`Skill "${n.skillName}" ${l("skills.deleteSuccess")}`}),g(null),O(!1),M(!1),ye(),t==null||t()}catch(L){re(L.message||"",{title:l("skills.deleteFailed"),type:"error"})}finally{we(!1)}}},ce=async()=>{P(!0),X(!0);try{const[L,T]=await Promise.allSettled([se.suggestSkills(),se.getSignalStatus()]),Q=L.status==="fulfilled"?L.value.suggestions||[]:[],ie=T.status==="fulfilled"?T.value.suggestions||[]:[],ke=new Map;for(const Ie of Q)ke.set(Ie.name,Ie);for(const Ie of ie)ke.set(Ie.name,{...ke.get(Ie.name),...Ie});const Ue=[...ke.values()];G(Ue),a==null||a(Ue.length)}catch(L){re(L.message||"",{title:l("skills.aiRecommendFailed"),type:"error"}),G([]),a==null||a(0)}finally{P(!1)}};o.useEffect(()=>{s>0&&S.length===0&&!Z&&ce()},[]);const je=async L=>{q(L.name);try{const T=L.description||L.rationale||L.name,Q=`${l("skillsView.aiPromptPrefix")}
119
+
120
+ 名称:${L.name}
121
+ 描述:${T}
122
+ 推荐原因:${L.rationale}
123
+
124
+ 请直接生成 Skill 正文内容(Markdown 格式),不需要 frontmatter,不需要输出 JSON 元数据。内容应该详细、实用,包含具体的操作指南和示例。`;let ke=(await se.aiGenerateSkill(Q)).reply||L.body||`# ${T}
125
+
126
+ ${L.rationale||""}`;ke=ke.replace(/^\s*\{["']name["']\s*:.*\}\s*\n?/,"").trim(),await se.createSkill({name:L.name,description:T,content:ke,createdBy:"user-ai"}),re(l("skills.createAddedToKB"),{title:`Skill "${L.name}" ${l("skills.createSuccess")}`}),G(Ue=>{const Ie=Ue.filter(ne=>ne.name!==L.name);return a==null||a(Ie.length),Ie}),ye()}catch(T){re(T.message||"",{title:l("skills.createFailed"),type:"error"})}finally{q(null)}},$=d.filter(L=>j==="all"?!0:L.source===j).sort((L,T)=>L.source===T.source?L.name.localeCompare(T.name):L.source==="project"?-1:1),K=d.filter(L=>L.source==="builtin").length,xe=d.filter(L=>L.source==="project").length;return e.jsxs("div",{className:"h-full flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 bg-violet-100 rounded-xl flex items-center justify-center",children:e.jsx(tt,{size:20,className:"text-violet-600"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-slate-800",children:l("skills.title")}),e.jsx("p",{className:"text-sm text-slate-500",children:l("skills.subtitle")})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:ce,disabled:z,className:"flex items-center gap-2 px-3 py-2 border border-amber-300 text-amber-700 bg-amber-50 rounded-lg hover:bg-amber-100 transition-colors text-sm font-medium disabled:opacity-50",title:l("skills.aiRecommendTooltip"),children:[z?e.jsx(Fe,{size:14,className:"animate-spin"}):e.jsx(jt,{size:14}),l("skills.aiRecommend")]}),e.jsx("button",{onClick:ye,className:"p-2 rounded-lg text-slate-400 hover:text-slate-600 hover:bg-slate-100 transition-colors",title:l("common.refresh"),children:e.jsx(yt,{size:16})}),e.jsxs("button",{onClick:()=>c(!0),className:"flex items-center gap-2 px-4 py-2 bg-violet-600 text-white rounded-lg hover:bg-violet-700 transition-colors text-sm font-medium",children:[e.jsx(Qe,{size:14}),l("skills.addSkill")]})]})]}),e.jsx("div",{className:"flex items-center gap-1 mb-4 p-1 bg-slate-100 rounded-lg w-fit",children:[{key:"all",label:l("common.all"),count:d.length},{key:"project",label:l("skills.filterProject"),count:xe,icon:wt},{key:"builtin",label:l("skills.filterBuiltin"),count:K,icon:Ll}].map(L=>e.jsxs("button",{onClick:()=>w(L.key),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${j===L.key?"bg-white text-violet-700 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:[L.icon&&e.jsx(L.icon,{size:12}),L.label,e.jsx("span",{className:`ml-0.5 px-1.5 py-0.5 rounded-full text-[10px] ${j===L.key?"bg-violet-100 text-violet-600":"bg-slate-200 text-slate-500"}`,children:L.count})]},L.key))}),Z&&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(jt,{size:16,className:"text-amber-600"}),e.jsx("span",{className:"text-sm font-semibold text-amber-800",children:l("skills.aiRecommendDesc")}),S.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:S.length})]}),e.jsx("button",{onClick:()=>X(!1),className:"p-1 text-amber-400 hover:text-amber-600",children:e.jsx(Xe,{size:14})})]}),z?e.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-xs py-2",children:[e.jsx(Fe,{size:14,className:"animate-spin"}),l("skills.aiRecommending")]}):S.length===0?e.jsx("p",{className:"text-xs text-amber-600/70",children:l("skills.noRecommendations")}):e.jsx("div",{className:"space-y-2",children:S.map(L=>e.jsxs("div",{className:"flex items-start gap-3 p-3 bg-white 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-slate-800",children:L.name}),e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[9px] font-bold uppercase ${L.priority==="high"?"bg-red-100 text-red-600":L.priority==="medium"?"bg-amber-100 text-amber-600":"bg-slate-100 text-slate-500"}`,children:L.priority}),e.jsx("span",{className:"text-[10px] text-slate-400",children:L.source})]}),e.jsx("p",{className:"text-xs text-slate-600 mb-1",children:L.description}),e.jsx("p",{className:"text-[11px] text-slate-400 line-clamp-2",children:L.rationale})]}),e.jsx("button",{onClick:()=>je(L),disabled:H===L.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:H===L.name?e.jsxs(e.Fragment,{children:[e.jsx(Fe,{size:12,className:"animate-spin"})," ",l("skills.creating")]}):e.jsxs(e.Fragment,{children:[e.jsx(et,{size:12})," ",l("skills.acceptRecommend")]})})]},L.name))})]}),e.jsxs("div",{className:"flex-1 flex gap-6 min-h-0 overflow-hidden",children:[e.jsx("div",{className:"w-1/2 overflow-y-auto pr-2 space-y-2",children:u?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx(Fe,{size:24,className:"animate-spin text-violet-400"})}):$.length===0?e.jsxs("div",{className:"text-center py-20 text-slate-400",children:[e.jsx(tt,{size:40,className:"mx-auto mb-3 opacity-40"}),e.jsx("p",{children:l("skills.noResults")})]}):$.map(L=>e.jsx("button",{onClick:()=>v(L.name),className:`w-full text-left p-4 rounded-xl border transition-all ${(n==null?void 0:n.skillName)===L.name?"border-violet-300 bg-violet-50 shadow-sm":"border-slate-200 bg-white hover:border-slate-300 hover:shadow-sm"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`mt-0.5 shrink-0 ${(n==null?void 0:n.skillName)===L.name?"text-violet-500":"text-slate-400"}`,children:(n==null?void 0:n.skillName)===L.name?e.jsx(Gt,{size:16}):e.jsx(rt,{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-slate-800",children:L.name}),e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider ${L.source==="builtin"?"bg-blue-100 text-blue-600":"bg-emerald-100 text-emerald-600"}`,children:L.source==="builtin"?l("skills.filterBuiltin"):l("skills.filterProject")}),L.createdBy&&gs[L.createdBy]&&(()=>{const T=gs[L.createdBy],Q=T.icon;return e.jsxs("span",{className:`flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[10px] font-medium ${T.color}`,children:[e.jsx(Q,{size:10}),T.label]})})()]}),e.jsx("p",{className:"text-xs text-slate-500 line-clamp-2",children:L.summary}),L.useCase&&e.jsxs("p",{className:"text-[11px] text-violet-500 mt-1 italic",children:[l("skills.useCase"),":",L.useCase]})]})]})},L.name))}),e.jsx("div",{className:"w-1/2 overflow-y-auto border border-slate-200 rounded-xl bg-white",children:f?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(Fe,{size:24,className:"animate-spin text-violet-400"})}):n?e.jsxs("div",{className:"h-full flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nt,{size:16,className:"text-violet-500"}),e.jsx("span",{className:"font-mono font-semibold text-sm",children:n.skillName}),e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-bold uppercase ${n.source==="builtin"?"bg-blue-100 text-blue-600":"bg-emerald-100 text-emerald-600"}`,children:n.source==="builtin"?l("skills.filterBuiltin"):l("skills.filterProject")}),n.createdBy&&gs[n.createdBy]&&(()=>{const L=gs[n.createdBy],T=L.icon;return e.jsxs("span",{className:`flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[10px] font-medium ${L.color}`,children:[e.jsx(T,{size:10}),l(`skills.createdBy.${n.createdBy}`)]})})()]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-[10px] text-slate-400",children:[n.charCount," ",l("skills.chars")]}),e.jsx("button",{onClick:ee,className:"p-1.5 rounded-md hover:bg-slate-100 transition-colors text-slate-400 hover:text-slate-600",title:l("common.copy"),children:C?e.jsx(kt,{size:14,className:"text-emerald-500"}):e.jsx(qt,{size:14})}),n.source==="project"&&!R&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:ae,className:"p-1.5 rounded-md hover:bg-blue-50 transition-colors text-slate-400 hover:text-blue-600",title:l("common.edit"),children:e.jsx(Ms,{size:14})}),e.jsx("button",{onClick:()=>O(!0),className:"p-1.5 rounded-md hover:bg-red-50 transition-colors text-slate-400 hover:text-red-500",title:l("common.delete"),children:e.jsx(ot,{size:14})})]}),R&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:fe,disabled:N,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:[N?e.jsx(Fe,{size:12,className:"animate-spin"}):e.jsx(Ss,{size:12}),l("common.save")]}),e.jsx("button",{onClick:ue,className:"px-2.5 py-1 border border-slate-200 text-slate-500 rounded-md hover:bg-slate-50 transition-colors text-xs",children:l("common.cancel")})]})]})]}),n.relatedSkills.length>0&&e.jsxs("div",{className:"px-4 py-2 border-b border-slate-50 flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"text-[10px] text-slate-400 uppercase font-bold",children:[l("skills.related"),":"]}),n.relatedSkills.map(L=>e.jsx("button",{onClick:()=>v(L),className:"text-[11px] text-violet-600 hover:text-violet-800 bg-violet-50 px-2 py-0.5 rounded-full transition-colors",children:L},L))]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 relative",children:[R?e.jsx("textarea",{value:_,onChange:L=>m(L.target.value),className:"w-full h-full min-h-[300px] text-xs text-slate-700 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-slate-700 font-mono leading-relaxed",children:n.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-white border border-red-200 rounded-xl shadow-lg p-6 max-w-sm text-center",children:[e.jsx(ot,{size:32,className:"mx-auto mb-3 text-red-400"}),e.jsx("h3",{className:"font-semibold text-slate-800 mb-2",children:l("skills.deleteConfirm")}),e.jsx("p",{className:"text-sm text-slate-500 mb-4",children:l("skills.deleteSkillConfirmMsg",{name:n.skillName})}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsx("button",{onClick:()=>O(!1),className:"px-4 py-2 border border-slate-200 text-slate-600 rounded-lg hover:bg-slate-50 text-sm",children:l("common.cancel")}),e.jsxs("button",{onClick:he,disabled:be,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:[be?e.jsx(Fe,{size:14,className:"animate-spin"}):e.jsx(ot,{size:14}),l("skills.confirmDelete")]})]})]})})]})]}):e.jsx("div",{className:"flex items-center justify-center h-full text-slate-400",children:e.jsxs("div",{className:"text-center",children:[e.jsx(tt,{size:40,className:"mx-auto mb-3 opacity-30"}),e.jsx("p",{className:"text-sm",children:l("skills.selectToView")})]})})})]}),x&&e.jsx(Gn,{onClose:()=>c(!1),onCreated:()=>{c(!1),ye(),t==null||t()}})]})},Gn=({onClose:t,onCreated:s})=>{const{t:a}=_e(),[l,d]=o.useState("ai"),[i,u]=o.useState(""),[p,n]=o.useState(!1),[g,f]=o.useState(""),[h,x]=o.useState(""),[c,j]=o.useState(""),[w,C]=o.useState(!1),[E,S]=o.useState(""),[G,z]=o.useState(!1),P=async()=>{if(i.trim()){n(!0),S("");try{const H=(await se.aiGenerateSkill(i)).reply||"";let q="",R="",M=H;const _=/```(?:json)?\s*\n?\s*(\{[^}]*"name"[^}]*\})\s*\n?\s*```/i,m=H.match(_);if(m)try{const N=JSON.parse(m[1]);q=N.name||"",R=N.description||"",M=H.replace(m[0],"").trim()}catch{}if(!q){const N=H.split(`
127
+ `);for(let y=0;y<Math.min(N.length,5);y++){const W=N[y].trim();if(!(!W||W.startsWith("```"))&&W.startsWith("{")&&W.endsWith("}"))try{const O=JSON.parse(W);if(O.name){q=O.name,R=O.description||"";let be=y+1;for(;be<N.length&&!N[be].trim();)be++;M=N.slice(be).join(`
128
+ `).trim();break}}catch{}}}if(!q){const N=/"name"\s*:\s*"([a-z][a-z0-9-]{1,62}[a-z0-9])"/,y=/"description"\s*:\s*"([^"]+)"/,W=H.match(N),O=H.match(y);W&&(q=W[1]),O&&(R=O[1])}M=M.replace(/```(?:json)?\s*\n?\s*\{[^}]*"name"[^}]*\}\s*\n?\s*```/gi,"").replace(/^\s*\{[^}]*"name"[^}]*\}\s*$/gm,"").trim(),q&&f(q),R&&x(R),j(M||H.trim()),z(!0),d("manual"),re(a("skills.checkGenerated"),{title:a("skills.aiGenerated")})}catch(X){S(a("skills.aiGenFailed")+": "+(X.message||""))}finally{n(!1)}}},Z=async()=>{var X,H,q;if(!g.trim()||!h.trim()||!c.trim()){S(a("skills.fillRequired"));return}C(!0),S("");try{await se.createSkill({name:g.trim(),description:h.trim(),content:c.trim(),createdBy:G?"user-ai":"manual"}),re(a("skills.savedToKB"),{title:`Skill "${g}" ${a("skills.createSuccess")}`}),s()}catch(R){const M=((q=(H=(X=R.response)==null?void 0:X.data)==null?void 0:H.error)==null?void 0:q.message)||R.message||"";S(a("skills.createFailed")+": "+M)}finally{C(!1)}};return e.jsxs(Ze,{className:"z-40 flex items-center justify-center",children:[e.jsx(Ze.Backdrop,{className:"bg-black/40 backdrop-blur-sm"}),e.jsxs("div",{className:"relative bg-white 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-slate-100",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(Qe,{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-slate-100 transition-colors",children:e.jsx(Xe,{size:18,className:"text-slate-400"})})]}),e.jsx("div",{className:"px-6 pt-4",children:e.jsxs("div",{className:"inline-flex items-center gap-1 p-1 bg-slate-100 rounded-lg",children:[e.jsxs("button",{onClick:()=>d("ai"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${l==="ai"?"bg-white text-violet-700 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:[e.jsx(Qe,{size:12}),a("skills.aiGenMode")]}),e.jsxs("button",{onClick:()=>d("manual"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${l==="manual"?"bg-white text-violet-700 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:[e.jsx(nt,{size:12}),a("skills.manualMode")]})]})}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-4 space-y-4",children:[l==="ai"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-slate-700 mb-1.5",children:a("skills.describeSkill")}),e.jsx("div",{className:"relative",children:e.jsx("textarea",{value:i,onChange:X=>u(X.target.value),placeholder:a("skillsView.placeholderDesc"),className:"w-full h-32 px-4 py-3 border border-slate-200 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:P,disabled:p||!i.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(Fe,{size:16,className:"animate-spin"}),a("skills.aiGeneratingContent")]}):e.jsxs(e.Fragment,{children:[e.jsx(Bs,{size:16}),a("skills.generateSkill")]})})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-slate-700 mb-1.5",children:[a("skills.skillName")," ",e.jsx("span",{className:"text-slate-400 text-xs",children:"(kebab-case)"})]}),e.jsx("input",{type:"text",value:g,onChange:X=>f(X.target.value),placeholder:"my-custom-skill",className:"w-full px-3 py-2 border border-slate-200 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-slate-700 mb-1.5",children:a("skills.skillDescription")}),e.jsx("input",{type:"text",value:h,onChange:X=>x(X.target.value),placeholder:a("skillsView.placeholderName"),className:"w-full px-3 py-2 border border-slate-200 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-slate-700 mb-1.5",children:[a("skills.skillContent")," ",e.jsx("span",{className:"text-slate-400 text-xs",children:"(Markdown)"})]}),e.jsx("textarea",{value:c,onChange:X=>j(X.target.value),placeholder:a("skillsView.placeholderContent"),className:"w-full h-64 px-4 py-3 border border-slate-200 rounded-xl text-sm font-mono resize-none focus:outline-none focus:ring-2 focus:ring-violet-300 focus:border-violet-400 leading-relaxed"})]})]}),E&&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(Ot,{size:16,className:"shrink-0 mt-0.5"}),e.jsx("span",{children:E})]})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-slate-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:t,className:"px-4 py-2 text-sm text-slate-600 hover:text-slate-800 transition-colors",children:a("common.cancel")}),l==="manual"&&e.jsx("button",{onClick:Z,disabled:w||!g.trim()||!h.trim()||!c.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:w?e.jsxs(e.Fragment,{children:[e.jsx(Fe,{size:14,className:"animate-spin"}),a("common.saving")]}):e.jsxs(e.Fragment,{children:[e.jsx(Nt,{size:14}),a("skills.addSkill")]})})]})]})]})},ja=["objc-deep-scan","category-scan","project-profile","code-standard","architecture","code-pattern","event-and-data-flow","best-practice","agent-guidelines"],Hn={"code-standard":e.jsx(tt,{className:"w-5 h-5"}),"code-pattern":e.jsx(Ht,{className:"w-5 h-5"}),architecture:e.jsx(lt,{className:"w-5 h-5"}),"best-practice":e.jsx(Qe,{className:"w-5 h-5"}),"event-and-data-flow":e.jsx(et,{className:"w-5 h-5"}),"project-profile":e.jsx(Ea,{className:"w-5 h-5"}),"agent-guidelines":e.jsx(qs,{className:"w-5 h-5"})};function qn(t){return Hn[t]||e.jsx(Ht,{className:"w-5 h-5"})}const On=({task:t})=>{const{t:s}=_e(),{status:a,meta:l}=t,d={skeleton:"bg-slate-50 border-slate-200",filling:"bg-blue-50 border-blue-300",completed:"bg-emerald-50 border-emerald-300",failed:"bg-red-50 border-red-300"},i={skeleton:e.jsxs("span",{className:"flex items-center gap-1 text-xs text-slate-400",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-slate-300"}),s("bootstrap.statusLabels.skeleton")]}),filling:e.jsxs("span",{className:"flex items-center gap-1 text-xs text-blue-600",children:[e.jsx(Fe,{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(kt,{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(Xe,{className:"w-3 h-3"}),s("bootstrap.statusLabels.failed")]})};return e.jsxs("div",{className:`relative rounded-xl border p-4 transition-all duration-300 ${d[a]||d.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-slate-200/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-slate-100 text-slate-400"}`,children:qn(t.id)}),e.jsxs("div",{children:[e.jsx("h3",{className:`font-medium text-sm ${a==="skeleton"?"text-slate-400":"text-slate-800"}`,children:(()=>{const u=`bootstrap.pipelineLabels.${l.dimId}`,p=s(u);return p!==u?p:l.label})()}),e.jsxs("p",{className:"text-xs text-slate-500 mt-0.5",children:[l.skillWorthy?"Skill":"Candidate",t.result&&a==="completed"&&e.jsx("span",{className:"ml-2 text-emerald-600",children:(()=>{const u=t.result,p=u.sourceCount??0,n=u.extracted??0;return u.type==="empty"?s("bootstrap.noMatch"):u.type==="skill"?u.empty?s("bootstrap.noMatch"):n>0?s("bootstrap.featuresAndCandidates",{sourceCount:p,extracted:n}):s("bootstrap.featuresOnly",{sourceCount:p}):n>0?s("bootstrap.candidatesOnly",{extracted:n}):s("bootstrap.noMatch")})()}),t.error&&a==="failed"&&e.jsx("span",{className:"ml-2 text-red-500 truncate max-w-[200px] inline-block align-bottom",children:t.error})]})]})]}),e.jsx("div",{className:"flex-shrink-0",children:i[a]})]})]})},Kn=[{key:"round1",labelKey:"bootstrap.reviewRounds.round1Label",descKey:"bootstrap.reviewRounds.round1Desc",icon:e.jsx(za,{className:"w-4 h-4"})},{key:"round2",labelKey:"bootstrap.reviewRounds.round2Label",descKey:"bootstrap.reviewRounds.round2Desc",icon:e.jsx(fs,{className:"w-4 h-4"})},{key:"round3",labelKey:"bootstrap.reviewRounds.round3Label",descKey:"bootstrap.reviewRounds.round3Desc",icon:e.jsx(Ml,{className:"w-4 h-4"})}],Un=({review:t})=>{const{t:s}=_e();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(rs,{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:Kn.map(({key:a,labelKey:l,descKey:d,icon:i})=>{const u=t[a],p=u.status==="running",n=u.status==="completed",g=u.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":n?"border-emerald-300 bg-emerald-50/60":"border-slate-200 bg-white/40"}`,children:[e.jsx("div",{className:`flex-shrink-0 p-1.5 rounded-md ${p?"bg-purple-200 text-purple-700":n?"bg-emerald-100 text-emerald-600":"bg-slate-100 text-slate-400"}`,children:i}),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-slate-400":"text-slate-800"}`,children:s(l)}),e.jsx("span",{className:"text-xs text-slate-400",children:s(d)})]}),a==="round1"&&n&&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"&&n&&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"&&n&&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(Fe,{className:"w-4 h-4 text-purple-500 animate-spin"}),n&&e.jsx(kt,{className:"w-4 h-4 text-emerald-500"})]})]},a)})})]})};function va(t){if(t<0)return"--";const s=Math.floor(t/1e3),a=Math.floor(s/60),l=s%60;return a===0?`${l}s`:`${a}m ${l.toString().padStart(2,"0")}s`}const Wn=({session:t,isAllDone:s,reviewState:a,onDismiss:l})=>{const{t:d}=_e(),i=o.useRef(!1),[u,p]=o.useState(Date.now());if(o.useEffect(()=>{if(!t||t.status!=="running")return;const w=setInterval(()=>p(Date.now()),1e3);return()=>clearInterval(w)},[t==null?void 0:t.status]),o.useEffect(()=>{if(s&&t&&!i.current){i.current=!0;const w=t.failed>0?d("bootstrap.notifyPartial",{completed:t.completed,total:t.total,failed:t.failed}):d("bootstrap.notifySuccess",{completed:t.completed});re(w,{title:d("bootstrap.coldStartComplete"),type:t.failed>0?"error":"success"})}},[s,t]),o.useEffect(()=>{t||(i.current=!1)},[t==null?void 0:t.id]),!t)return null;const n=t.startedAt?u-t.startedAt:t.elapsedMs??0,g=t.completed+t.failed,f=t.total-g,h=t.elapsedMs??0,x=g>0&&h>0?Math.round(h/g*f):-1,c=t.totalToolCalls??0,j=t.status==="completed"?d("bootstrap.allCompleted"):t.status==="completed_with_errors"?d("bootstrap.completedWithErrors"):null;return e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-200 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-slate-800",children:d("bootstrap.title")}),j&&e.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:j})]}),s&&l&&e.jsx("button",{onClick:l,className:"text-sm px-3 py-1.5 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-600 transition-colors",children:d("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-slate-600",children:[e.jsx(xt,{size:14,className:"text-slate-400"}),e.jsxs("span",{children:[d("bootstrap.elapsed")," ",e.jsx("span",{className:"font-medium text-slate-800",children:va(n)})]})]}),t.status==="running"&&f>0&&x>0&&e.jsxs("div",{className:"flex items-center gap-1.5 text-slate-600",children:[e.jsx(xt,{size:14,className:"text-blue-400"}),e.jsxs("span",{children:[d("bootstrap.estimatedRemaining")," ",e.jsx("span",{className:"font-medium text-blue-600",children:va(x)})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-slate-600",children:[e.jsx($a,{size:14,className:"text-slate-400"}),e.jsxs("span",{children:[d("bootstrap.toolCalls")," ",e.jsx("span",{className:"font-medium text-slate-800",children:c})]})]}),e.jsx("div",{className:"text-slate-400 text-xs",children:d("bootstrap.dimensions",{done:g,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((w,C)=>{var G,z;const E=ja.indexOf(((G=w.meta)==null?void 0:G.dimId)??w.id),S=ja.indexOf(((z=C.meta)==null?void 0:z.dimId)??C.id);return(E===-1?999:E)-(S===-1?999:S)}).map(w=>e.jsx(On,{task:w},w.id))}),a&&a.activeRound>0&&e.jsx(Un,{review:a})]})},bs={index:{icon:tt,color:"text-blue-600",label:"overview"},architecture:{icon:lt,color:"text-violet-600",label:"architecture"},"getting-started":{icon:ht,color:"text-emerald-600",label:"getting-started"},protocols:{icon:Qe,color:"text-amber-600",label:"protocols"},components:{icon:ht,color:"text-emerald-600",label:"components"},patterns:{icon:Qe,color:"text-amber-600",label:"patterns"},module:{icon:wt,color:"text-cyan-600",label:"module"},document:{icon:nt,color:"text-orange-600",label:"document"},_index:{icon:as,color:"text-slate-500",label:"index"}};function Vn(t){var a;const s=((a=t.split("/").pop())==null?void 0:a.replace(".md",""))||"";return s==="_index"?bs._index:t.startsWith("modules/")?bs.module:t.startsWith("documents/")?bs.document:bs[s]||{icon:nt,color:"text-slate-500",label:"doc"}}const Jn={"cursor-devdocs":{label:"Cursor Docs",color:"text-orange-700",bg:"bg-orange-50 border-orange-200"}},Yn={modules:"modules",documents:"documents"};function Za(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`}function Qn(t){if(!t)return"";const s=new Date(t);if(isNaN(s.getTime()))return"";const l=Date.now()-s.getTime();return l<6e4?"just now":l<36e5?`${Math.floor(l/6e4)} min ago`:l<864e5?`${Math.floor(l/36e5)} hr ago`:l<6048e5?`${Math.floor(l/864e5)} d ago`:s.toLocaleDateString("zh-CN")}const Xn=({task:t,wiki:s})=>{const{t:a}=_e();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(Ot,{size:F.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!=null&&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(Ot,{size:F.md,className:"text-amber-600"})}),e.jsx("span",{className:"text-sm text-amber-700",children:a("wiki.outOfDateHint")})]}):null};function Zn(t,s){const a=[],l=new Map((s==null?void 0:s.map(g=>[g.path,g]))||[]),d=[],i=new Map;for(const g of t){const f=g.path.split("/"),h=l.get(g.path);if(f.length===1)d.push({name:f[0],path:g.path,isDir:!1,file:g,metaInfo:h});else{const x=f[0];i.has(x)||i.set(x,[]),i.get(x).push({name:f.slice(1).join("/"),path:g.path,isDir:!1,file:g,metaInfo:h})}}const u=["index.md","architecture.md","getting-started.md","patterns.md","protocols.md","components.md"];d.sort((g,f)=>{const h=u.indexOf(g.name),x=u.indexOf(f.name);return h!==-1&&x!==-1?h-x:h!==-1?-1:x!==-1?1:g.name.localeCompare(f.name)}),a.push(...d);const p=["modules","patterns","documents"],n=[...i.entries()].sort(([g],[f])=>{const h=p.indexOf(g),x=p.indexOf(f);return h!==-1&&x!==-1?h-x:h!==-1?-1:x!==-1?1:g.localeCompare(f)});for(const[g,f]of n){const h=f.filter(x=>!x.name.startsWith("_index")).sort((x,c)=>x.name.localeCompare(c.name));a.push({name:g,path:g,isDir:!0,children:h})}return a}const eo=({tree:t,selectedFile:s,onSelect:a,searchQuery:l})=>{const[d,i]=o.useState(new Set(["modules","documents"])),u=g=>{i(f=>{const h=new Set(f);return h.has(g)?h.delete(g):h.add(g),h})},n=(g=>{if(!l)return g;const f=l.toLowerCase();return g.filter(h=>{var x;return h.isDir?(x=h.children)==null?void 0:x.some(c=>c.name.toLowerCase().includes(f)||c.path.toLowerCase().includes(f)):h.name.toLowerCase().includes(f)||h.path.toLowerCase().includes(f)})})(t);return e.jsx("div",{className:"space-y-0.5",children:n.map(g=>{var f;if(g.isDir){const h=d.has(g.path),x=l.toLowerCase(),c=l?(f=g.children)==null?void 0:f.filter(j=>j.name.toLowerCase().includes(x)||j.path.toLowerCase().includes(x)):g.children;return e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>u(g.path),className:"w-full flex items-center gap-2 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 rounded-lg transition-colors",children:[h?e.jsx(Gt,{size:14,className:"text-slate-400 flex-shrink-0"}):e.jsx(rt,{size:14,className:"text-slate-400 flex-shrink-0"}),e.jsx(wt,{size:14,className:"text-amber-500 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:Yn[g.name]||g.name}),e.jsx("span",{className:"ml-auto text-xs text-slate-400",children:(c==null?void 0:c.length)||0})]}),h&&c&&e.jsx("div",{className:"ml-3",children:c.map(j=>e.jsx(Na,{node:j,isActive:s===j.path,onSelect:a},j.path))})]},g.path)}return e.jsx(Na,{node:g,isActive:s===g.path,onSelect:a},g.path)})})},Na=({node:t,isActive:s,onSelect:a})=>{var p,n;const l=Vn(t.path),d=l.icon,i=(p=t.metaInfo)==null?void 0:p.polished,u=(n=t.metaInfo)==null?void 0:n.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-slate-600 hover:bg-slate-50"}`,children:[e.jsx(d,{size:14,className:`flex-shrink-0 ${s?"text-blue-500":l.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:[i&&e.jsx("span",{title:"AI Enhanced",children:e.jsx(Qe,{size:10,className:"text-violet-400"})}),u&&e.jsx("span",{title:`Source: ${u}`,children:e.jsx(zl,{size:10,className:"text-orange-400"})})]})]})},to=({filePath:t,content:s,loading:a,meta:l,onBack:d})=>{var x;const{t:i}=_e(),[u,p]=o.useState(!1),n=(x=l==null?void 0:l.files)==null?void 0:x.find(c=>c.path===t),g=()=>{navigator.clipboard.writeText(s),p(!0),setTimeout(()=>p(!1),2e3)},f=t.split("/"),h=f.map((c,j)=>({label:j===f.length-1?c.replace(".md",""):c,isLast:j===f.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-slate-50 border-b border-slate-200 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:d,className:"p-1.5 hover:bg-slate-200 rounded-lg transition-colors lg:hidden",title:i("wiki.backToList"),children:e.jsx(Fl,{size:F.md})}),e.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[e.jsx(tt,{size:14,className:"text-slate-400"}),e.jsx("span",{className:"text-slate-400",children:"wiki"}),h.map((c,j)=>e.jsxs(Ct.Fragment,{children:[e.jsx(rt,{size:12,className:"text-slate-300"}),e.jsx("span",{className:c.isLast?"font-medium text-slate-700":"text-slate-400",children:c.label})]},j))]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[(n==null?void 0:n.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(Qe,{size:10}),i("wiki.aiBadge")]}),(n==null?void 0:n.source)&&(()=>{const c=Jn[n.source];return e.jsx("span",{className:`flex items-center gap-1 text-xs border px-2 py-0.5 rounded-full ${(c==null?void 0:c.bg)||"bg-slate-50 border-slate-200"} ${(c==null?void 0:c.color)||"text-slate-600"}`,children:(c==null?void 0:c.label)||n.source})})(),e.jsxs("button",{onClick:g,className:"flex items-center gap-1 px-2.5 py-1 text-xs text-slate-500 hover:text-slate-700 hover:bg-slate-100 rounded-md transition-colors",children:[u?e.jsx(kt,{size:12,className:"text-emerald-500"}):e.jsx(qt,{size:12}),i(u?"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(Fe,{size:F.xl,className:"text-blue-500 animate-spin"})}):e.jsx("div",{className:"px-8 py-6 max-w-4xl mx-auto",children:e.jsx(gt,{content:s,className:"wiki-reader"})})})]})},so=()=>{const{t}=_e();return e.jsxs("div",{className:"h-72 flex flex-col items-center justify-center bg-white rounded-2xl border border-dashed border-slate-200 text-slate-400",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-slate-50 flex items-center justify-center mb-4",children:e.jsx(tt,{size:32,className:"text-slate-300"})}),e.jsx("p",{className:"text-sm font-medium text-slate-500",children:t("wiki.emptyTitle")}),e.jsx("p",{className:"mt-2 text-xs max-w-sm text-center leading-relaxed text-slate-400",children:t("wiki.emptyDesc")}),e.jsx("p",{className:"mt-3 text-[11px] text-slate-400",children:t("wiki.emptyHint")})]})},ao=({meta:t,onSelectFile:s,isGenerating:a,progress:l,message:d})=>{var g;const{t:i}=_e(),u=[{path:"index.md",label:i("wiki.quickOverview"),desc:i("wiki.quickOverviewDesc"),icon:tt,color:"bg-blue-50 text-blue-600 border-blue-200"},{path:"architecture.md",label:i("wiki.quickArch"),desc:i("wiki.quickArchDesc"),icon:lt,color:"bg-violet-50 text-violet-600 border-violet-200"},{path:"getting-started.md",label:i("wiki.quickStart"),desc:i("wiki.quickStartDesc"),icon:ht,color:"bg-emerald-50 text-emerald-600 border-emerald-200"},{path:"protocols.md",label:i("wiki.quickProtocols"),desc:i("wiki.quickProtocolsDesc"),icon:Qe,color:"bg-amber-50 text-amber-600 border-amber-200"}],p=new Set(((g=t==null?void 0:t.files)==null?void 0:g.map(f=>f.path||f.name))??[]),n=u.filter(f=>p.size===0||p.has(f.path));return e.jsxs("div",{className:"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(qs,{size:36,className:"text-blue-500 animate-pulse"})})]}),e.jsx("h3",{className:"text-lg font-semibold text-slate-700 mb-1",children:i("wiki.wikiGenerating")}),e.jsx("p",{className:"text-sm text-slate-500 max-w-md text-center leading-relaxed",children:d||i("wiki.generating")}),typeof l=="number"&&e.jsxs("div",{className:"mt-4 w-48",children:[e.jsx("div",{className:"w-full bg-slate-100 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(l,3)}%`}})}),e.jsxs("p",{className:"text-xs text-center text-blue-500 mt-1.5 font-mono",children:[l,"%"]})]})]}),!a&&e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"w-12 h-12 bg-slate-100 rounded-xl flex items-center justify-center mx-auto mb-3",children:e.jsx(nt,{size:24,className:"text-slate-400"})}),e.jsx("h3",{className:"text-lg font-semibold text-slate-700",children:i("wiki.selectFile")}),e.jsx("p",{className:"text-sm text-slate-500 mt-1",children:i("wiki.selectPlaceholder")})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 max-w-lg mx-auto",children:n.map(f=>{const h=f.icon;return e.jsxs("button",{onClick:()=>s(f.path),className:`text-left p-4 rounded-xl border ${f.color} hover:shadow-sm transition-all group`,children:[e.jsx(h,{size:20,className:"mb-2 opacity-70 group-hover:opacity-100"}),e.jsx("div",{className:"font-medium text-sm",children:f.label}),e.jsx("div",{className:"text-xs opacity-60 mt-0.5",children:f.desc})]},f.path)})}),t&&e.jsxs("div",{className:"mt-8 text-center text-xs text-slate-400",children:[t.generatedAt&&`${i("wiki.lastGenerated")}: ${new Date(t.generatedAt).toLocaleString()}`,t.duration!=null&&` · ${i("wiki.duration")} ${Za(t.duration)}`,t.version&&` · v${t.version}`]})]})},lo=()=>{const{t}=_e(),[s,a]=o.useState({task:{status:"idle"}}),[l,d]=o.useState([]),[i,u]=o.useState(!1),[p,n]=o.useState(null),[g,f]=o.useState(""),[h,x]=o.useState(!1),[c,j]=o.useState(!0),[w,C]=o.useState(""),[E,S]=o.useState(null),G=o.useRef(null),z=o.useCallback(async()=>{try{const m=await se.wikiStatus();return a(m),m}catch{return null}},[]),P=o.useCallback(async()=>{try{const m=await se.wikiFiles();d(m.files||[]),u(m.exists)}catch{}},[]),Z=o.useCallback(async()=>{try{const m=await se.wikiFileContent("meta.json");m!=null&&m.content&&S(JSON.parse(m.content))}catch{}},[]);o.useEffect(()=>{(async()=>{j(!0),await Promise.all([z(),P(),Z()]),j(!1)})()},[z,P,Z]),o.useEffect(()=>{if(s.task.status==="running"){let m=0;G.current=setInterval(async()=>{const N=await z();m++,m%3===0&&await P(),N&&N.task.status!=="running"&&(await Promise.all([P(),Z()]),G.current&&clearInterval(G.current))},1500)}else G.current&&clearInterval(G.current);return()=>{G.current&&clearInterval(G.current)}},[s.task.status,z,P,Z]);const X=async()=>{try{await se.wikiUpdate(),a(m=>({...m,task:{...m.task,status:"running",progress:0,message:t("wiki.incrementalUpdating")}}))}catch(m){console.error("Wiki update failed:",m)}},H=async m=>{if(m!=="meta.json"){n(m),x(!0);try{const N=await se.wikiFileContent(m);f(N.content)}catch{f(`# ${t("wiki.loadFailed")}
129
+
130
+ ${t("wiki.loadFailedDesc")}`)}finally{x(!1)}}},q=()=>{n(null),f("")},R=o.useMemo(()=>l.filter(m=>m.path!=="meta.json"),[l]),M=o.useMemo(()=>Zn(R,E==null?void 0:E.files),[R,E]);if(c)return e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx(Fe,{size:F.xl,className:"text-blue-500 animate-spin"})});const _=!i&&R.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(Xn,{task:s.task,wiki:s.wiki}),_?e.jsx(so,{}):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(Fe,{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-white border border-slate-200 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-slate-100 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(tt,{size:16,className:"text-blue-500"}),e.jsx("span",{className:"text-sm font-semibold text-slate-700",children:"Wiki"}),(E==null?void 0:E.version)&&e.jsxs("span",{className:"text-[10px] text-slate-300",children:["v",E.version]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[i&&e.jsx("span",{className:"text-[10px] text-slate-400",children:t("wiki.fileCount",{count:R.length})}),s.task.status!=="running"&&i&&e.jsx("button",{onClick:X,title:t("wiki.incrementalUpdate"),className:"p-1 rounded-md text-blue-500 hover:bg-blue-50 transition-colors",children:e.jsx(yt,{size:13})})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(ft,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx("input",{type:"text",placeholder:t("wiki.searchPlaceholder"),value:w,onChange:m=>C(m.target.value),className:"w-full pl-8 pr-3 py-2 text-sm bg-slate-50 border border-slate-200 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(eo,{tree:M,selectedFile:p,onSelect:H,searchQuery:w}),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(Fe,{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")})]})]}),(E==null?void 0:E.generatedAt)&&e.jsx("div",{className:"px-3 py-2 border-t border-slate-100 shrink-0",children:e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] text-slate-400",children:[e.jsx(xt,{size:10}),e.jsx("span",{children:Qn(E.generatedAt)}),E.duration!=null&&e.jsxs("span",{children:["· ",Za(E.duration)]})]})})]}),e.jsx("div",{className:`flex-1 bg-white border border-slate-200 rounded-xl overflow-hidden flex flex-col min-h-0 ${p?"":"hidden lg:flex"}`,children:p?e.jsx(to,{filePath:p,content:g,loading:h,meta:E,onBack:q}):e.jsx(ao,{meta:E,onSelectFile:H,isGenerating:s.task.status==="running",progress:s.task.progress,message:s.task.message})})]})]})]})},ro={authority:0,guardUsageCount:0,humanUsageCount:0,aiUsageCount:0,lastUsedAt:null,authorityScore:0},no=({editingRecipe:t,setEditingRecipe:s,handleSaveRecipe:a,closeRecipeEdit:l,isSavingRecipe:d=!1})=>{var x,c,j,w,C,E,S,G,z,P,Z,X,H,q,R,M,_;const{t:i}=_e(),[u,p]=o.useState("preview"),n=o.useRef(!0);o.useEffect(()=>()=>{n.current=!1},[]);const g=(()=>{const m=(t.language||"").toLowerCase();return["objectivec","objc","objective-c","obj-c"].includes(m)?"objectivec":t.language||"text"})(),f=async m=>{try{if(await se.setRecipeAuthority(t.name,m),n.current){const N=t.stats?{...t.stats,authority:m}:{...ro,authority:m};s({...t,stats:N})}}catch(N){console.warn(i("recipeEditor.authorityFailed"),N==null?void 0:N.message)}},h=m=>{if(!m)return"";const N=typeof m=="string"?new Date(m).getTime():m;return isNaN(N)?"":new Date(N).toLocaleString("zh-CN",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"})};return e.jsxs(Ze,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx(Ze.Backdrop,{className:"bg-slate-900/50 backdrop-blur-sm"}),e.jsxs("div",{className:"relative bg-white w-full max-w-6xl rounded-2xl shadow-2xl flex flex-col h-[85vh]",children:[e.jsxs("div",{className:"p-6 border-b border-slate-100 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:i("recipeEditor.title")}),t.kind&&(()=>{const N={rule:{label:"Rule",color:"text-red-700",bg:"bg-red-50",border:"border-red-200",icon:ut},pattern:{label:"Pattern",color:"text-violet-700",bg:"bg-violet-50",border:"border-violet-200",icon:jt},fact:{label:"Fact",color:"text-cyan-700",bg:"bg-cyan-50",border:"border-cyan-200",icon:tt}}[t.kind];if(!N)return null;const y=N.icon;return e.jsxs("span",{className:`text-[10px] font-bold px-2 py-1 rounded uppercase flex items-center gap-1 border ${N.bg} ${N.color} ${N.border}`,children:[e.jsx(y,{size:F.sm}),N.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-slate-50 text-slate-500 border-slate-200":t.status==="archived"?"bg-orange-50 text-orange-600 border-orange-200":"bg-slate-50 text-slate-500 border-slate-200"}`,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-slate-500",children:i("recipeEditor.authorityScore")}),u==="preview"?e.jsx("span",{className:"text-sm text-slate-700",children:((x=t.stats)==null?void 0:x.authority)??3}):e.jsxs("select",{className:"font-bold text-amber-600 bg-amber-50 border border-amber-100 px-2 py-1 rounded-lg outline-none text-[10px] focus:ring-2 focus:ring-amber-500",value:((c=t.stats)==null?void 0:c.authority)??3,onChange:m=>f(parseInt(m.target.value)),children:[e.jsxs("option",{value:"1",children:["⭐ 1 - ",i("recipeEditor.qualityLevels.basic")]}),e.jsxs("option",{value:"2",children:["⭐⭐ 2 - ",i("recipeEditor.qualityLevels.good")]}),e.jsxs("option",{value:"3",children:["⭐⭐⭐ 3 - ",i("recipeEditor.qualityLevels.solid")]}),e.jsxs("option",{value:"4",children:["⭐⭐⭐⭐ 4 - ",i("recipeEditor.qualityLevels.great")]}),e.jsxs("option",{value:"5",children:["⭐⭐⭐⭐⭐ 5 - ",i("recipeEditor.qualityLevels.excellent")]})]})]}),e.jsxs("div",{className:"flex bg-slate-100 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 ${u==="preview"?"bg-white shadow-sm text-blue-600":"text-slate-400"}`,children:[e.jsx(os,{size:F.sm})," ",i("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 ${u==="edit"?"bg-white shadow-sm text-blue-600":"text-slate-400"}`,children:[e.jsx(Et,{size:F.sm})," ",i("recipeEditor.edit")]})]}),e.jsx("button",{onClick:l,className:"p-2 hover:bg-slate-100 rounded-full",children:e.jsx(Xe,{size:F.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:u==="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-slate-400 uppercase mb-1",children:i("recipeEditor.path")}),e.jsx("input",{className:"w-full p-2 bg-slate-50 border border-slate-200 rounded-lg text-sm",value:t.name,onChange:m=>s({...t,name:m.target.value})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-slate-400 uppercase mb-1",children:i("recipeEditor.description")}),e.jsx("textarea",{className:"w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300 resize-none",rows:2,value:t.description||"",onChange:m=>s({...t,description:m.target.value}),placeholder:i("recipeEditor.descPlaceholder")})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-bold text-slate-400 uppercase mb-1.5 flex items-center gap-1.5",children:[e.jsx(nt,{size:11,className:"text-blue-400"})," ",i("recipeEditor.markdown")]}),e.jsx("div",{className:"border border-slate-200 rounded-lg overflow-hidden",style:{minHeight:180},children:e.jsx(ks,{value:((j=t.content)==null?void 0:j.markdown)||"",onChange:m=>s({...t,content:{...t.content,markdown:m}}),language:"markdown",height:"180px",showLineNumbers:!0})})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-bold text-slate-400 uppercase mb-1.5 flex items-center gap-1.5",children:[e.jsx(Ht,{size:11,className:"text-emerald-500"})," ",i("recipeEditor.code")]}),e.jsx("div",{className:"border border-slate-200 rounded-lg overflow-hidden",style:{minHeight:180},children:e.jsx(ks,{value:((w=t.content)==null?void 0:w.pattern)||"",onChange:m=>s({...t,content:{...t.content,pattern:m}}),language:g,height:"180px",showLineNumbers:!0})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-slate-400 uppercase mb-1",children:i("recipeEditor.rationale")}),e.jsx("textarea",{className:"w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-300 resize-y",rows:3,value:((C=t.content)==null?void 0:C.rationale)||"",onChange:m=>s({...t,content:{...t.content,rationale:m.target.value}}),placeholder:i("recipeEditor.rationalePlaceholder")})]})]}):e.jsxs("div",{className:"flex-1 overflow-y-auto space-y-6 scrollbar-light",children:[(()=>{const m=[["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(([,N])=>!!N);return m.length===0?null:e.jsxs("div",{className:"bg-slate-50 border border-slate-200 rounded-2xl p-6",children:[e.jsx("h3",{className:"text-[10px] font-bold text-slate-400 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:m.map(([N,y])=>e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-[10px] text-slate-400 font-bold uppercase mb-1",children:N}),e.jsx("span",{className:"text-sm text-slate-700 break-all font-medium",children:y})]},N))})]})})(),t.description&&e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:i("recipeEditor.description")}),e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:t.description})]}),((E=t.content)==null?void 0:E.markdown)&&e.jsxs("div",{className:"bg-white rounded-2xl border border-blue-100 p-6",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-3 block flex items-center gap-1.5",children:[e.jsx(nt,{size:11,className:"text-blue-400"})," ",i("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-slate-700 leading-relaxed",children:e.jsx(gt,{content:t.content.markdown})})})]}),((S=t.content)==null?void 0:S.pattern)&&e.jsxs("div",{className:"bg-white rounded-2xl border border-emerald-100 p-6",children:[e.jsxs("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-3 block flex items-center gap-1.5",children:[e.jsx(Ht,{size:11,className:"text-emerald-500"})," ",i("recipeEditor.code")]}),e.jsx(dt,{code:t.content.pattern,language:g,showLineNumbers:!0})]}),((G=t.content)==null?void 0:G.rationale)&&e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:i("recipeEditor.rationale")}),e.jsx("div",{className:"bg-slate-50 border border-slate-100 rounded-xl p-4",children:e.jsx("p",{className:"text-sm text-slate-600 leading-relaxed",children:t.content.rationale})})]}),((z=t.content)==null?void 0:z.steps)&&t.content.steps.length>0&&e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:i("recipeEditor.steps")}),e.jsx("div",{className:"space-y-2",children:t.content.steps.map((m,N)=>typeof m=="string"?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 border border-slate-100 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:N+1}),e.jsx("p",{className:"text-xs text-slate-700 leading-relaxed",children:m})]},N):e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 border border-slate-100",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:N+1}),m.title&&e.jsx("span",{className:"text-xs font-bold text-slate-700",children:m.title})]}),m.description&&e.jsx("p",{className:"text-xs text-slate-600 ml-7 leading-relaxed",children:m.description}),m.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:m.code})]},N))})]}),((P=t.content)==null?void 0:P.codeChanges)&&t.content.codeChanges.length>0&&e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:i("recipeEditor.codeChanges")}),e.jsx("div",{className:"space-y-2",children:t.content.codeChanges.map((m,N)=>e.jsxs("div",{className:"border border-slate-200 rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-3 py-1.5 bg-slate-50 border-b border-slate-200 flex items-center gap-2",children:[e.jsx(ht,{size:11,className:"text-blue-400"}),e.jsx("code",{className:"text-[10px] font-mono text-slate-600",children:m.file})]}),m.explanation&&e.jsx("p",{className:"text-[11px] text-slate-500 px-3 py-1.5 border-b border-slate-100 bg-yellow-50/30",children:m.explanation}),e.jsxs("div",{className:"p-2 bg-red-50/20 border-b border-slate-100",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-slate-600 whitespace-pre-wrap break-words font-mono",children:m.before||i("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-slate-700 whitespace-pre-wrap break-words font-mono",children:m.after})]})]},N))})]}),((Z=t.content)==null?void 0:Z.verification)&&e.jsxs("div",{className:"bg-white rounded-2xl border border-teal-100 p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-slate-400 uppercase mb-2 block",children:i("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-slate-600",children:[e.jsx("span",{className:"font-bold text-teal-600",children:i("recipeEditor.validationMethod")})," ",t.content.verification.method]}),t.content.verification.expectedResult&&e.jsxs("p",{className:"text-xs text-slate-600",children:[e.jsx("span",{className:"font-bold text-teal-600",children:i("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-slate-50 border border-slate-200 rounded-2xl p-6",children:[e.jsxs("h3",{className:"text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-3 flex items-center gap-1.5",children:[e.jsx(ls,{size:11,className:"text-blue-400"})," ",i("recipeEditor.tags")]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.tags.map((m,N)=>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:m},N))})]}),!!(t.constraints&&((X=t.constraints.guards)!=null&&X.length||(H=t.constraints.boundaries)!=null&&H.length||(q=t.constraints.preconditions)!=null&&q.length||(R=t.constraints.sideEffects)!=null&&R.length))&&e.jsxs("div",{className:"bg-slate-50 border border-slate-200 rounded-2xl p-6 space-y-4",children:[e.jsxs("h3",{className:"text-[10px] font-bold text-slate-400 uppercase tracking-widest flex items-center gap-1.5",children:[e.jsx(ut,{size:11,className:"text-amber-500"})," ",i("recipeEditor.constraints")]}),t.constraints.guards&&t.constraints.guards.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-slate-500 block mb-1.5",children:i("recipeEditor.guardRules")}),e.jsx("ul",{className:"text-sm text-slate-600 space-y-1",children:t.constraints.guards.map((m,N)=>e.jsxs("li",{className:"flex gap-2 items-start",children:[e.jsx("span",{className:`text-xs mt-0.5 ${m.severity==="error"?"text-red-500":"text-yellow-500"}`,children:"●"}),e.jsx("code",{className:"font-mono text-xs bg-slate-100 px-1.5 py-0.5 rounded",children:m.pattern}),m.message&&e.jsxs("span",{className:"text-xs text-slate-400",children:["— ",m.message]})]},N))})]}),t.constraints.boundaries&&t.constraints.boundaries.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-slate-500 block mb-1.5",children:i("recipeEditor.boundaryConstraints")}),e.jsx("ul",{className:"text-sm text-slate-600 space-y-1",children:t.constraints.boundaries.map((m,N)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-orange-400",children:"●"}),m]},N))})]}),t.constraints.preconditions&&t.constraints.preconditions.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-slate-500 block mb-1.5",children:i("recipeEditor.preconditions")}),e.jsx("ul",{className:"text-sm text-slate-600 space-y-1",children:t.constraints.preconditions.map((m,N)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-blue-400",children:"◆"}),m]},N))})]}),t.constraints.sideEffects&&t.constraints.sideEffects.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-slate-500 block mb-1.5",children:i("recipeEditor.sideEffects")}),e.jsx("ul",{className:"text-sm text-slate-600 space-y-1",children:t.constraints.sideEffects.map((m,N)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-pink-400",children:"⚡"}),m]},N))})]})]}),t.relations&&Object.entries(t.relations).some(([,m])=>Array.isArray(m)&&m.length>0)&&e.jsxs("div",{className:"bg-slate-50 border border-slate-200 rounded-2xl p-6",children:[e.jsx("h3",{className:"text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-4",children:i("recipeEditor.relations")}),e.jsx("div",{className:"space-y-2",children:[{key:"inherits",label:i("recipeEditor.relationTypes.inherits"),color:"text-green-600",icon:"↑"},{key:"implements",label:i("recipeEditor.relationTypes.implements"),color:"text-blue-600",icon:"◇"},{key:"calls",label:i("recipeEditor.relationTypes.calls"),color:"text-cyan-600",icon:"→"},{key:"dependsOn",label:i("recipeEditor.relationTypes.dependsOn"),color:"text-yellow-600",icon:"⊕"},{key:"dataFlow",label:i("recipeEditor.relationTypes.dataFlow"),color:"text-purple-600",icon:"⇢"},{key:"conflicts",label:i("recipeEditor.relationTypes.conflicts"),color:"text-red-600",icon:"✕"},{key:"extends",label:i("recipeEditor.relationTypes.extends"),color:"text-teal-600",icon:"⊃"},{key:"related",label:i("recipeEditor.relationTypes.associates"),color:"text-slate-500",icon:"∼"}].map(({key:m,label:N,color:y,icon:W})=>{var be;const O=(be=t.relations)==null?void 0:be[m];return!O||!Array.isArray(O)||O.length===0?null:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("span",{className:`text-xs font-mono ${y} w-16 shrink-0 pt-0.5`,children:[W," ",N]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:O.map((we,ye)=>e.jsx("span",{className:"px-2 py-0.5 bg-white border border-slate-200 text-slate-600 rounded-lg text-xs font-mono",children:typeof we=="string"?we:we.id||we.title||JSON.stringify(we)},ye))})]},m)})})]}),!((M=t.content)!=null&&M.markdown)&&!((_=t.content)!=null&&_.pattern)&&!t.description&&e.jsx("div",{className:"bg-white p-8 rounded-2xl border border-slate-100 shadow-sm min-h-[200px] flex items-center justify-center",children:e.jsx("div",{className:"text-slate-300 italic",children:i("recipeEditor.noContent")})})]})})}),e.jsxs("div",{className:"p-6 border-t border-slate-100 flex justify-end gap-3",children:[e.jsx("button",{onClick:l,disabled:d,className:"px-4 py-2 text-slate-600 font-medium disabled:opacity-50",children:i("recipeEditor.cancel")}),e.jsxs("button",{onClick:a,disabled:d,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:[d?e.jsx(Fe,{size:F.lg,className:"animate-spin"}):e.jsx(Ss,{size:F.lg}),i(d?"recipeEditor.saving":"recipeEditor.saveChanges")]})]})]})]})},oo=({setShowCreateModal:t,createPath:s,setCreatePath:a,handleCreateFromPath:l,handleCreateFromClipboard:d,isExtracting:i})=>{const{t:u}=_e(),{isDark:p}=St();return e.jsxs(Ze,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx(Ze.Backdrop,{className:"bg-slate-900/50 backdrop-blur-sm"}),e.jsxs("div",{className:`relative w-full max-w-lg rounded-2xl shadow-2xl overflow-hidden ${p?"bg-[#1e1e1e]":"bg-white"}`,children:[e.jsxs("div",{className:`p-6 border-b flex justify-between items-center ${p?"bg-[#252526] border-[#3e3e42]":"bg-slate-50 border-slate-100"}`,children:[e.jsxs("h2",{className:`text-xl font-bold flex items-center gap-2 ${p?"text-white":"text-slate-800"}`,children:[e.jsx(Nt,{size:F.xl,className:"text-blue-600"})," ",u("createModal.title")]}),e.jsx("button",{onClick:()=>t(!1),className:`p-2 rounded-full transition-all duration-150 ${p?"text-slate-400 hover:bg-[#3e3e42] hover:text-slate-200":"text-slate-500 hover:bg-white hover:text-slate-700"}`,children:e.jsx(Xe,{size:F.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 ${p?"text-slate-500":"text-slate-400"}`,children:[e.jsx(Ma,{size:F.sm})," ",u("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-blue-500 border ${p?"bg-[#2a2d35] border-[#3e3e42] text-slate-200 placeholder-slate-500":"bg-slate-100 border-slate-200 text-slate-900"}`,placeholder:u("createModal.pathPlaceholder"),value:s,onChange:n=>a(n.target.value)}),e.jsx("button",{onClick:l,disabled:!s||i,className:`px-4 py-2 rounded-xl text-sm font-bold disabled:opacity-50 transition-all duration-150 ${p?"bg-slate-200 text-slate-900 hover:bg-white":"bg-slate-900 text-white hover:bg-slate-800"}`,children:u("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 ${p?"border-[#3e3e42]":"border-slate-100"}`})}),e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:`px-2 font-bold ${p?"bg-[#1e1e1e] text-slate-500":"bg-white text-slate-300"}`,children:u("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 ${p?"text-slate-500":"text-slate-400"}`,children:[e.jsx(_l,{size:F.sm})," ",u("createModal.importFromClipboard")]}),e.jsxs("button",{onClick:()=>d(),disabled:i,className:`w-full flex items-center justify-center gap-3 p-4 rounded-xl font-bold transition-all duration-150 border ${p?"bg-blue-500/10 text-blue-300 border-blue-500/20 hover:bg-blue-500/20 hover:border-blue-400/30":"bg-blue-50 text-blue-700 border-blue-100 hover:bg-blue-100"}`,children:[e.jsx(et,{size:F.lg})," ",u("createModal.useClipboard")]})]})]}),i&&e.jsxs("div",{className:"bg-blue-600 text-white p-4 flex items-center justify-center gap-3 animate-pulse",children:[e.jsx(ns,{size:F.lg,className:"animate-spin"}),e.jsx("span",{className:"font-bold text-sm",children:u("createModal.aiThinking")})]})]})]})};function io(t){if(!t)return"";if(typeof t=="object"){const d=t.code||t.pattern||t.markdown||t.snippet||t.body||"";if(d)return d}const a=(typeof t=="string"?t:JSON.stringify(t)).replace(/^---[\s\S]*?---\s*\n?/,"").trim(),l=a.match(/```[\w]*\n([\s\S]*?)```/);return l&&l[1]?l[1].trim():a.slice(0,8e3)}const co=({searchQ:t,insertPath:s,onClose:a})=>{const{t:l}=_e(),[d,i]=o.useState([]),[u,p]=o.useState(!0),[n,g]=o.useState(null),f=o.useRef(!0),h=o.useRef(null);o.useEffect(()=>(f.current=!0,h.current=new AbortController,se.search(t||"",{mode:"bm25",type:"recipe",signal:h.current.signal}).then(c=>{f.current&&i((c.items||[]).map(j=>({name:(j.title||j.name||"")+".md",path:"",content:j.content,qualityScore:(j.quality||{}).overall||j.qualityScore||0,recommendReason:""})))}).catch(c=>{c.name!=="AbortError"&&f.current&&i([])}).finally(()=>{f.current&&p(!1)}),()=>{f.current=!1,h.current&&h.current.abort()}),[t]);const x=async c=>{g(c.name);try{const j=io(c.content);await se.insertAtSearchMark({path:s,content:j}),f.current&&(alert(l("searchModal.insertSuccess")+" "+s),a())}catch{f.current&&alert(l("searchModal.insertFailed"))}finally{f.current&&g(null)}};return e.jsxs(Ze,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx(Ze.Backdrop,{className:"bg-slate-900/50 backdrop-blur-sm"}),e.jsxs("div",{className:"relative bg-white 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-slate-100 flex justify-between items-center bg-slate-50",children:[e.jsxs("h2",{className:"text-xl font-bold flex items-center gap-2 text-slate-800",children:[e.jsx(ft,{size:F.xl,className:"text-blue-600"})," ",l("searchModal.title")]}),e.jsx("button",{onClick:a,className:"p-2 hover:bg-white rounded-full transition-colors",children:e.jsx(Xe,{size:F.lg})})]}),e.jsxs("div",{className:"p-4 text-sm text-slate-500 border-b border-slate-100",children:[l("searchModal.keyword")," ",t||l("searchModal.keywordAll")," · ",l("searchModal.insertTo")," ",s]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:u?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"})}):d.length===0?e.jsx("div",{className:"text-slate-500 text-center py-8",children:l("searchModal.noResults")}):e.jsx("ul",{className:"space-y-2",children:d.map(c=>e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>x(c),disabled:n!==null,className:"w-full flex items-center justify-between gap-3 p-4 rounded-xl border border-slate-200 hover:border-blue-300 hover:bg-blue-50/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-slate-800 truncate",children:c.name}),(c.qualityScore!==void 0||c.recommendReason)&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.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:["🤖 ",l("searchModal.quality")," ",(c.qualityScore*100).toFixed(0),"%"]}),c.recommendReason&&e.jsx("span",{className:"text-xs text-slate-600 italic truncate max-w-xs",children:c.recommendReason})]})]}),n===c.name?e.jsxs("span",{className:"text-blue-600 text-sm flex items-center gap-1",children:[e.jsx("span",{className:"animate-spin",children:"⏳"})," ",l("searchModal.inserting")]}):e.jsxs("span",{className:"text-blue-600 text-sm flex items-center gap-1",children:[e.jsx(Fa,{size:F.md})," ",l("searchModal.insertBtn")]})]})},c.name))})})]})]})},Ps=[{id:"google",labelKey:"llmConfig.providers.gemini",defaultModel:"gemini-2.0-flash",keyEnv:"ASD_GOOGLE_API_KEY"},{id:"openai",labelKey:"llmConfig.providers.openai",defaultModel:"gpt-4o",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-3-5-sonnet-20240620",keyEnv:"ASD_CLAUDE_API_KEY"},{id:"ollama",labelKey:"llmConfig.providers.ollama",defaultModel:"llama3",keyEnv:""}],uo=({onClose:t,onSaved:s})=>{const{t:a}=_e(),{isDark:l}=St(),[d,i]=o.useState(!0),[u,p]=o.useState(!1),[n,g]=o.useState(!1),[f,h]=o.useState("google"),[x,c]=o.useState("gemini-2.0-flash"),[j,w]=o.useState(""),[C,E]=o.useState(""),[S,G]=o.useState(!1),[z,P]=o.useState({}),[Z,X]=o.useState(!1);o.useEffect(()=>{H()},[]);const H=async()=>{i(!0);try{const y=await se.getLlmEnvConfig();g(y.hasEnvFile);const W=y.vars||{};W.ASD_AI_PROVIDER&&h(W.ASD_AI_PROVIDER),W.ASD_AI_MODEL&&c(W.ASD_AI_MODEL),W.ASD_AI_PROXY&&E(W.ASD_AI_PROXY),P(W)}catch{}finally{i(!1)}},q=Ps.find(y=>y.id===f),R=(q==null?void 0:q.keyEnv)||"",M=R?!!z[R]:!0,_=y=>{h(y);const W=Ps.find(O=>O.id===y);W&&c(W.defaultModel),w("")},m=async()=>{if(f){if(R&&!M&&!j.trim()){alert(a("llmConfig.apiKeyRequired"));return}p(!0),X(!1);try{await se.saveLlmEnvConfig({provider:f,model:x||void 0,apiKey:j.trim()||void 0,proxy:C.trim()||void 0}),X(!0),setTimeout(()=>{s(),t()},800)}catch(y){alert((y==null?void 0:y.message)||a("llmConfig.saveFailed"))}finally{p(!1)}}},N=y=>!y||y.length<10?y?"••••••":"":`${y.slice(0,6)}••••${y.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-lg mx-4 overflow-hidden ${l?"bg-[#1e1e1e]":"bg-white"}`,onClick:y=>y.stopPropagation(),children:[e.jsxs("div",{className:`flex items-center justify-between px-6 py-4 border-b ${l?"border-[#3e3e42]":"border-slate-100"}`,children:[e.jsx("h2",{className:`text-lg font-semibold ${l?"text-white":"text-slate-800"}`,children:a("llmConfig.title")}),e.jsx("button",{onClick:t,className:`p-1 rounded-lg transition-all duration-150 ${l?"hover:bg-[#3e3e42] text-slate-400 hover:text-slate-200":"hover:bg-slate-100 text-slate-400"}`,children:e.jsx(Xe,{size:F.md})})]}),e.jsx("div",{className:"px-6 py-5 space-y-5",children:d?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Fe,{size:24,className:"animate-spin text-blue-500"})}):e.jsxs(e.Fragment,{children:[!n&&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(Rt,{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 ${l?"text-slate-300":"text-slate-700"}`,children:a("llmConfig.provider")}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:Ps.map(y=>e.jsx("button",{type:"button",onClick:()=>_(y.id),className:`px-3 py-2 rounded-lg text-sm font-medium border transition-all ${f===y.id?l?"bg-blue-500/20 border-blue-500/40 text-blue-300 ring-1 ring-blue-500/30":"bg-blue-50 border-blue-300 text-blue-700 ring-1 ring-blue-200":l?"bg-[#2a2d35] border-[#3e3e42] text-slate-300 hover:border-slate-500 hover:bg-[#333842]":"bg-white border-slate-200 text-slate-600 hover:border-slate-300 hover:bg-slate-50"}`,children:a(y.labelKey)},y.id))})]}),e.jsxs("div",{children:[e.jsx("label",{className:`block text-sm font-medium mb-1.5 ${l?"text-slate-300":"text-slate-700"}`,children:a("llmConfig.model")}),e.jsx("input",{type:"text",value:x,onChange:y=>c(y.target.value),placeholder:(q==null?void 0:q.defaultModel)||"",className:`w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-300 ${l?"bg-[#2a2d35] border-[#3e3e42] text-slate-200 placeholder-slate-500":"border-slate-200"}`})]}),R&&e.jsxs("div",{children:[e.jsxs("label",{className:`block text-sm font-medium mb-1.5 ${l?"text-slate-300":"text-slate-700"}`,children:[a("llmConfig.apiKey"),M&&e.jsxs("span",{className:"ml-2 text-xs text-green-600 font-normal",children:["(",a("llmConfig.configured")," ",N(z[R]),")"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:S?"text":"password",value:j,onChange:y=>w(y.target.value),placeholder:a(M?"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-blue-500/20 focus:border-blue-300 ${l?"bg-[#2a2d35] border-[#3e3e42] text-slate-200 placeholder-slate-500":"border-slate-200"}`}),e.jsx("button",{type:"button",onClick:()=>G(y=>!y),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-slate-400 hover:text-slate-600",children:S?e.jsx($l,{size:16}):e.jsx(os,{size:16})})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:`block text-sm font-medium mb-1.5 ${l?"text-slate-300":"text-slate-700"}`,children:[a("llmConfig.proxy")," ",e.jsx("span",{className:`text-xs font-normal ${l?"text-slate-500":"text-slate-400"}`,children:a("llmConfig.optional")})]}),e.jsx("input",{type:"text",value:C,onChange:y=>E(y.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-blue-500/20 focus:border-blue-300 ${l?"bg-[#2a2d35] border-[#3e3e42] text-slate-200 placeholder-slate-500":"border-slate-200"}`})]})]})}),e.jsxs("div",{className:`flex items-center justify-end gap-3 px-6 py-4 border-t ${l?"border-[#3e3e42] bg-[#252526]":"border-slate-100 bg-slate-50/50"}`,children:[e.jsx("button",{onClick:t,className:`px-4 py-2 text-sm font-medium transition-colors ${l?"text-slate-400 hover:text-slate-200":"text-slate-600 hover:text-slate-800"}`,children:a("llmConfig.cancel")}),e.jsxs("button",{onClick:m,disabled:u||d||Z,className:`flex items-center gap-2 px-5 py-2 rounded-lg text-sm font-medium transition-all ${Z?"bg-green-500 text-white":"bg-blue-600 text-white hover:bg-blue-700 shadow-sm"} disabled:opacity-60`,children:[u?e.jsx(Fe,{size:16,className:"animate-spin"}):Z?e.jsx(cs,{size:16}):e.jsx(Ss,{size:16}),a(Z?"llmConfig.saved":"llmConfig.saveToEnv")]})]})]})})};class po extends Ct.Component{constructor(s){super(s),this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}render(){var s;return this.state.hasError?e.jsxs("div",{style:{padding:40,textAlign:"center"},children:[e.jsx("h2",{style:{color:"#ef4444",marginBottom:12},children:zs.app.errorBoundary.title}),e.jsx("pre",{style:{fontSize:12,color:"#64748b",whiteSpace:"pre-wrap",maxWidth:600,margin:"0 auto"},children:(s=this.state.error)==null?void 0:s.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:zs.app.errorBoundary.refreshBtn})]}):this.props.children}}function Qt(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 xo=()=>{var Je,st;const t=pr(),s=mr((Je=t.user)==null?void 0:Je.role),a=hr(),{t:l,lang:d}=_e(),i=()=>{const A=window.location.pathname.replace(/^\//,"").split("/")[0]||"";return sr.includes(A)?A:"help"},[u,p]=o.useState(null),[n,g]=o.useState(i()),[f,h]=o.useState(!1),[x,c]=o.useState(""),[j,w]=o.useState(!0),[C,E]=o.useState(null),[S,G]=o.useState([]),[z,P]=o.useState([]),[Z,X]=o.useState(null),[H,q]=o.useState(!1),[R,M]=o.useState({current:0,total:0,status:""}),[_,m]=o.useState([]),[N,y]=o.useState([]),[W,O]=o.useState(null),[be,we]=o.useState("All"),[ye,v]=o.useState(1),[ee,ae]=o.useState(12),[ue,fe]=o.useState(!1),[he,ce]=o.useState(""),[je,$]=o.useState(!1),[K,xe]=o.useState(null),[L,T]=o.useState(null),[Q,ie]=o.useState(!1),[ke,Ue]=o.useState(!0),[Ie,ne]=o.useState(!1),[ve,He]=o.useState(0),Pe=o.useRef(null),Ne=o.useRef(null);o.useEffect(()=>{v(1)},[x,be]),o.useEffect(()=>{if(u!=null&&u.projectRoot)try{const A=`asd:custom-folder-targets:${u.projectRoot}`,le=localStorage.getItem(A);P(le?JSON.parse(le):[])}catch{P([])}},[u==null?void 0:u.projectRoot]);const r=()=>{Pe.current&&Pe.current.abort()};o.useEffect(()=>{let A=!1;const le=async()=>{var pe,De,Te;try{const Ee=await se.getSignalStatus();if(!A){const Me=((pe=Ee==null?void 0:Ee.suggestions)==null?void 0:pe.length)||0,Se=((Te=(De=Ee==null?void 0:Ee.snapshot)==null?void 0:De.lastResult)==null?void 0:Te.newSuggestions)||0;He(Me||Se)}}catch{}};le();const Y=setInterval(le,300*1e3);return()=>{A=!0,clearInterval(Y)}},[]),o.useEffect(()=>{a.isAllDone&&D()},[a.isAllDone]),o.useEffect(()=>{if(a.candidateCreatedTick>0){const A=setTimeout(()=>D(),2e3);return()=>clearTimeout(A)}},[a.candidateCreatedTick]);const k=(A,le)=>{g(A);const Y=le!=null&&le.preserveSearch&&window.location.search?window.location.search:"";window.history.pushState({},document.title,`/${A}${Y}`)},b=A=>{E(A),g("recipes");const le=new URLSearchParams(window.location.search);le.set("edit",encodeURIComponent(A.name)),window.history.pushState({},document.title,`/recipes?${le.toString()}`)},B=()=>{E(null),window.history.replaceState({},document.title,"/recipes")};o.useEffect(()=>{x===""&&xe(null)},[x]),o.useEffect(()=>{g(i())},[]),o.useEffect(()=>{if(!u)return;const A=window.location.pathname.replace(/^\//,"").split("/")[0],Y=new URLSearchParams(window.location.search).get("edit");if(A==="recipes"&&Y&&u.recipes)try{const pe=decodeURIComponent(Y),De=u.recipes.find(Te=>Te.name===pe);De&&!C&&(g("recipes"),b(De))}catch{}},[u]),o.useEffect(()=>{D(),U(),te();const A=()=>{g(i())};window.addEventListener("popstate",A);const le=new URLSearchParams(window.location.search),Y=le.get("action"),pe=le.get("path"),De=le.get("q")||"";return Y==="search"&&pe?T({q:De,path:pe}):Y==="create"&&pe&&(ce(pe),fe(!0),le.get("autoScan")==="1"&&setTimeout(()=>I(pe),500)),Y&&window.history.replaceState({},document.title,window.location.pathname),()=>{window.removeEventListener("popstate",A)}},[]);const D=async()=>{w(!0);try{const A=await se.fetchData();p(A)}catch(A){re((A==null?void 0:A.message)||l("app.load.failed"),{title:l("app.load.failedTitle"),type:"error"})}finally{w(!1)}},U=async()=>{try{const A=await se.fetchTargets();G(A)}catch(A){console.warn("删除候选残留失败:",A==null?void 0:A.message)}},te=async()=>{try{const A=await se.getLlmEnvConfig();Ue(A.llmReady)}catch{}},de=async()=>{try{const A=await se.syncSnippets("all");re(l("app.sync.success"),{title:l("app.sync.successTitle")})}catch{re(l("app.sync.failedHint"),{title:l("app.sync.failed"),type:"error"})}},me=async()=>{try{await se.refreshProject(),U(),re(l("app.projectRefresh.success"),{title:l("app.projectRefresh.successTitle")})}catch{re(l("app.load.failedHint"),{title:l("app.projectRefresh.failed"),type:"error"})}},I=async A=>{var le;$(!0);try{const Y=await se.extractFromPath(A);y(Y.result.map(pe=>({...Qt(pe,"extract"),mode:"full",lang:"cn"}))),k("spm"),fe(!1),D(),((le=Y.result)==null?void 0:le.length)>0&&re(l("app.extract.success"),{title:l("app.extract.successTitle")})}catch{re(l("app.extract.failed"),{type:"error"})}finally{$(!1)}},V=async()=>{var A;if(he){$(!0);try{const le=await se.extractFromPath(he);y(le.result.map(Y=>({...Qt(Y,"extract"),mode:"full",lang:"cn"}))),k("spm"),fe(!1),D(),((A=le.result)==null?void 0:A.length)>0?re(le.isMarked?l("app.extract.markerSuccess"):l("app.extract.normalSuccess"),{title:l("app.extract.successTitle")}):le.isMarked||re(l("app.extract.noMarker"),{title:l("app.extract.extracting"),type:"info"})}catch{re(l("app.extract.failed"),{type:"error"})}finally{$(!1)}}},Ce=async A=>{var le,Y,pe,De;try{const Te=await navigator.clipboard.readText();if(!Te)return re(l("app.clipboard.empty"),{title:l("app.clipboard.emptyTitle"),type:"info"});re(l("app.clipboard.analyzing"),{title:l("app.clipboard.analyzingTitle"),type:"info"}),$(!0);const Ee=A||he;try{const Me=await se.extractFromText(Te,Ee||void 0),Se=Me._multipleCount;y([{...Qt(Me,"clipboard"),mode:"full",lang:"cn"}]),k("spm"),fe(!1),D(),re(Se?l("app.clipboard.resultMulti",{count:Se}):l("app.extract.normalSuccess"),{title:l("app.clipboard.resultTitle")})}catch(Me){const Se=((Y=(le=Me.response)==null?void 0:le.data)==null?void 0:Y.aiError)===!0,Ke=((De=(pe=Me.response)==null?void 0:pe.data)==null?void 0:De.error)||Me.message;Se?re(Ke,{title:l("app.clipboard.aiFailed"),type:"error"}):re(Ke,{title:l("common.operationFailed"),type:"error"})}}catch{re(l("app.clipboard.permissionError"),{title:l("app.clipboard.permissionTitle"),type:"error"})}finally{$(!1)}},Ae={"scan:started":{percent:5,status:l("app.scan.events.initializing")},"scan:files-loaded":{percent:15,status:A=>l("app.scan.events.filesLoaded",{count:A.count||0})},"scan:reading":{percent:25,status:A=>l("app.scan.events.readingFiles",{count:A.count||0})},"scan:ai-extracting":{percent:40,status:l("app.scan.events.aiAnalyzing")},"scan:enriching":{percent:85,status:A=>l("app.scan.events.enriching",{count:A.recipeCount||0})},"scan:completed":{percent:95,status:l("app.scan.events.completing")}},Re=async A=>{var Y;if(H)return;Pe.current&&Pe.current.abort(),Ne.current&&(clearInterval(Ne.current),Ne.current=null);const le=new AbortController;Pe.current=le,X(A.name),q(!0),y([]),O(null),m([]),M({current:0,total:100,status:l("app.scan.streamInit")});try{const pe=await se.scanTargetStream(A,Ee=>{const Me=Ae[Ee.type];if(Me){const Se=typeof Me.status=="function"?Me.status(Ee):Me.status;M({current:Me.percent,total:100,status:Se})}Ee.type==="scan:files-loaded"&&Ee.files&&m(Ee.files),Ee.type==="scan:ai-extracting"&&(Ne.current&&clearInterval(Ne.current),Ne.current=setInterval(()=>{M(Se=>({...Se,current:Math.min(Se.current+1,80)}))},3e3)),(Ee.type==="scan:enriching"||Ee.type==="scan:completed")&&Ne.current&&(clearInterval(Ne.current),Ne.current=null)},le.signal);Ne.current&&(clearInterval(Ne.current),Ne.current=null),M({current:100,total:100,status:l("app.scan.completed")});const De=pe.recipes||[],Te=pe.scannedFiles||[];if(De.length>0||Te.length>0){const Ee=typeof A=="string"?A:(A==null?void 0:A.name)||"unknown",Me=De.map(Se=>({...Qt(Se,"ai-scan"),mode:"full",lang:"cn",candidateTargetName:Ee,scanMode:"target"}));if(y(Me),Te.length>0&&m(Te),D(),De.length>0)re(l("app.scan.targetSuccess",{count:De.length}),{title:l("app.scan.targetSuccessTitle")});else if(pe.message){const Se=pe.noAi;re(pe.message,{title:l(Se?"app.scan.aiNotConfigured":"app.scan.noResults"),type:Se?"info":"error"})}else re(l("app.scan.noSnippets"),{title:l("app.scan.scanComplete"),type:"info"})}else re(l("app.scan.scanFailedHint"),{title:l("app.scan.scanFailed"),type:"error"})}catch(pe){if(Ne.current&&(clearInterval(Ne.current),Ne.current=null),pe.name==="AbortError")return;const De=(Y=pe.message)==null?void 0:Y.includes("timeout"),Te=De?l("app.scan.timeout"):pe.message||l("app.scan.scanError");re(Te,{title:l(De?"app.scan.timeoutTitle":"app.scan.scanError"),type:"error"})}finally{Pe.current===le&&(q(!1),M({current:0,total:0,status:""}),Pe.current=null)}},Be=async()=>{var le,Y,pe,De,Te,Ee;if(H)return;Pe.current&&Pe.current.abort();const A=new AbortController;Pe.current=A,k("candidates"),q(!0),y([]),O(null),m([]),M({current:0,total:100,status:l("app.coldStart.collecting")}),a.resetSession();try{const Me=await se.bootstrap(A.signal);M({current:100,total:100,status:l("app.coldStart.skeletonCreated")}),Me.bootstrapSession&&a.initFromApiResponse(Me.bootstrapSession),D();const Se=Me.report||{},Ke=((le=Me.targets)==null?void 0:le.length)||0,it=((Y=Se.totals)==null?void 0:Y.files)||0,At=((pe=Se.totals)==null?void 0:pe.graphEdges)||0,Kt=Me.guardSummary,As=Kt?`, ${l("app.coldStart.guardSuffix",{count:Kt.totalViolations})}`:"";re(l("app.coldStart.skeletonDetail",{targets:Ke,files:it,deps:At})+As)}catch(Me){if(ss.isCancel(Me))return;const Ke=Me.code==="ECONNABORTED"||((De=Me.message)==null?void 0:De.includes("timeout"))?l("app.coldStart.timeout"):((Ee=(Te=Me.response)==null?void 0:Te.data)==null?void 0:Ee.error)||Me.message;re(Ke,{type:"error"})}finally{Pe.current===A&&(q(!1),M({current:0,total:0,status:""}),Pe.current=null)}},Ye=async()=>{var De,Te,Ee,Me;if(H)return;Pe.current&&Pe.current.abort();const A=new AbortController;Pe.current=A,k("spm"),X("__project__"),q(!0),y([]),O(null),m([]),M({current:0,total:100,status:l("app.fullScan.collecting")});const le=[{status:l("app.fullScan.phase5"),percent:5},{status:l("app.fullScan.phase15"),percent:15},{status:l("app.fullScan.phase25"),percent:25},{status:l("app.fullScan.phase35"),percent:35},{status:l("app.fullScan.phase45"),percent:45},{status:l("app.fullScan.phase55"),percent:55},{status:l("app.fullScan.phase65"),percent:65},{status:l("app.fullScan.phase75"),percent:75},{status:l("app.fullScan.phase85"),percent:85}];let Y=0;const pe=setInterval(()=>{Y=Math.min(Y+1,le.length);const Se=le[Y-1];Se&&M(Ke=>({...Ke,current:Se.percent,status:Se.status}))},15e3);try{const Se=await se.scanProject(A.signal);clearInterval(pe),M({current:100,total:100,status:Se.partial?l("app.fullScan.partialComplete"):l("app.fullScan.completed")});const Ke=Se.recipes||[],it=Se.scannedFiles||[];if(Ke.length>0||it.length>0){const At=Ke.map(tl=>({...Qt(tl,"ai-scan"),mode:"full",lang:"cn",candidateTargetName:"__project__",scanMode:"project"}));y(At),m(it),O(Se.guardAudit||null),D();const Kt=(De=Se.guardAudit)==null?void 0:De.summary,As=Kt?`, ${l("app.fullScan.guardSuffix",{count:Kt.totalViolations})}`:"",el=Se.partial?l("app.fullScan.timeoutSuffix"):"";re(l("app.fullScan.resultDetail",{count:Ke.length})+As+el)}else re(l("app.fullScan.noContent"))}catch(Se){if(clearInterval(pe),ss.isCancel(Se))return;const it=Se.code==="ECONNABORTED"||((Te=Se.message)==null?void 0:Te.includes("timeout"))?l("app.fullScan.timeout"):((Me=(Ee=Se.response)==null?void 0:Ee.data)==null?void 0:Me.error)||Se.message;re(it,{type:"error"})}finally{Pe.current===A&&(q(!1),M({current:0,total:0,status:""}),Pe.current=null)}},J=(A,le)=>{const Y=[...N],pe={...Y[A],...le};Y[A]=pe,y(Y)},Le=async A=>{var le;if(!Q){ie(!0);try{const Y=(((le=A.content)==null?void 0:le.pattern)||"").trim(),pe=(()=>{if(!Y)return!1;const Ke=Y.split(`
131
+ `).filter(At=>At.trim());return Ke.filter(At=>/^\s*(#{1,6}\s|[-*>]\s|\d+\.\s)/.test(At)).length<=Ke.length*.3})(),De=(A.trigger||"").split(/[,,\s]+/).map(Ke=>Ke.trim()).filter(Boolean);if(pe&&De.length===0){re(l("app.recipe.triggerRequired"),{type:"error"}),ie(!1);return}const Te={title:A.title||"Untitled",description:A.description||"",trigger:De.join(", ")||"",language:A.language||"",category:A.category||"Utility",kind:A.kind||"pattern",knowledgeType:A.knowledgeType||"code-pattern",complexity:A.complexity||"intermediate",scope:A.scope||null,difficulty:A.difficulty||"",tags:A.tags||[],source:A.source||"ai-scan",sourceFile:A.sourceFile||"",moduleName:A.moduleName||"",doClause:A.doClause||"",dontClause:A.dontClause||"",whenClause:A.whenClause||"",topicHint:A.topicHint||"",coreCode:A.coreCode||"",content:A.content||{},reasoning:A.reasoning||{},quality:A.quality||{},constraints:A.constraints||{},relations:A.relations||{},stats:A.stats||{},headers:A.headers||[],headerPaths:A.headerPaths||[],includeHeaders:A.includeHeaders||!1},Ee=await se.knowledgeCreate(Te);if(Ee!=null&&Ee.id)try{await se.knowledgeLifecycle(Ee.id,"publish")}catch(Ke){console.warn("auto-publish after save failed:",Ke)}re(l(pe?"app.recipe.savedAsRecipe":"app.recipe.savedToKb")),y(Ke=>Ke.filter(it=>it.title!==A.title));const Me=A.candidateTargetName,Se=A.candidateId;if(Me&&Se)try{await se.deleteCandidate(Se)}catch{}D()}catch(Y){const pe=aa(Y)??vs(Y);re(pe??l("app.recipe.saveFailed"),{type:"error"})}finally{ie(!1)}}},qe=async()=>{var A,le;if(!(!C||Q)){ie(!0);try{const Y=C.id||((A=C.name)==null?void 0:A.replace(/\.md$/,"")),pe=typeof C.content=="string"?{pattern:C.content,markdown:"",rationale:"",steps:[],codeChanges:[],verification:null}:C.content||{};await se.knowledgeUpdate(Y,{title:((le=C.name)==null?void 0:le.replace(/\.md$/,""))||"",description:C.description||"",content:pe,tags:C.tags||[],kind:C.kind,language:C.language,category:C.category}),B(),D()}catch(Y){const pe=aa(Y)??vs(Y);re(pe??l("app.recipe.saveRecipeFailed"),{type:"error"})}finally{ie(!1)}}},ze=async A=>{if(window.confirm(l("common.areYouSure")))try{await se.deleteRecipe(A),D()}catch(le){const Y=vs(le);re(Y??l("common.deleteFailed"),{type:"error"})}},Ve=async(A,le)=>{try{await se.deleteCandidate(le),y(Y=>Y.filter(pe=>!(pe.candidateId===le&&pe.candidateTargetName===A))),p(Y=>{if(!(Y!=null&&Y.candidates))return Y;const pe={...Y.candidates};if(pe[A]){const De=pe[A].items.filter(Te=>Te.id!==le);De.length===0?delete pe[A]:pe[A]={...pe[A],items:De}}return{...Y,candidates:pe}})}catch{re(l("common.operationFailed"),{type:"error"})}},ge=async A=>{if(window.confirm(l("app.candidate.clearConfirm",{name:A})))try{await se.deleteAllCandidatesInTarget(A),D(),re(l("app.candidate.clearDone",{name:A}))}catch{re(l("common.operationFailed"),{type:"error"})}},Oe=async(A,le)=>{var Y,pe;try{await se.promoteToCandidate(A,A.candidateTargetName||Z||"_review"),re(l("app.candidate.pushSuccess")),y(De=>De.filter((Te,Ee)=>Ee!==le)),D()}catch(De){const Te=(pe=(Y=De.response)==null?void 0:Y.data)==null?void 0:pe.error,Ee=typeof Te=="string"?Te:(Te==null?void 0:Te.message)||l("app.candidate.pushFailed");re(Ee,{type:"error"})}},We=((u==null?void 0:u.recipes)||[]).filter(A=>{var Ee,Me;if(K)return K.some(Se=>Se.metadata.type==="recipe"&&Se.metadata.name===A.name);const le=A.name||"",Y=typeof A.content=="string"?A.content:[(Ee=A.content)==null?void 0:Ee.pattern,(Me=A.content)==null?void 0:Me.markdown].filter(Boolean).join(" "),pe=le.toLowerCase().includes(x.toLowerCase())||Y.toLowerCase().includes(x.toLowerCase())||(A.description||"").toLowerCase().includes(x.toLowerCase());if(be==="All")return pe;const De=Y?Y.match(/category:\s*(.*)/):null,Te=De?De[1].trim():"Utility";return pe&&Te===be}).sort((A,le)=>{var De,Te,Ee,Me;if(K){const Se=((De=K.find(it=>it.metadata.name===A.name))==null?void 0:De.similarity)||0;return(((Te=K.find(it=>it.metadata.name===le.name))==null?void 0:Te.similarity)||0)-Se}const Y=((Ee=A.stats)==null?void 0:Ee.authorityScore)??0;return(((Me=le.stats)==null?void 0:Me.authorityScore)??0)-Y}),Ge=Ct.useMemo(()=>{const A=new Set(S.map(Y=>`${Y.discovererId||""}::${Y.name}`)),le=z.filter(Y=>!A.has(`${Y.discovererId||""}::${Y.name}`));return[...S,...le]},[S,z]),pt=Ge.filter(A=>A.name.toLowerCase().includes(x.toLowerCase())).sort((A,le)=>{const Y=us(A.name),pe=us(le.name);if(Y&&!pe)return 1;if(!Y&&pe)return-1;const De=A.isVirtual?1:0,Te=le.isVirtual?1:0;return De!==Te?De-Te:A.name.localeCompare(le.name)}),Mt=o.useCallback(A=>{P(le=>{if(le.some(pe=>pe.path===A.path))return le;const Y=[...le,A];return u!=null&&u.projectRoot&&localStorage.setItem(`asd:custom-folder-targets:${u.projectRoot}`,JSON.stringify(Y)),Y})},[u==null?void 0:u.projectRoot]),Ft=o.useCallback(A=>{P(le=>{const Y=le.filter(pe=>pe.path!==A);return u!=null&&u.projectRoot&&localStorage.setItem(`asd:custom-folder-targets:${u.projectRoot}`,JSON.stringify(Y)),Y})},[u==null?void 0:u.projectRoot]),zt=Object.values((u==null?void 0:u.candidates)||{}).reduce((A,le)=>A+le.items.length,0),{isDark:$e}=St();return e.jsx(po,{children:e.jsx(Fr,{children:e.jsxs("div",{className:`flex h-screen ${$e?"bg-[#1e1e1e] text-slate-200":"bg-slate-50 text-slate-900"} overflow-hidden font-sans`,children:[e.jsx(rl,{position:"top-center",toastOptions:{duration:5e3,style:{background:"none",padding:0,boxShadow:"none",border:"none"}},containerStyle:{top:24}}),e.jsx(br,{activeTab:n,navigateToTab:k,candidateCount:zt,signalSuggestionCount:ve,currentUser:s.user!=="anonymous"?s.user:void 0,currentRole:s.role,permissionMode:s.mode,onLogout:void 0,collapsed:f,onToggleCollapse:()=>h(A=>!A)}),e.jsxs("main",{className:"flex-1 flex flex-col overflow-hidden relative",children:[e.jsx(_r,{searchQuery:x,setSearchQuery:c,setShowCreateModal:fe,handleSyncSnippets:de,aiConfig:u==null?void 0:u.aiConfig,llmReady:ke,onOpenLlmConfig:()=>ne(!0),onBeforeAiSwitch:r,onAiConfigChange:D,onSemanticSearchResults:A=>{xe(A),n!=="recipes"&&k("recipes")}}),n==="recipes"&&e.jsx($r,{selectedCategory:be,setSelectedCategory:we}),e.jsx("div",{className:`flex-1 ${n==="wiki"?"overflow-hidden":"overflow-y-auto p-8"}`,children:j?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"})}):n==="recipes"?e.jsx(Wr,{recipes:We,openRecipeEdit:b,handleDeleteRecipe:ze,onRefresh:D,idTitleMap:u==null?void 0:u.idTitleMap,currentPage:ye,onPageChange:v,pageSize:ee,onPageSizeChange:A=>{ae(A),v(1)}}):n==="guard"?e.jsx(vn,{onRefresh:D}):n==="skills"?e.jsx(Bn,{onRefresh:D,signalSuggestionCount:ve,onSuggestionCountChange:He}):n==="candidates"?e.jsxs(e.Fragment,{children:[a.session&&e.jsx("div",{className:"mb-4",children:e.jsx(Wn,{session:a.session,isAllDone:a.isAllDone,reviewState:a.reviewState,onDismiss:()=>a.resetSession()})}),e.jsx(ln,{data:u,isShellTarget:us,isSilentTarget:lr,isPendingTarget:rr,handleDeleteCandidate:Ve,onEditRecipe:b,onColdStart:Be,isScanning:H,isBootstrapping:((st=a.session)==null?void 0:st.status)==="running",onRefresh:D,onAuditCandidate:(A,le)=>{var De,Te;const Y=(((De=A.content)==null?void 0:De.pattern)||"").trim(),pe=!!Y&&(()=>{const Ee=Y.split(`
132
+ `).filter(Se=>Se.trim());return Ee.filter(Se=>/^\s*(#{1,6}\s|[-*>]\s|\d+\.\s)/.test(Se)).length<=Ee.length*.3})();y([{...A,mode:pe?"full":"preview",lang:"cn",includeHeaders:!0,difficulty:A.difficulty||A.complexity||"intermediate",authority:((Te=A.stats)==null?void 0:Te.authority)||3,candidateId:A.id,candidateTargetName:le}]),k("spm")},onAuditAllInTarget:(A,le)=>{y(A.map(Y=>{var Te,Ee;const pe=(((Te=Y.content)==null?void 0:Te.pattern)||"").trim(),De=!!pe&&(()=>{const Me=pe.split(`
133
+ `).filter(Ke=>Ke.trim());return Me.filter(Ke=>/^\s*(#{1,6}\s|[-*>]\s|\d+\.\s)/.test(Ke)).length<=Me.length*.3})();return{...Y,mode:De?"full":"preview",lang:"cn",includeHeaders:!0,difficulty:Y.difficulty||Y.complexity||"intermediate",authority:((Ee=Y.stats)==null?void 0:Ee.authority)||3,candidateId:Y.id,candidateTargetName:le}})),k("spm")},handleDeleteAllInTarget:ge})]}):n==="knowledge"?e.jsx($n,{onRefresh:me,idTitleMap:u==null?void 0:u.idTitleMap}):n==="depgraph"?e.jsx(jn,{}):n==="knowledgegraph"?e.jsx(Mn,{}):n==="spm"?e.jsx(mn,{targets:Ge,filteredTargets:pt,selectedTargetName:Z,isScanning:H,scanProgress:R,scanFileList:_,scanResults:N,guardAudit:W,handleScanTarget:Re,handleScanProject:Ye,handleUpdateScanResult:J,handleSaveExtracted:Le,handlePromoteToCandidate:Oe,handleDeleteCandidate:Ve,onEditRecipe:b,isShellTarget:us,recipes:(u==null?void 0:u.recipes)??[],isSavingRecipe:Q,handleRefreshProject:me,onAddCustomFolder:Mt,onRemoveCustomFolder:Ft}):n==="wiki"?e.jsx(lo,{}):n==="help"?e.jsx(Qr,{}):e.jsx(kn,{})}),C&&e.jsx(no,{editingRecipe:C,setEditingRecipe:E,handleSaveRecipe:qe,closeRecipeEdit:B,isSavingRecipe:Q}),ue&&e.jsx(oo,{setShowCreateModal:fe,createPath:he,setCreatePath:ce,handleCreateFromPath:V,handleCreateFromClipboard:Ce,isExtracting:je}),L&&e.jsx(co,{searchQ:L.q,insertPath:L.path,onClose:()=>{T(null),window.history.replaceState({},document.title,window.location.pathname)}}),Ie&&e.jsx(uo,{onClose:()=>ne(!1),onSaved:()=>{te(),D()}})]}),e.jsx(mo,{})]})})})},mo=()=>{const{isOpen:t}=ds();return t?e.jsx(zr,{}):null};nl.createRoot(document.getElementById("root")).render(e.jsx(Ct.StrictMode,{children:e.jsx(Ul,{children:e.jsx(ql,{children:e.jsx(xo,{})})})}));