autosnippet 3.2.8 → 3.2.9

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 (113) hide show
  1. package/bin/cli.js +6 -5
  2. package/dashboard/dist/assets/index-BTAsOZv2.js +128 -0
  3. package/dashboard/dist/assets/index-C_72Ct98.css +1 -0
  4. package/dashboard/dist/index.html +2 -2
  5. package/lib/cli/AiScanService.js +23 -26
  6. package/lib/cli/SetupService.js +1 -1
  7. package/lib/core/AstAnalyzer.js +1 -1
  8. package/lib/core/discovery/index.js +2 -2
  9. package/lib/external/ai/AiProvider.js +66 -172
  10. package/lib/external/ai/providers/GoogleGeminiProvider.js +23 -1
  11. package/lib/external/mcp/handlers/bootstrap/BootstrapSession.js +1 -1
  12. package/lib/external/mcp/handlers/bootstrap/ExternalSubmissionTracker.js +3 -3
  13. package/lib/external/mcp/handlers/bootstrap/MissionBriefingBuilder.js +1 -1
  14. package/lib/external/mcp/handlers/bootstrap/pipeline/IncrementalBootstrap.js +1 -1
  15. package/lib/external/mcp/handlers/bootstrap/pipeline/dimension-context.js +8 -8
  16. package/lib/external/mcp/handlers/bootstrap/pipeline/noAiFallback.js +1 -1
  17. package/lib/external/mcp/handlers/bootstrap/pipeline/orchestrator.js +287 -204
  18. package/lib/external/mcp/handlers/bootstrap/shared/bootstrap-phases.js +7 -6
  19. package/lib/external/mcp/handlers/bootstrap/shared/dimension-sop.js +1 -1
  20. package/lib/external/mcp/handlers/bootstrap-internal.js +2 -2
  21. package/lib/external/mcp/handlers/dimension-complete-external.js +6 -6
  22. package/lib/http/HttpServer.js +1 -1
  23. package/lib/http/middleware/requestLogger.js +1 -0
  24. package/lib/http/routes/ai.js +240 -35
  25. package/lib/http/routes/candidates.js +2 -3
  26. package/lib/http/routes/extract.js +13 -11
  27. package/lib/http/routes/modules.js +2 -2
  28. package/lib/http/routes/recipes.js +9 -5
  29. package/lib/http/routes/remote.js +134 -255
  30. package/lib/http/routes/violations.js +0 -54
  31. package/lib/http/utils/sse-sessions.js +1 -1
  32. package/lib/infrastructure/logging/Logger.js +5 -4
  33. package/lib/infrastructure/monitoring/PerformanceMonitor.js +3 -2
  34. package/lib/injection/ServiceContainer.js +64 -17
  35. package/lib/platform/ScreenCaptureService.js +177 -0
  36. package/lib/platform/ios/routes/spm.js +2 -2
  37. package/lib/service/agent/AgentEventBus.js +207 -0
  38. package/lib/service/agent/AgentFactory.js +490 -0
  39. package/lib/service/agent/AgentMessage.js +240 -0
  40. package/lib/service/agent/AgentRouter.js +228 -0
  41. package/lib/service/agent/AgentRuntime.js +1016 -0
  42. package/lib/service/agent/AgentState.js +217 -0
  43. package/lib/service/agent/IntentClassifier.js +331 -0
  44. package/lib/service/agent/LarkTransport.js +389 -0
  45. package/lib/service/agent/capabilities.js +408 -0
  46. package/lib/service/{chat → agent/context}/ContextWindow.js +37 -12
  47. package/lib/service/{chat → agent/context}/ExplorationTracker.js +25 -14
  48. package/lib/service/{chat → agent/core}/ChatAgentPrompts.js +1 -1
  49. package/lib/service/agent/core/LoopContext.js +170 -0
  50. package/lib/service/agent/core/MessageAdapter.js +223 -0
  51. package/lib/service/agent/core/ToolExecutionPipeline.js +376 -0
  52. package/lib/service/{chat → agent/domain}/ChatAgentTasks.js +19 -98
  53. package/lib/service/{chat → agent/domain}/EpisodicConsolidator.js +7 -7
  54. package/lib/service/{chat → agent/domain}/EvidenceCollector.js +4 -2
  55. package/lib/service/{chat/AnalystAgent.js → agent/domain/insight-analyst.js} +37 -172
  56. package/lib/service/{chat/HandoffProtocol.js → agent/domain/insight-gate.js} +85 -135
  57. package/lib/service/agent/domain/insight-producer.js +267 -0
  58. package/lib/service/agent/domain/scan-prompts.js +105 -0
  59. package/lib/service/agent/forced-summary.js +266 -0
  60. package/lib/service/agent/index.js +91 -0
  61. package/lib/service/{chat → agent}/memory/MemoryCoordinator.js +7 -7
  62. package/lib/service/{chat/ProjectSemanticMemory.js → agent/memory/PersistentMemory.js} +359 -89
  63. package/lib/service/{chat → agent}/memory/SessionStore.js +1 -1
  64. package/lib/service/{chat → agent}/memory/index.js +1 -1
  65. package/lib/service/agent/policies.js +442 -0
  66. package/lib/service/agent/presets.js +303 -0
  67. package/lib/service/agent/strategies.js +717 -0
  68. package/lib/service/{chat → agent/tools}/ToolRegistry.js +3 -3
  69. package/lib/service/agent/tools/ai-analysis.js +75 -0
  70. package/lib/service/{chat → agent}/tools/composite.js +2 -1
  71. package/lib/service/{chat → agent}/tools/guard.js +1 -121
  72. package/lib/service/{chat → agent}/tools/index.js +27 -21
  73. package/lib/service/{chat → agent}/tools/infrastructure.js +1 -1
  74. package/lib/service/agent/tools/knowledge-graph.js +112 -0
  75. package/lib/service/agent/tools/scan-recipe.js +189 -0
  76. package/lib/service/agent/tools/system-interaction.js +476 -0
  77. package/lib/service/automation/DirectiveDetector.js +0 -1
  78. package/lib/service/automation/FileWatcher.js +0 -8
  79. package/lib/service/automation/handlers/CreateHandler.js +7 -3
  80. package/lib/service/automation/handlers/DraftHandler.js +7 -6
  81. package/lib/service/module/ModuleService.js +40 -73
  82. package/lib/service/skills/SignalCollector.js +26 -19
  83. package/lib/service/snippet/codecs/VSCodeCodec.js +1 -1
  84. package/lib/shared/FieldSpec.js +1 -1
  85. package/lib/shared/StyleGuide.js +1 -1
  86. package/package.json +4 -1
  87. package/resources/native-ui/screenshot.swift +228 -0
  88. package/dashboard/dist/assets/index-D5jiDBQG.css +0 -1
  89. package/dashboard/dist/assets/index-e5OKj-Ni.js +0 -128
  90. package/lib/core/discovery/SpmDiscoverer.js +0 -5
  91. package/lib/external/mcp/handlers/bootstrap/pipeline/EpisodicMemory.js +0 -750
  92. package/lib/external/mcp/handlers/bootstrap/pipeline/ToolResultCache.js +0 -277
  93. package/lib/http/routes/spm.js +0 -5
  94. package/lib/infrastructure/external/XcodeAutomation.js +0 -15
  95. package/lib/service/chat/ChatAgent.js +0 -1602
  96. package/lib/service/chat/Memory.js +0 -161
  97. package/lib/service/chat/ProducerAgent.js +0 -431
  98. package/lib/service/chat/ReasoningTrace.js +0 -523
  99. package/lib/service/chat/TaskPipeline.js +0 -357
  100. package/lib/service/chat/WorkingMemory.js +0 -359
  101. package/lib/service/chat/memory/PersistentMemory.js +0 -450
  102. package/lib/service/chat/tools/ai-analysis.js +0 -267
  103. package/lib/service/chat/tools/knowledge-graph.js +0 -234
  104. package/lib/service/chat/tools.js +0 -18
  105. package/lib/service/snippet/PlaceholderConverter.js +0 -5
  106. package/lib/service/snippet/codecs/XcodeCodec.js +0 -5
  107. /package/lib/service/{chat → agent}/ConversationStore.js +0 -0
  108. /package/lib/service/{chat → agent}/memory/ActiveContext.js +0 -0
  109. /package/lib/service/{chat → agent}/tools/_shared.js +0 -0
  110. /package/lib/service/{chat → agent}/tools/ast-graph.js +0 -0
  111. /package/lib/service/{chat → agent}/tools/lifecycle.js +0 -0
  112. /package/lib/service/{chat → agent}/tools/project-access.js +0 -0
  113. /package/lib/service/{chat → agent}/tools/query.js +0 -0
@@ -0,0 +1,128 @@
1
+ import{r as l,j as e,_ as Ga,$ as Wr,a0 as Vr,a1 as Jr,a2 as Yr,a3 as $a,a4 as Qr,a5 as Xr,a6 as Zr,a7 as Ha,a8 as Oa,a9 as Ka,aa as en,ab as tn,ac as qa,ad as Ua,ae as Wa,af as sn,ag as Va,ah as Ja,ai as Ya,aj as Qa,ak as Xa,al as Za,am as er,an,ao as rn,ap as tr,aq as nn,ar as sr,as as ln,at as ar,au as rr,av as on,aw as ct,ax as Pt,ay as cn,az as dn,aA as nr,aB as lr,aC as un,aD as pn}from"./vendor-Ck-HBmg5.js";import{a as ds}from"./axios-C0Zqfgkc.js";import{Z as et,L as Zs,S as mn,B as us,H as ea,C as xn,a as mt,W as gn,G as ta,b as Qe,c as ht,d as Is,e as hn,f as fn,D as or,g as ps,P as bn,h as qt,i as ir,F as Dt,j as it,k as Rs,l as ft,M as It,m as cr,n as vn,o as yn,p as jn,U as dr,q as wn,r as Je,s as kt,X as Xe,t as Pe,u as yt,R as ur,v as rt,w as sa,A as pr,x as Nn,y as Ct,z as Ts,E as Rt,I as jt,J as kn,K as Cn,N as aa,O as Sn,T as mr,Q as Ut,V as Tt,Y as An,_ as xr,$ as Dn,a0 as In,a1 as Rn,a2 as Tn,a3 as Es,a4 as $t,a5 as ot,a6 as Yt,a7 as Ms,a8 as ra,a9 as gr,aa as ls,ab as En,ac as Pn,ad as ga,ae as ha,af as Ln,ag as hr,ah as fa,ai as Ns,aj as Us,ak as Mn,al as ms,am as ks,an as Qt,ao as ba,ap as Xt,aq as Fn,ar as fr,as as Ws,at as Bt,au as zn,av as br,aw as Vs,ax as vr,ay as _n,az as Bn,aA as Js,aB as Gn,aC as na,aD as $n,aE as Hn,aF as On,aG as Kn,aH as qn}from"./icons-pSac4wYO.js";import{A as Un,m as Wn}from"./framer-motion-DOATyqla.js";import"./yaml-qRaU8Ldn.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const n of o)if(n.type==="childList")for(const d of n.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&r(d)}).observe(document,{childList:!0,subtree:!0});function a(o){const n={};return o.integrity&&(n.integrity=o.integrity),o.referrerPolicy&&(n.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?n.credentials="include":o.crossOrigin==="anonymous"?n.credentials="omit":n.credentials="same-origin",n}function r(o){if(o.ep)return;o.ep=!0;const n=a(o);fetch(o.href,n)}})();const Ys={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"},commandPalette:{searchPlaceholder:"搜索知识、命令、页面...",noResults:"没有找到结果",recent:"最近",pages:"页面",commands:"命令"},login:{title:"AutoSnippet",subtitle:"连接开发者、AI 与项目知识库",heading:"登录 Dashboard",username:"用户名",password:"密码",usernamePlaceholder:"输入用户名",passwordPlaceholder:"输入密码",usernameRequired:"请输入用户名",passwordRequired:"请输入密码",loginFailed:"登录失败,请重试",loggingIn:"登录中...",loginBtn:"登录",envHint:"登录功能由 VITE_AUTH_ENABLED 环境变量控制"},pagination:{showing:"显示 {start}-{end},共 {total} 条",perPage:"每页",unit:"条",firstPage:"第一页",prevPage:"上一页",nextPage:"下一页",lastPage:"最后一页"},recipes:{title:"Recipe 知识库",sortNewest:"最新",sortAlpha:"字母",sortQuality:"质量",filterAll:"全部类型",filterSnippet:"仅 Snippet",filterKnowledge:"仅 Knowledge",searchPlaceholder:"搜索 Recipes...",totalCount:"共 {count} 条",noResults:"没有匹配的 Recipe",batchActions:"批量操作",selectAll:"全选",deselectAll:"取消全选",batchDelete:"删除选中",batchDeleteConfirm:"确定删除选中的 {count} 条 Recipe?",batchDeleteDone:"已删除 {count} 条",qualityAuthorityScore:"权威分",qualityExcellent:"优秀",qualityGreat:"Great",qualitySolid:"Solid",qualityGood:"Good",qualityBasic:"基础",knowledgeType:"类型",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 润色",aiEnrich:"AI 补齐",viewDetail:"查看详情",selectAll:"全选",deselectAll:"取消全选",silent:"静默",expandedDetail:"展开详情",collapse:"收起",qualityDimensions:"质量维度",authorityScore:"权威分",trigger:"Trigger",category:"Category",language:"Language",path:"Path",description:"描述",code:"代码",markdown:"Markdown",rationale:"设计原理",tags:"标签",headers:"Headers",confidence:"置信度",source:"来源",createdAt:"创建时间",updatedAt:"更新时间",groupByTarget:"按 Target 分组",clearGroup:"确定移除「{name}」下的全部候选?",clearGroupDone:"已移除 {name} 下的全部候选",coldStartTitle:"冷启动:结构收集 + 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 审查提交",sourceFallbackLabel:"规则降级"},knowledge:{title:"批量管理",lifecycle:"生命周期",lifecycleCandidate:"Candidate",lifecycleRecipe:"Recipe",lifecycleArchived:"Archived",searchPlaceholder:"搜索知识条目...",totalCount:"共 {count} 条",noResults:"无匹配条目",batchActions:"批量操作",batchPromote:"批量晋升",batchDemote:"批量降级",batchArchive:"批量归档",batchDelete:"批量删除",batchDeleteConfirm:"确定删除选中的 {count} 条知识?",batchDeleteDone:"已删除 {count} 条",selectAll:"全选",deselectAll:"取消全选",detail:"知识详情",detailContent:"内容",detailQuality:"质量",detailMeta:"元数据",qualityCompleteness:"完整度",qualityClarity:"清晰度",qualityRelevance:"关联性",qualityAccuracy:"精确度",qualityUsability:"可用性",authorityScore:"权威分",source:"来源",category:"分类",language:"语言",createdAt:"创建时间",updatedAt:"更新时间",path:"路径",trigger:"触发词",lifecyclePending:"待审核",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:"重新打开",aiGenPlaceholder:"例: 禁止在 View 中直接调用网络请求",addRule:"添加规则",refreshAudit:"刷新审计",refreshing:"审计刷新中...",refreshSuccess:"审计已刷新",reportIssue:"提交误报",clearHistory:"清空历史",clearConfirm:"确定清空所有 Guard 违反记录?",addRuleValidation:"请填写规则 ID、说明、正则和至少一种语言",patternLabel:"正则(对每行匹配,JSON 中反斜杠需双写)",languagesLabel:"语言",dimensionLabel:"审查规模",noteLabel:"备注",allLanguages:"所有语言",noMatchingRules:"无匹配规则,请调整筛选条件",violationRecords:"违反记录(共 {runs} 次运行,{count} 处违反)",dimFile:"同文件",dimTarget:"同 target",dimProject:"同项目",rationale:"技术原因",fixSuggestion:"修复建议",sourceRecipe:"来源 Recipe",categorySafety:"安全",categoryCorrectness:"正确性",categoryPerformance:"性能",categoryStyle:"风格",category:"分类",currentProject:"当前项目",dimNoLimit:"不限制",notePlaceholder:"仅作简单模式提示",copyFixSuggestion:"复制修复建议",codeLevelConfigTip:"Code-Level 和 Cross-File 检查(如过度 unwrap、循环 import 等)可通过配置禁用或调整阈值。",codeLevelConfigPath:"配置路径:config/default.json → guard.disabledRules / guard.codeLevelThresholds",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 开发注意事项"},pipelineDescs:{"project-profile":"技术栈、目录结构、三方依赖","objc-deep-scan":"宏定义、静态常量、Method Swizzling","category-scan":"Foundation/UIKit 分类方法清单","code-standard":"命名约定、注释风格、文件组织",architecture:"分层架构、模块职责、依赖关系","code-pattern":"单例、委托、工厂、观察者等模式","event-and-data-flow":"事件传播、数据状态管理","best-practice":"错误处理、并发安全、内存管理","agent-guidelines":"强制规范、废弃 API、架构约束"},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:"✓ 无匹配内容",skillPending:"⏳ Skill 生成中…",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 与项目知识库:TaskGraph 结构化任务 · Guard 代码审查 · Skills 开放平台 · 知识库持续生长",techSpecs:"Node.js ≥ 20 · 11 Skills · 20 MCP 工具 · TaskGraph 任务管理 · VSCode Extension · 4 层检索管线",viewGithub:"查看 GitHub",fullDocs:"完整文档",tokenUsageLast7Days:"Token 用量(近 7 日)",quickStart:"快速开始",coreConcepts:"核心概念",coreFeatures:"核心功能",editorDirectives:"编辑器指令",cursorIntegration:"IDE 集成",v3Architecture:"V3 架构",cliReference:"命令行速查",step1Title:"安装与初始化",step2Title:"启动 Dashboard",step2Desc:"启动 HTTP API + Dashboard + FileWatcher",step3Title:"IDE 集成",step3Desc:"安装 MCP + Skills + Cursor Rules + VSCode Extension",step4Title:"创建第一个 Recipe",step4Desc1:"Dashboard → New Recipe",step4Desc2:"Use Copied Code → AI 填充 → 保存",threeRoles:"三大角色",roleColumn:"角色",responsibilityColumn:"职责",capabilityColumn:"能力",roleDeveloper:"开发者",roleCursorAgent:"IDE 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/VSCode/Xcode",loopStep5:"持续优化",loopStep5Sub:"asd sync",knowledgeBuild:"知识库构建",semanticSearchLabel:"语义检索",codeAudit:"代码审查(Audit)",dataSync:"数据同步",usageExamples:"使用示例",exampleSearchKB:"检索知识库",exampleSearchKBDesc:'对 Cursor 说:"查找网络请求错误处理的代码"',exampleBatchScan:"批量扫描",exampleBatchScanDesc:'对 Cursor 说:"扫描 NetworkModule,生成 Recipes 到候选"',exampleSubmitCode:"提交代码",exampleSubmitCodeDesc:'对 Cursor 说:"把这段代码保存为 Recipe"',skills10:"11 个 Skills",mcp16:"20 个 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:"11 个 Skills 理解规范;20 个 MCP 工具按需检索、提交候选;写操作经 Gateway 审核;VSCode lm.registerTool 深度集成",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>(无参数)→ Mission Briefing + <code class="bg-green-100 px-1 rounded">dimension_complete</code>',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:"AgentRuntime + PipelineStrategy 统一驱动分析与生产",chatAgentCompBullet2:"增强质量门控 + 三态重试/降级 + 轻量记忆持久化",chatAgentCompBullet3:"项目感知:自动注入知识库状态上下文",searchPipelineBullet1:"InvertedIndex → CoarseRanker → MultiSignalRanker → RetrievalFunnel",searchPipelineBullet2:"BM25 + keyword + semantic 三路融合",searchPipelineBullet3:"search MCP 工具:mode 参数路由 auto / keyword / bm25 / semantic / context 五种模式",guardCompBullet1:"内建规则 + 自定义规则 + Recipe 关联",guardCompBullet2:"VSCode 保存时自动检查 → DiagnosticCollection 波浪线 → 灯泡菜单搜索修复",guardCompBullet3:'MCP:<code class="bg-rose-100 px-1 rounded">guard</code>(code=单文件 / files=批量)、<code class="bg-rose-100 px-1 rounded">bootstrap</code>(含 Guard 审计)',kbBuildBullet1:'<strong>AI 扫描</strong>:<code class="bg-slate-100 px-1 rounded text-xs">asd ais [Target]</code> 批量提取',kbBuildBullet2:'<strong>Cursor 扫描</strong>:对 Copilot 说 "扫描 Module"',kbBuildBullet3:"<strong>手动创建</strong>:New Recipe → Use Copied Code",kbBuildBullet4:'<strong>编辑器内</strong>:复制代码 → <code class="bg-slate-100 px-1 rounded text-xs">// as:create -c</code>',semSearchBullet1:"<strong>4 层管线</strong>:InvertedIndex → CoarseRanker → MultiSignalRanker → RetrievalFunnel",semSearchBullet2:'<strong>编辑器内</strong>:<code class="bg-slate-100 px-1 rounded text-xs">// as:search keyword</code>',semSearchBullet3:"<strong>Cursor MCP</strong>:search 统合工具(mode 路由 5 种模式)",semSearchBullet4:"<strong>Dashboard</strong>:搜索框支持语义 + 关键词",auditFeatureBullet1:'<strong>文件审查</strong>:<code class="bg-slate-100 px-1 rounded text-xs">// as:audit</code>',auditFeatureBullet2:'<strong>Target 审查</strong>:<code class="bg-slate-100 px-1 rounded text-xs">// as:audit target</code>',auditFeatureBullet3:'<strong>Guard 审查</strong>:MCP <code class="bg-slate-100 px-1 rounded text-xs">guard</code>(code / files 参数)',auditFeatureBullet4:"<strong>Dashboard</strong>:Guard 页面可视化审查",syncBullet1:'<strong>同步</strong>:<code class="bg-slate-100 px-1 rounded text-xs">asd sync</code> .md → DB(增量)',syncBullet2:'<strong>Hash 校验</strong>:<code class="bg-slate-100 px-1 rounded text-xs">_contentHash</code> 检测手动编辑',syncBullet3:"<strong>向量索引</strong>:启动时自动构建语义索引",syncBullet4:'<strong>依赖图</strong>:<code class="bg-slate-100 px-1 rounded text-xs">structure</code>(operation: targets / files)MCP 工具',coreFeaturesDesc:"覆盖知识采集、智能检索、代码合规、任务编排、文档生成、数据同步六大能力",kbBuildDesc:"多通道采集,AI 驱动的知识库全生命周期管理",semSearchDescShort:"4 层管线融合 BM25 + keyword + semantic 三路信号",guardCompliance:"Guard 合规闭环",guardComplianceDesc:"规则审查 → 诊断波浪线 → 灯泡修复,代码合规闭环",featureTaskGraphTitle:"TaskGraph 任务编排",featureTaskGraphDesc:"DAG 任务图 + tokenBudget 感知,结构化管理复杂工程任务",featureTaskGraphBullet1:"<strong>DAG 模型</strong>:decompose / prime / ready / claim / close 等 15 种操作",featureTaskGraphBullet2:"<strong>tokenBudget 感知</strong>:自动裁剪详情级别(CRITICAL &lt; 5K, WARNING &lt; 20K)",featureTaskGraphBullet3:"<strong>MCP + VSCode</strong>:task 工具 + lm.registerTool 原生集成",featureTaskGraphBullet4:"<strong>Prime 预热</strong>:自动注入 Mission Briefing + 关键上下文",wikiDocGen:"Wiki 文档生成",wikiDocGenDesc:"Agent 驱动的项目文档自动生成与维护",wikiDocBullet1:"<strong>wiki_plan</strong>:扫描项目 → 规划主题 + 数据包",wikiDocBullet2:"<strong>wiki_finalize</strong>:meta.json 汇总 + 去重 + 文件验证",wikiDocBullet3:"<strong>知识聚合</strong>:基于 Recipe 自动生成开发文档",wikiDocBullet4:"<strong>增量更新</strong>:版本追踪 + 差异合并",syncDescShort:"增量同步、Hash 校验、向量索引、依赖图分析",createDirBullet1:"无选项:打开 Dashboard",createDirBullet2:"<code>-c</code>:从剪贴板静默创建",createDirBullet3:"<code>-f</code>:扫描当前文件",searchDirBullet1:"从知识库检索 Recipe/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:"生命周期",skillDevdocs:"开发文档",mcpLayerHeader:"层级",mcpToolHeader:"工具",mcpDescHeader:"说明",mcpAgentLayerHeader:"Agent 层(16 个)— 默认对外暴露",mcpAdminLayerHeader:"Admin 层(4 个)— 需设置 ASD_MCP_TIER=admin",mcpHealthDesc:"服务健康检查",mcpCapabilitiesDesc:"服务能力清单(Agent 自发现)",mcpGuardDesc:"code=单文件审查 / files=批量审查",mcpSubmitDesc:"提交候选 / 批量 / 保存文档",mcpEnrichDesc:"AI 润色 / 校验 / 查重",mcpLifecycleDesc:"批量生命周期操作",mcpSearchDesc:"mode 路由 auto / keyword / bm25 / 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:"无参数,返回 Mission Briefing + 维度任务清单",mcpDimensionCompleteDesc:"维度完成通知 + Checkpoint + Hints 分发",mcpWikiPlanDesc:"文档规划:扫描项目 → 主题 + 数据包",mcpWikiFinalizeDesc:"文档完成:meta.json + 去重 + 文件验证",mcpTaskDesc:"15 种操作:create / ready / claim / close / decompose / prime / stats 等",archBootstrapStep1:"① 项目扫描 → 依赖 / 目录 / 入口分析",archBootstrapStep2:"② AI 批量提取 → Candidate 候选列表",archBootstrapStep3:"③ 审阅 + Promote → Recipe 知识库就绪",archBootstrapNote:"支持 bootstrap → dimension_complete 循环迭代、session 断点续跑",archPipelineL1:"InvertedIndex — 倒排索引快速召回",archPipelineL2:"CoarseRanker — BM25 + TF-IDF 粗排",archPipelineL3:"MultiSignalRanker — 多维信号精排",archPipelineL4:"RetrievalFunnel — 漏斗截断 + 上下文装配",archAnalystAgent:"<strong>Analyze 阶段</strong>:分析用户意图 → 检索知识库 → 给出建议 → 信心信号分级",archProducerAgent:"<strong>Produce 阶段</strong>:格式化知识 → 创建候选 → 执行提交 → 结果聚合",archHandoff:"<strong>QualityGate</strong>:PipelineStrategy 三态门控 (pass/retry/degrade)",archMemory:"<strong>轻量记忆</strong>:跨对话偏好/决策/上下文持久化(JSONL,TTL 过期)",archProjectAware:"<strong>项目感知</strong>:自动注入知识库状态(Recipe 分布、候选积压量、Guard 规则数)",archCliDesc:"asd × 18+ 命令",archMcpDesc:"stdio × 20 工具",archHttpDesc:"Express × 18 路由模块",archSkillsDesc:"11 个 Skills",archVscodeDesc:"lm.registerTool × 深度集成",v3ArchDesc:"从冷启动到知识消费,端到端的 AI 工程化架构",archOverviewLabel:"端到端架构流",archOverviewBootstrap:"冷启动",archOverviewKB:"知识库",archOverviewPipeline:"4 层检索",archOverviewAgent:"ChatAgent",archOverviewTask:"TaskGraph",archOverviewOutput:"输出",archOverviewSecurity:"Constitution / Gateway 安全保障层",archOverviewIDE:"IDE 集成层(MCP + Skills + Extension)",ideIntegrationLabel:"IDE 集成",ideIntegrationDesc:"多通道接入 IDE,深度融合开发流程",ideIntegrationBullet1:"<strong>MCP Server</strong>:20 个工具 + Skills 自动发现",ideIntegrationBullet2:"<strong>VSCode Extension</strong>:lm.registerTool + Guard Diagnostics + CodeLens",ideIntegrationBullet3:'<strong>Editor Directives</strong>:<code class="bg-slate-100 px-1 rounded text-xs">// as:search</code> / <code class="bg-slate-100 px-1 rounded text-xs">as:create</code> / <code class="bg-slate-100 px-1 rounded text-xs">as:audit</code>',securityLabel:"安全与权限",securityDesc:"三层权限架构 + 宪法治理,约束 AI 操作边界",securityBullet1:"<strong>Constitution 宪法</strong>:YAML 定义角色 + 权限矩阵 + 治理规则",securityBullet2:"<strong>Gateway 拦截</strong>:MCP 写操作统一校验,AI 不能直接修改 Recipe",securityBullet3:'<strong>审计追踪</strong>:全链路操作日志 + <code class="bg-slate-100 px-1 rounded text-xs">checkWriteSafety</code> 文件保护',constitutionSecurity:"Constitution / Gateway 安全模型",constitutionSecurityDesc:"三重安全保障:权限校验 + 宪法规则 + 审计追踪",archConstitutionBullet1:"<strong>Gateway 权限</strong>:MCP 写操作经 Gateway 层统一拦截",archConstitutionBullet2:"<strong>Constitution 宪法</strong>:YAML 定义的行为准则,约束 AI 操作边界",archConstitutionBullet3:"<strong>审计日志</strong>:全链路操作可追溯,异常自动报警",archConstitutionBullet4:"<strong>Tier 隔离</strong>:Agent / Admin 分层,敏感操作需提升权限",archTaskGraphTitle:"TaskGraph 任务体系",archTaskGraphDesc:"DAG 有向无环图驱动的结构化任务管理:",archTaskGraphBullet1:"<strong>Task DAG</strong>:依赖关系建模 → 拓扑排序 → 并行调度",archTaskGraphBullet2:"<strong>状态机</strong>:pending → ready → claimed → done,自动流转",archTaskGraphBullet3:"<strong>tokenBudget</strong>:剩余 token 感知,智能裁剪任务详情",archTaskGraphBullet4:"<strong>Session 持久化</strong>:断点续跑 + 进度可视化",cliSetupDesc:"初始化项目",cliStatusDesc:"环境自检",cliUiDesc:"启动 Dashboard",cliUpgradeDesc:"升级 IDE 集成",cliSyncDesc:".md → DB 增量同步",cliAisDesc:"AI 扫描提取 Candidates",cliAisForceDesc:"强制重新扫描全量",cliWatchDesc:"文件监控 + 指令触发",cliSearchDesc:"搜索知识库",cliSearchSemanticDesc:"语义搜索模式",cliGuardDesc:"Guard 规则检查",cliServerDesc:"单独启动 API 服务",cliUpgradeMcpDesc:"升级 MCP / Skills / Rules",cliInstallFullDesc:"全量安装 IDE 集成",cliSyncForceDesc:"全量重建 DB",cliSyncDryDesc:"预览同步变更",taskGraphLabel:"TaskGraph(任务图)",taskGraphDesc:"结构化任务生命周期管理引擎",taskGraphBullet1:"create / claim / close / decompose 等 15 种操作",taskGraphBullet2:"依赖图谱 + ready 队列自动计算 + prime 上下文恢复",taskGraphBullet3:'MCP:<code class="bg-cyan-100 px-1 rounded">task</code>(15 种 operation 统合)',vscodeExtension:"VSCode Extension",vscodeExtDesc:"基于 lm.registerTool API 的原生 Copilot 深度集成",vscodeExtTaskTool:"TaskGraph 代理工具",vscodeExtTaskToolDesc:"通过 tokenBudget 感知实现 WARNING / CRITICAL 分级保护,CRITICAL 时自动内联 prime 数据",vscodeExtGuardDiag:"保存时 Guard 自动检查",vscodeExtGuardDiagDesc:"onDidSave → Guard API → DiagnosticCollection 波浪线标记 + 灯泡菜单搜索修复",vscodeExtCodeLens:"指令检测 CodeLens",vscodeExtCodeLensDesc:"检测 // as:search / // as:create 等指令,提供可视化操作按钮",vscodeExtCmd1:"autosnippet.search — 搜索知识库(Cmd+Shift+F5)",vscodeExtCmd2:"autosnippet.create — 从选区创建候选",vscodeExtCmd3:"autosnippet.audit — 审计当前文件",vscodeExtCmd4:"autosnippet.auditProject — 审计整个项目",vscodeExtCmd5:"autosnippet.status — 显示连接状态",cliColdstartAndScan:"冷启动与扫描",cliTaskManagement:"任务管理",cliGuardCi:"Guard CI/CD",cliColdstartDesc:"9 维度冷启动知识库",cliGuardCiDesc:"CI/CD 全项目 Guard 检查",cliGuardStagedDesc:"Git staged 文件检查",cliCursorRulesDesc:"生成 Cursor 多通道交付物料",cliMirrorDesc:"镜像到 .qoder / .trae",cliTaskListDesc:"列出任务图谱",cliTaskReadyDesc:"就绪任务 + 知识上下文",cliTaskPrimeDesc:"恢复会话上下文",cliTaskStatsDesc:"任务统计"},moduleExplorer:{title:"Module Explorer",scanTargets:"扫描 Targets",scanning:"扫描中...",scanComplete:"扫描完成",targetFiles:"{count} 个文件",noTargets:"未发现 Target",recipesInTarget:"关联 Recipes",guardSummary:"Guard 概况",guardViolations:"{count} 项违规",noViolations:"无违规",openFile:"打开文件",refreshTree:"刷新文件树",extractFromFile:"提取代码",fileDetail:"文件详情",projectModules:"项目模块 ({count})",addFolderScan:"添加目录扫描",refreshProject:"刷新项目结构",discovererFolderScan:"目录扫描",removeFolder:"移除此目录",fullProjectResults:"全项目扫描结果",moduleLabel:"模块: {name}",reviewResults:"审核提取结果",resultsCount:"{count} 条",candidateSuffix:" Candidate",fullProjectScanning:"全项目扫描中",moduleScanLabel:"模块扫描: {name}",filesInScan:"本次扫描的文件 ({count})",knowledgeExtract:"知识提取",knowledgeExtractHint:"在左侧选择模块扫描,或点击 + 添加任意目录。提取代码模式并生成 Recipe 知识卡片。",guardAuditSummary:"Guard 审计摘要",auditedFiles:"已审计文件:",totalViolationsLabel:"违反总数:",errorsCount:"{count} 错误",warningsCount:"{count} 警告",recipeNotExist:"「{name}」不存在于当前知识库",recipeNotExistTitle:"Recipe 不存在",loadRecipeFailed:"加载 Recipe 失败",browseFailedTitle:"目录浏览失败",browseFailedDefault:"无法加载目录列表",selectFolderTitle:"选择要扫描的目录",scanningDirs:"正在扫描项目目录...",noDirs:"未发现可扫描的目录",sourceFileCount:"{count} 文件",selectFolderHint:"选择包含源码文件的目录,系统将自动检测语言并执行 AI 扫描",modulesTabLabel:"模块 ({count})",foldersTabLabel:"目录"},search:{title:"智能搜索",searchPlaceholder:"输入搜索关键词...",noResults:"未找到匹配结果",resultCount:"找到 {count} 条结果",relevance:"相关度",source:"来源",category:"分类",language:"语言",matchType:"匹配类型",matchExact:"精确",matchFuzzy:"模糊",matchSemantic:"语义匹配",matchKeyword:"关键词匹配",viewRecipe:"查看 Recipe",insertCode:"插入代码",searchFailed:"搜索失败。请重试。",searching:"搜索中...",searchBtn:"搜索",emptyHint:"输入关键词后点击搜索",contextRelevant:"上下文相关",authorityScore:"权威分",usage:"使用",usageCount:"{count}次",recommendReason:"推荐理由",viewFullContent:"查看完整内容",similarity:"相似度",quality:"质量",noContent:"无内容",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:"知识库概览",analyze_code:"分析代码",enrich_candidate:"丰富候选内容",refine_bootstrap_candidates:"润色候选批次",check_duplicate:"查重检测",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:"查询违规记录",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"}},Vn={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 / 中"},commandPalette:{searchPlaceholder:"Search knowledge, commands, pages...",noResults:"No results found",recent:"Recent",pages:"Pages",commands:"Commands"},login:{title:"AutoSnippet",subtitle:"Connect developers, AI & project knowledge",heading:"Sign in to Dashboard",username:"Username",password:"Password",usernamePlaceholder:"Enter username",passwordPlaceholder:"Enter password",usernameRequired:"Username is required",passwordRequired:"Password is required",loginFailed:"Login failed, please try again",loggingIn:"Signing in...",loginBtn:"Sign in",envHint:"Authentication is controlled by the VITE_AUTH_ENABLED environment variable"},pagination:{showing:"Showing {start}-{end} of {total}",perPage:"Per page",unit:"",firstPage:"First page",prevPage:"Previous page",nextPage:"Next page",lastPage:"Last page"},recipes:{title:"Recipe Knowledge Base",sortNewest:"Newest",sortAlpha:"A-Z",sortQuality:"Quality",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",aiEnrich:"AI Enrich",viewDetail:"View Detail",selectAll:"Select all",deselectAll:"Deselect all",silent:"Silent",expandedDetail:"Expanded Detail",collapse:"Collapse",qualityDimensions:"Quality Dimensions",authorityScore:"Authority",trigger:"Trigger",category:"Category",language:"Language",path:"Path",description:"Description",code:"Code",markdown:"Markdown",rationale:"Rationale",tags:"Tags",headers:"Headers",confidence:"Confidence",source:"Source",createdAt:"Created",updatedAt:"Updated",groupByTarget:"Group by Target",clearGroup:'Remove all candidates under "{name}"?',clearGroupDone:"Removed all candidates under {name}",coldStartTitle:"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",sourceFallbackLabel:"Rule Fallback"},knowledge:{title:"Batch Management",lifecycle:"Lifecycle",lifecycleCandidate:"Candidate",lifecycleRecipe:"Recipe",lifecycleArchived:"Archived",searchPlaceholder:"Search knowledge entries...",totalCount:"{count} total",noResults:"No matching entries",batchActions:"Batch Actions",batchPromote:"Promote",batchDemote:"Demote",batchArchive:"Archive",batchDelete:"Delete",batchDeleteConfirm:"Delete {count} selected entries?",batchDeleteDone:"{count} deleted",selectAll:"Select all",deselectAll:"Deselect all",detail:"Detail",detailContent:"Content",detailQuality:"Quality",detailMeta:"Metadata",qualityCompleteness:"Completeness",qualityClarity:"Clarity",qualityRelevance:"Relevance",qualityAccuracy:"Accuracy",qualityUsability:"Usability",authorityScore:"Authority",source:"Source",category:"Category",language:"Language",createdAt:"Created",updatedAt:"Updated",path:"Path",trigger:"Trigger",lifecyclePending:"Pending",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",aiGenPlaceholder:"e.g. Disallow direct network calls in Views",addRule:"Add Rule",refreshAudit:"Refresh Audit",refreshing:"Refreshing audit...",refreshSuccess:"Audit refreshed",reportIssue:"Report false positive",clearHistory:"Clear History",clearConfirm:"Are you sure to clear all Guard violation records?",addRuleValidation:"Please fill in rule ID, message, regex and at least one language",patternLabel:"Regex (matched per line)",languagesLabel:"Languages",dimensionLabel:"Audit Scope",noteLabel:"Note",allLanguages:"All Languages",noMatchingRules:"No matching rules, adjust filters",violationRecords:"Violations ({runs} runs, {count} violations)",dimFile:"Same file",dimTarget:"Same target",dimProject:"Same project",rationale:"Rationale",fixSuggestion:"Fix suggestion",sourceRecipe:"Source Recipe",categorySafety:"Safety",categoryCorrectness:"Correctness",categoryPerformance:"Performance",categoryStyle:"Style",category:"Category",currentProject:"Current project",dimNoLimit:"No limit",notePlaceholder:"Simple pattern hint only",copyFixSuggestion:"Copy fix suggestion",codeLevelConfigTip:"Code-Level and Cross-File checks (e.g. excessive unwrap, circular import) can be disabled or threshold-adjusted via config.",codeLevelConfigPath:"Config path: config/default.json → guard.disabledRules / guard.codeLevelThresholds",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"},pipelineDescs:{"project-profile":"Tech stack, directory structure, dependencies","objc-deep-scan":"Macros, static constants, Method Swizzling","category-scan":"Foundation/UIKit category methods","code-standard":"Naming conventions, comments, file organization",architecture:"Layered architecture, module boundaries, deps","code-pattern":"Singleton, delegate, factory, observer patterns","event-and-data-flow":"Event propagation, state management","best-practice":"Error handling, concurrency, memory mgmt","agent-guidelines":"Mandatory rules, deprecated APIs, constraints"},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",skillPending:"⏳ Generating Skill…",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: TaskGraph structured tasks · Guard code review · Skills open platform · Knowledge base continuous growth",techSpecs:"Node.js ≥ 20 · 11 Skills · 20 MCP Tools · TaskGraph Management · VSCode Extension · 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:"IDE Integration",v3Architecture:"V3 Architecture",cliReference:"CLI Quick Reference",step1Title:"Install & Initialize",step2Title:"Start Dashboard",step2Desc:"Start HTTP API + Dashboard + FileWatcher",step3Title:"IDE Integration",step3Desc:"Install MCP + Skills + Cursor Rules + VSCode Extension",step4Title:"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:"IDE Agent",roleChatAgent:"ChatAgent",developerResp:"Review & decide, maintain project standards",cursorAgentResp:"Generate code per standards, search knowledge base, manage tasks",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/VSCode/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:"11 Skills",mcp16:"20 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:"Six Entry Channels",initAndEnv:"Init & Environment",kbManagement:"Knowledge Base Management",searchAndAudit:"Search & Audit",maintenanceUpgrade:"Maintenance & Upgrade",footerHint:"Need more details? Check {link} or run {cmd} to verify your environment",footerGithubReadme:"GitHub README",mcpWriteNote:"Write tools (submit_knowledge, guard, bootstrap, etc.) are protected by Gateway permissions / constitution / audit triple protection.",editorDirectivesNote:"Requires asd watch or asd ui running; supports shortcuts asc / ass / asa",createDirective:"Create Recipe/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:"11 Skills understand conventions; 20 MCP tools for on-demand retrieval & candidate submission; writes go through Gateway review; VSCode lm.registerTool deep integration",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> (no params) → Mission Briefing + <code class="bg-green-100 px-1 rounded">dimension_complete</code>',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:"AgentRuntime + PipelineStrategy unified analysis & production",chatAgentCompBullet2:"Enhanced quality gate + tri-state retry/degrade + 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 / bm25 / semantic / context five modes",guardCompBullet1:"Built-in rules + custom rules + Recipe association",guardCompBullet2:"VSCode auto-check on save → DiagnosticCollection squiggles → lightbulb menu search fix",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> (includes Guard audit)',kbBuildBullet1:'<strong>AI Scan</strong>: <code class="bg-slate-100 px-1 rounded text-xs">asd ais [Target]</code> batch extraction',kbBuildBullet2:'<strong>Cursor Scan</strong>: Tell Copilot "scan Module"',kbBuildBullet3:"<strong>Manual Create</strong>: New Recipe → Use Copied Code",kbBuildBullet4:'<strong>In Editor</strong>: Copy code → <code class="bg-slate-100 px-1 rounded text-xs">// as:create -c</code>',semSearchBullet1:"<strong>4-Layer Pipeline</strong>: InvertedIndex → CoarseRanker → MultiSignalRanker → RetrievalFunnel",semSearchBullet2:'<strong>In Editor</strong>: <code class="bg-slate-100 px-1 rounded text-xs">// as:search keyword</code>',semSearchBullet3:"<strong>Cursor MCP</strong>: search unified tool (mode routes 5 modes)",semSearchBullet4:"<strong>Dashboard</strong>: Search box supports semantic + keyword",auditFeatureBullet1:'<strong>File Audit</strong>: <code class="bg-slate-100 px-1 rounded text-xs">// as:audit</code>',auditFeatureBullet2:'<strong>Target Audit</strong>: <code class="bg-slate-100 px-1 rounded text-xs">// as:audit target</code>',auditFeatureBullet3:'<strong>Guard Audit</strong>: MCP <code class="bg-slate-100 px-1 rounded text-xs">guard</code> (code / files param)',auditFeatureBullet4:"<strong>Dashboard</strong>: Guard page visual audit",syncBullet1:'<strong>Sync</strong>: <code class="bg-slate-100 px-1 rounded text-xs">asd sync</code> .md → DB (incremental)',syncBullet2:'<strong>Hash Check</strong>: <code class="bg-slate-100 px-1 rounded text-xs">_contentHash</code> detect manual edits',syncBullet3:"<strong>Vector Index</strong>: Auto-build semantic index on startup",syncBullet4:'<strong>Dependency Graph</strong>: <code class="bg-slate-100 px-1 rounded text-xs">structure</code> (operation: targets / files) MCP tool',coreFeaturesDesc:"Six key capabilities: knowledge collection, intelligent search, code compliance, task orchestration, document generation, and data sync",kbBuildDesc:"Multi-channel collection, AI-driven full lifecycle knowledge base management",semSearchDescShort:"4-layer pipeline fusing BM25 + keyword + semantic triple signals",guardCompliance:"Guard Compliance Loop",guardComplianceDesc:"Rule audit → diagnostic squiggles → lightbulb fix, closed-loop compliance",featureTaskGraphTitle:"TaskGraph Orchestration",featureTaskGraphDesc:"DAG task graph + tokenBudget awareness, structured complex task management",featureTaskGraphBullet1:"<strong>DAG Model</strong>: decompose / prime / ready / claim / close — 15 operations",featureTaskGraphBullet2:"<strong>tokenBudget Aware</strong>: auto-trim detail levels (CRITICAL &lt; 5K, WARNING &lt; 20K)",featureTaskGraphBullet3:"<strong>MCP + VSCode</strong>: task tool + lm.registerTool native integration",featureTaskGraphBullet4:"<strong>Prime Warmup</strong>: auto-inject Mission Briefing + key context",wikiDocGen:"Wiki Doc Generation",wikiDocGenDesc:"Agent-driven automatic project documentation generation & maintenance",wikiDocBullet1:"<strong>wiki_plan</strong>: Scan project → plan topics + data packages",wikiDocBullet2:"<strong>wiki_finalize</strong>: meta.json aggregation + dedup + file validation",wikiDocBullet3:"<strong>Knowledge Aggregation</strong>: Auto-generate dev docs from Recipes",wikiDocBullet4:"<strong>Incremental Update</strong>: Version tracking + diff merging",syncDescShort:"Incremental sync, hash check, vector index, dependency graph analysis",createDirBullet1:"No options: open Dashboard",createDirBullet2:"<code>-c</code>: silently create from clipboard",createDirBullet3:"<code>-f</code>: scan current file",searchDirBullet1:"Retrieve Recipe/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",skillDevdocs:"Dev Docs",mcpLayerHeader:"Layer",mcpToolHeader:"Tool",mcpDescHeader:"Description",mcpAgentLayerHeader:"Agent Layer (16) — 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 / bm25 / 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:"No params — returns Mission Briefing + dimension task list",mcpDimensionCompleteDesc:"Dimension complete notification + Checkpoint + Hints dispatch",mcpWikiPlanDesc:"Document planning: scan project → topics + data packages",mcpWikiFinalizeDesc:"Document finalization: meta.json + dedup + file validation",mcpTaskDesc:"15 operations: create / ready / claim / close / decompose / prime / stats etc.",archBootstrapStep1:"① Project scan → dependency / directory / entry analysis",archBootstrapStep2:"② AI batch extraction → Candidate list",archBootstrapStep3:"③ Review + Promote → Recipe knowledge base ready",archBootstrapNote:"Supports bootstrap → dimension_complete loop iteration & session resume from breakpoint",archPipelineL1:"InvertedIndex — inverted index fast recall",archPipelineL2:"CoarseRanker — BM25 + TF-IDF coarse ranking",archPipelineL3:"MultiSignalRanker — multi-dimensional signal fine ranking",archPipelineL4:"RetrievalFunnel — funnel truncation + context assembly",archAnalystAgent:"<strong>Analyze Stage</strong>: Analyze user intent → retrieve knowledge base → provide suggestions → confidence signal grading",archProducerAgent:"<strong>Produce Stage</strong>: Format knowledge → create candidates → execute submissions → aggregate results",archHandoff:"<strong>QualityGate</strong>: PipelineStrategy tri-state gate (pass/retry/degrade)",archMemory:"<strong>Lightweight Memory</strong>: Cross-conversation preference/decision/context persistence (JSONL, TTL expiry)",archProjectAware:"<strong>Project-Aware</strong>: Auto-inject knowledge base state (Recipe distribution, candidate backlog, Guard rule count)",archCliDesc:"asd × 18+ commands",archMcpDesc:"stdio × 20 tools",archHttpDesc:"Express × 18 route modules",archSkillsDesc:"11 Skills",archVscodeDesc:"lm.registerTool × deep integration",v3ArchDesc:"End-to-end AI engineering architecture from cold start to knowledge consumption",archOverviewLabel:"End-to-End Architecture Flow",archOverviewBootstrap:"Cold Start",archOverviewKB:"Knowledge Base",archOverviewPipeline:"4-Layer Search",archOverviewAgent:"ChatAgent",archOverviewTask:"TaskGraph",archOverviewOutput:"Output",archOverviewSecurity:"Constitution / Gateway Security Layer",archOverviewIDE:"IDE Integration Layer (MCP + Skills + Extension)",ideIntegrationLabel:"IDE Integration",ideIntegrationDesc:"Multi-channel IDE access, deeply integrated into dev workflow",ideIntegrationBullet1:"<strong>MCP Server</strong>: 20 tools + Skills auto-discovery",ideIntegrationBullet2:"<strong>VSCode Extension</strong>: lm.registerTool + Guard Diagnostics + CodeLens",ideIntegrationBullet3:'<strong>Editor Directives</strong>: <code class="bg-slate-100 px-1 rounded text-xs">// as:search</code> / <code class="bg-slate-100 px-1 rounded text-xs">as:create</code> / <code class="bg-slate-100 px-1 rounded text-xs">as:audit</code>',securityLabel:"Security & Permissions",securityDesc:"3-layer permission architecture + constitution governance, constraining AI boundaries",securityBullet1:"<strong>Constitution</strong>: YAML-defined roles + permission matrix + governance rules",securityBullet2:"<strong>Gateway Interception</strong>: Unified MCP write-op validation, AI cannot modify Recipes directly",securityBullet3:'<strong>Audit Trail</strong>: Full-chain operation logs + <code class="bg-slate-100 px-1 rounded text-xs">checkWriteSafety</code> file protection',constitutionSecurity:"Constitution / Gateway Security",constitutionSecurityDesc:"Triple security: permission check + constitution rules + audit trail",archConstitutionBullet1:"<strong>Gateway Permission</strong>: MCP write ops intercepted by Gateway layer",archConstitutionBullet2:"<strong>Constitution</strong>: YAML-defined behavioral rules constraining AI operation boundaries",archConstitutionBullet3:"<strong>Audit Log</strong>: Full-chain operation traceability, auto-alert on anomalies",archConstitutionBullet4:"<strong>Tier Isolation</strong>: Agent / Admin layered, sensitive ops require escalation",archTaskGraphTitle:"TaskGraph System",archTaskGraphDesc:"DAG-driven structured task management:",archTaskGraphBullet1:"<strong>Task DAG</strong>: Dependency modeling → topological sort → parallel scheduling",archTaskGraphBullet2:"<strong>State Machine</strong>: pending → ready → claimed → done, auto-transition",archTaskGraphBullet3:"<strong>tokenBudget</strong>: Remaining token aware, intelligent task detail trimming",archTaskGraphBullet4:"<strong>Session Persistence</strong>: Resume from breakpoint + progress visualization",cliSetupDesc:"Initialize project",cliStatusDesc:"Environment check",cliUiDesc:"Start Dashboard",cliUpgradeDesc:"Upgrade IDE integration",cliSyncDesc:".md → DB incremental sync",cliAisDesc:"AI scan extract Candidates",cliAisForceDesc:"Force full rescan",cliWatchDesc:"File watch + directive trigger",cliSearchDesc:"Search knowledge base",cliSearchSemanticDesc:"Semantic search mode",cliGuardDesc:"Guard rule check",cliServerDesc:"Start API server only",cliUpgradeMcpDesc:"Upgrade MCP / Skills / Rules",cliInstallFullDesc:"Full IDE integration install",cliSyncForceDesc:"Full DB rebuild",cliSyncDryDesc:"Preview sync changes",taskGraphLabel:"TaskGraph",taskGraphDesc:"Structured task lifecycle management engine",taskGraphBullet1:"create / claim / close / decompose and 15 total operations",taskGraphBullet2:"Dependency graph + ready queue auto-computation + prime context restore",taskGraphBullet3:'MCP: <code class="bg-cyan-100 px-1 rounded">task</code> (15 unified operations)',vscodeExtension:"VSCode Extension",vscodeExtDesc:"Native Copilot deep integration via lm.registerTool API",vscodeExtTaskTool:"TaskGraph Proxy Tool",vscodeExtTaskToolDesc:"tokenBudget-aware WARNING / CRITICAL tiered protection; auto-inlines prime data at CRITICAL level",vscodeExtGuardDiag:"Guard Check on Save",vscodeExtGuardDiagDesc:"onDidSave → Guard API → DiagnosticCollection squiggles + lightbulb menu search fix",vscodeExtCodeLens:"Directive CodeLens",vscodeExtCodeLensDesc:"Detects // as:search / // as:create directives and provides visual action buttons",vscodeExtCmd1:"autosnippet.search — Search knowledge base (Cmd+Shift+F5)",vscodeExtCmd2:"autosnippet.create — Create candidate from selection",vscodeExtCmd3:"autosnippet.audit — Audit current file",vscodeExtCmd4:"autosnippet.auditProject — Audit entire project",vscodeExtCmd5:"autosnippet.status — Show connection status",cliColdstartAndScan:"Cold Start & Scan",cliTaskManagement:"Task Management",cliGuardCi:"Guard CI/CD",cliColdstartDesc:"9-dimension cold start knowledge base",cliGuardCiDesc:"CI/CD full project Guard check",cliGuardStagedDesc:"Git staged files Guard check",cliCursorRulesDesc:"Generate Cursor multi-channel delivery",cliMirrorDesc:"Mirror to .qoder / .trae",cliTaskListDesc:"List task graph",cliTaskReadyDesc:"Ready tasks + knowledge context",cliTaskPrimeDesc:"Restore session context",cliTaskStatsDesc:"Task statistics"},moduleExplorer:{title:"Module Explorer",scanTargets:"Scan Targets",scanning:"Scanning...",scanComplete:"Scan complete",targetFiles:"{count} files",noTargets:"No Targets found",recipesInTarget:"Related Recipes",guardSummary:"Guard Summary",guardViolations:"{count} violations",noViolations:"No violations",openFile:"Open file",refreshTree:"Refresh file tree",extractFromFile:"Extract code",fileDetail:"File Detail",projectModules:"Project Modules ({count})",addFolderScan:"Add folder scan",refreshProject:"Refresh project structure",discovererFolderScan:"Folder Scan",removeFolder:"Remove this folder",fullProjectResults:"Full project scan results",moduleLabel:"Module: {name}",reviewResults:"Review extraction results",resultsCount:"{count} items",candidateSuffix:" Candidate",fullProjectScanning:"Full project scanning",moduleScanLabel:"Module scan: {name}",filesInScan:"Scanned files ({count})",knowledgeExtract:"Knowledge Extraction",knowledgeExtractHint:"Select a module on the left to scan, or click + to add a folder. Extract code patterns and generate Recipe knowledge cards.",guardAuditSummary:"Guard Audit Summary",auditedFiles:"Audited files:",totalViolationsLabel:"Total violations:",errorsCount:"{count} errors",warningsCount:"{count} warnings",recipeNotExist:'"{name}" does not exist in the current knowledge base',recipeNotExistTitle:"Recipe not found",loadRecipeFailed:"Failed to load Recipe",browseFailedTitle:"Browse folder failed",browseFailedDefault:"Unable to load directory listing",selectFolderTitle:"Select folder to scan",scanningDirs:"Scanning project directories...",noDirs:"No scannable directories found",sourceFileCount:"{count} files",selectFolderHint:"Select a folder with source files. Language will be auto-detected and AI scan will run.",modulesTabLabel:"Modules ({count})",foldersTabLabel:"Folders"},search:{title:"Smart Search",searchPlaceholder:"Enter search keywords...",noResults:"No matching results",resultCount:"{count} results found",relevance:"Relevance",source:"Source",category:"Category",language:"Language",matchType:"Match Type",matchExact:"Exact",matchFuzzy:"Fuzzy",matchSemantic:"Semantic Match",matchKeyword:"Keyword Match",viewRecipe:"View Recipe",insertCode:"Insert Code",searchFailed:"Search failed. Please try again.",searching:"Searching...",searchBtn:"Search",emptyHint:"Enter keywords and click Search",contextRelevant:"Context Relevant",authorityScore:"Authority",usage:"Usage",usageCount:"{count} times",recommendReason:"Recommendation Reason",viewFullContent:"View Full Content",similarity:"Similarity",quality:"Quality",noContent:"No content",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:"Description",code:"Code / Standard Usage",markdown:"Markdown Document",rationale:"Design Rationale",tags:"Tags",confidence:"Confidence",aiInsights:"AI Insights",agentNotes:"Agent Notes",relations:"Relations"},diff:{noChanges:"No changes detected",excludedRestore:"Excluded · Restore",exclude:"Exclude",before:"Before",after:"After",empty:"(empty)"},system:{refinePrefix:`🎯 Refine Mode — **{title}**
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",analyze_code:"Analyze code",enrich_candidate:"Enrich candidate",refine_bootstrap_candidates:"Refine candidates",check_duplicate:"Check duplicate",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",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"}},va={zh:Ys,en:Vn},Cs="asd-dashboard-lang";function Jn(){try{const t=localStorage.getItem(Cs);if(t==="en"||t==="zh")return t}catch{}return"zh"}function ya(t,s){const a=s.split(".");let r=t;for(const o of a){if(r==null||typeof r!="object")return;r=r[o]}return typeof r=="string"?r:void 0}function Yn(t,s){return s?t.replace(/\{(\w+)\}/g,(a,r)=>{const o=s[r];return o!=null?String(o):`{${r}}`}):t}const yr=l.createContext(null);function Qn({children:t}){const[s,a]=l.useState(Jn);l.useEffect(()=>{const d=localStorage.getItem(Cs);d==="en"||d==="zh"?fetch("/api/v1/ai/lang",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lang:d})}).catch(()=>{}):fetch("/api/v1/ai/lang").then(u=>u.json()).then(u=>{var x;const c=(x=u==null?void 0:u.data)==null?void 0:x.lang;if(c==="en"||c==="zh"){a(c);try{localStorage.setItem(Cs,c)}catch{}}}).catch(()=>{})},[]);const r=l.useCallback(d=>{a(d);try{localStorage.setItem(Cs,d)}catch{}fetch("/api/v1/ai/lang",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lang:d})}).catch(()=>{})},[]),o=l.useCallback((d,u)=>{const c=ya(va[s],d)??ya(va.zh,d)??d;return Yn(c,u)},[s]),n=l.useMemo(()=>({lang:s,setLang:r,t:o}),[s,r,o]);return e.jsx(yr.Provider,{value:n,children:t})}function Me(){const t=l.useContext(yr);if(!t)throw new Error("useI18n must be used within <I18nProvider>");return t}const jr="asd-dashboard-theme";function Xn(){return typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches}function Zn(){try{const t=localStorage.getItem(jr);if(t==="light"||t==="dark"||t==="system")return t}catch{}return"system"}const wr=l.createContext(null);function el({children:t}){const[s,a]=l.useState(Zn),[r,o]=l.useState(Xn);l.useEffect(()=>{const x=window.matchMedia("(prefers-color-scheme: dark)"),v=g=>o(g.matches);return x.addEventListener("change",v),()=>x.removeEventListener("change",v)},[]);const n=s==="dark"?!0:s==="light"?!1:r;l.useEffect(()=>{const x=document.documentElement;n?x.classList.add("dark"):x.classList.remove("dark")},[n]);const d=l.useCallback(x=>{a(x);try{localStorage.setItem(jr,x)}catch{}},[]),u=l.useCallback(()=>{d(n?"light":"dark")},[n,d]),c=l.useMemo(()=>({isDark:n,mode:s,toggle:u,setTheme:d}),[n,s,u,d]);return e.jsx(wr.Provider,{value:c,children:t})}function Fs(){const t=l.useContext(wr);if(!t)throw new Error("useTheme must be used within <ThemeProvider>");return t}const tl="AutoSnippet";function sl(t){if(typeof window>"u"||!("Notification"in window))return;const s=()=>{try{new Notification(tl,{body:t,tag:"autosnippet"})}catch{}};if(Notification.permission==="granted"){s();return}Notification.permission!=="denied"&&Notification.requestPermission().then(a=>{a==="granted"&&s()})}const al={success:5e3,error:8e3,info:5e3},ja={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"}},rl=()=>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"})}),nl=()=>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"})}),Nr=()=>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"})}),ll={success:rl,error:nl,info:Nr},ol=({visible:t,toastId:s,body:a,type:r,title:o,duration:n})=>{const d=ja[r]||ja.info,u=ll[r]||Nr,c=typeof document<"u"&&document.documentElement.classList.contains("dark");return e.jsxs("div",{onClick:()=>Ga.dismiss(s),style:{background:c?d.darkBg:d.bg,borderLeft:`4px solid ${c?d.darkBorder:d.border}`,borderRadius:10,boxShadow:c?"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(u,{})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[o&&e.jsx("div",{style:{fontWeight:600,fontSize:13,lineHeight:1.3,color:c?"#e2e8f0":"#1e293b",marginBottom:2},children:o}),e.jsx("div",{style:{fontSize:12.5,lineHeight:1.45,color:c?"#94a3b8":"#475569",wordBreak:"break-word"},children:a})]}),e.jsx("div",{style:{position:"absolute",bottom:0,left:0,height:3,width:"100%",background:d.bar,opacity:.45,animation:`toast-progress ${n}ms linear forwards`}})]})};function re(t,s){const a=(s==null?void 0:s.type)??"success",r=s==null?void 0:s.title,o=(s==null?void 0:s.duration)??al[a]??5e3;typeof document<"u"&&document.visibilityState==="visible"?il(t,a,r,o):sl(r?`${r}: ${t}`:t)}function il(t,s,a,r){Ga.custom(o=>e.jsx(ol,{visible:o.visible,toastId:o.id,body:t,type:s,title:a,duration:r}),{duration:r})}if(typeof document<"u"){const t="asd-toast-progress-style";if(!document.getElementById(t)){const s=document.createElement("style");s.id=t,s.textContent=`
18
+ @keyframes toast-progress {
19
+ from { width: 100%; }
20
+ to { width: 0%; }
21
+ }`,document.head.appendChild(s)}}const gt={All:{icon:qt,color:"text-slate-600",bg:"bg-slate-100",border:"border-slate-200"},View:{icon:bn,color:"text-pink-600",bg:"bg-pink-50",border:"border-pink-100"},Service:{icon:ps,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:or,color:"text-emerald-600",bg:"bg-emerald-50",border:"border-emerald-100"},Network:{icon:fn,color:"text-blue-600",bg:"bg-blue-50",border:"border-blue-100"},Storage:{icon:hn,color:"text-purple-600",bg:"bg-purple-50",border:"border-purple-100"},UI:{icon:Is,color:"text-cyan-600",bg:"bg-cyan-50",border:"border-cyan-100"},Utility:{icon:ht,color:"text-orange-600",bg:"bg-orange-50",border:"border-orange-100"},"code-standard":{icon:Qe,color:"text-violet-600",bg:"bg-violet-50",border:"border-violet-100"},"code-pattern":{icon:ta,color:"text-fuchsia-600",bg:"bg-fuchsia-50",border:"border-fuchsia-100"},architecture:{icon:gn,color:"text-sky-600",bg:"bg-sky-50",border:"border-sky-100"},"best-practice":{icon:mt,color:"text-emerald-600",bg:"bg-emerald-50",border:"border-emerald-100"},"event-and-data-flow":{icon:xn,color:"text-amber-600",bg:"bg-amber-50",border:"border-amber-100"},"project-profile":{icon:ea,color:"text-teal-600",bg:"bg-teal-50",border:"border-teal-100"},"agent-guidelines":{icon:us,color:"text-rose-600",bg:"bg-rose-50",border:"border-rose-100"},"objc-deep-scan":{icon:mn,color:"text-indigo-600",bg:"bg-indigo-50",border:"border-indigo-100"},"category-scan":{icon:Zs,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"}},cl=["All","View","Service","Tool","Model","Network","Storage","UI","Utility"],dl=["recipes","ai","spm","candidates","knowledge","depgraph","knowledgegraph","guard","skills","wiki","help"],Jt=[{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 la(t){var a;if(!t)return"";const s=t.toLowerCase().trim();for(const r of Jt)if(r.id===s||(a=r.aliases)!=null&&a.includes(s))return r.id;return s}function wa(t){switch(la(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 ul="https://github.com/GxFn/AutoSnippet/issues/new?title=Guard%20误报%2F建议%3A%20&body=请描述误报的规则ID、代码片段或改进建议。",gs=t=>["Example","Demo","Sample","Tests","Spec","Mock","Runner"].some(a=>t.endsWith(a)||t.includes(a)),pl=t=>t.startsWith("_"),ml=t=>t==="_pending",xl="您暂无写入权限,无法保存。如需此权限请联系管理员;请勿擅自修改核心代码或安装包,以免影响团队协作与数据安全。";function Ss(t){var o,n;const s=t==null?void 0:t.response;if((s==null?void 0:s.status)!==403)return null;const a=(o=s.data)==null?void 0:o.code,r=(n=s.data)==null?void 0:n.error;return a==="RECIPE_WRITE_FORBIDDEN"||typeof r=="string"&&r.includes("没权限")?xl:null}const gl="保存过于频繁,请稍后再试。";function Na(t){var a;const s=t==null?void 0:t.response;return s!=null&&s.data?s.status===403?Ss(t)??null:s.status===429&&((a=s.data)==null?void 0:a.code)==="RECIPE_SAVE_RATE_LIMIT"?gl:null:null}const le=ds.create({baseURL:"/api/v1"});function ka(t){const s=t.quality||{},a=t.stats||t.statistics||{},r=t.content||{},o=t.trigger||"@"+(t.title||"").replace(/[\s_-]+(.)?/g,(d,u)=>u?u.toUpperCase():""),n={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:r,category:t.category||"",language:t.language||"",description:t.description||"",status:t.lifecycle||t.status||"pending",kind:t.kind||void 0,knowledgeType:t.knowledgeType||void 0,relations:t.relations||null,constraints:t.constraints||null,tags:t.tags||[],stats:n,trigger:o,source:t.source||"",sourceFile:t.sourceFile||"",moduleName:t.moduleName||"",usageGuide:r.markdown||t.doClause||"",reasoning:t.reasoning||null,quality:t.quality||null,scope:t.scope||"",complexity:t.complexity||"",difficulty:t.difficulty||t.complexity||"",version:t.version||"",headers:t.headers||[],updatedAt:t.updatedAt||null}}function hl(t){let s="",a="general",r="",o="",n="",d="",u="",c="",x="",v=[],g=[],m="",i=0,f="1.0.0",j="",C="",I="",D="",$="",O="",T="",Z="",W="",M="",F=t;const k=t.match(/^---\n([\s\S]*?)\n---/);if(k){const E=k[1],B=P=>{const U=E.match(new RegExp(`^${P}:\\s*(.+)$`,"m"));return U?U[1].trim():null};s=B("language")||s,a=B("category")||a,r=B("title")||r,o=B("trigger")||"",n=B("summary_cn")||B("summary")||B("description")||n,d=B("summary_en")||"",u=B("knowledge_type")||B("knowledgeType")||"",c=B("complexity")||"",x=B("scope")||"",m=B("difficulty")||"",f=B("version")||"1.0.0";const b=B("authority");b&&(i=parseInt(b)||0);const h=B("tags");if(h)try{v=JSON.parse(h)}catch{v=h.split(",").map(P=>P.trim()).filter(Boolean)}const L=B("headers");if(L)try{g=JSON.parse(L)}catch{g=[L]}O=B("kind")||"",T=B("doClause")||"",Z=B("dontClause")||"",W=B("whenClause")||"",M=B("topicHint")||"";const ie=t.match(/```[\w]*\n([\s\S]*?)```/);ie&&(F=ie[1].trim());const Y=t.replace(/^---\n[\s\S]*?\n---/,"").trim(),ge=Y.match(/## (?:AI Context \/ )?Usage Guide(?:\s*\(CN\))?\n\n([\s\S]*?)(?=\n## |$)/);ge&&(j=ge[1].trim());const Ne=Y.match(/## (?:AI Context \/ )?Usage Guide\s*\(EN\)\n\n([\s\S]*?)(?=\n## |$)/);Ne&&(C=Ne[1].trim());const fe=Y.match(/## Architecture Usage\n\n([\s\S]*?)(?=\n## |$)/);fe&&(I=fe[1].trim());const w=Y.match(/## Best Practices\n\n([\s\S]*?)(?=\n## |$)/);w&&(D=w[1].trim());const N=Y.match(/## Standards\n\n([\s\S]*?)(?=\n## |$)/);N&&($=N[1].trim())}return{title:r,language:s,category:a,trigger:o,summary:n,summaryEn:d,knowledgeType:u,complexity:c,scope:x,tags:v,headers:g,difficulty:m,authority:i,version:f,codePattern:F,usageGuide:j,usageGuideEn:C,rationaleText:I,bestPracticesText:D,standardsText:$,kind:O,doClause:T,dontClause:Z,whenClause:W,topicHint:M}}function fl(t,s,a){var o;const r=Array.isArray(t.category)?t.category[0]:t.category||s||"general";return{title:t.title||"Untitled",content:t.content||{pattern:((o=t.content)==null?void 0:o.pattern)||"",markdown:"",rationale:""},description:t.description||"",trigger:t.trigger||"",language:t.language||"",category:r,kind:t.kind||"pattern",knowledgeType:t.knowledgeType||"code-pattern",complexity:t.complexity||"intermediate",source:a,lifecycle:"pending",tags:t.tags||[],sourceFile:t.sourceFile||"",moduleName:t.moduleName||"",headers:t.headers||[],headerPaths:t.headerPaths||[],reasoning:{whyStandard:t.description||t.title||"Extracted from project",sources:[a],confidence:.6},metadata:{targetName:s||"",title:t.title||"",trigger:t.trigger||"",description:t.description||"",category:r,headers:t.headers||[],headerPaths:t.headerPaths||[],moduleName:t.moduleName||"",isMarked:t.isMarked||!1}}}async function Wt(t){var n,d,u;const s=t.replace(/\.md$/i,"");if(/^[a-f0-9-]{8,}$/i.test(s))return s;const a=await le.get("/knowledge?limit=1000"),o=(((d=(n=a.data)==null?void 0:n.data)==null?void 0:d.data)||((u=a.data)==null?void 0:u.data)||[]).find(c=>{const x=c.title||c.name||"";return x===s||x+".md"===t});if(o!=null&&o.id)return o.id;throw new Error(`Knowledge entry not found: ${t}`)}async function bl(t,s){var d;const a=(d=t.body)==null?void 0:d.getReader();if(!a)throw new Error("ReadableStream not available");const r=new TextDecoder;let o="",n="";for(;;){const{done:u,value:c}=await a.read();if(u)break;const x=r.decode(c,{stream:!0});o+=x;const v=o.split(`
22
+ `);o=v.pop()||"";for(const g of v){if(g.startsWith(":")||!g.startsWith("data: "))continue;const m=g.slice(6).trim();if(!(!m||m==="[DONE]"))try{const i=JSON.parse(m);if(s(i),i.type==="text:delta"&&i.delta)n+=i.delta;else if(i.type==="stream:done"&&i.text)n=i.text;else if(i.type==="stream:error")throw new Error(i.message||"Stream error")}catch(i){if(i instanceof SyntaxError)continue;throw i}}}return n}const ne={async fetchData(){var m,i,f,j,C,I,D,$,O;const[t,s,a]=await Promise.all([le.get("/knowledge?limit=1000").catch(()=>({data:{success:!0,data:{data:[]}}})),le.get("/ai/config").catch(()=>({data:{success:!0,data:{provider:"",model:""}}})),le.get("/modules/project-info").catch(()=>({data:{success:!0,data:{projectRoot:""}}}))]),r=((i=(m=t.data)==null?void 0:m.data)==null?void 0:i.data)||((j=(f=t.data)==null?void 0:f.data)==null?void 0:j.items)||[],n=r.filter(T=>T.lifecycle==="active").map(ka),d=r.filter(T=>T.lifecycle==="pending"),u={};for(const T of d){const Z=T.category||T.language||"_pending";u[Z]||(u[Z]={targetName:Z,scanTime:T.createdAt,items:[]}),u[Z].items.push(T)}const c=((C=s.data)==null?void 0:C.data)||{provider:"",model:""},x={};for(const T of r)T.id&&T.title&&(x[T.id]=T.title);const v=((D=(I=a.data)==null?void 0:I.data)==null?void 0:D.projectRoot)||"",g=((O=($=a.data)==null?void 0:$.data)==null?void 0:O.projectName)||"";return{rootSpec:{list:[]},recipes:n,candidates:u,projectRoot:v,projectName:g,watcherStatus:"active",aiConfig:{provider:c.provider||"",model:c.model||""},idTitleMap:x}},async fetchTargets(){var a;return(((a=(await le.get("/modules/targets")).data)==null?void 0:a.data)||{}).targets||[]},async getTargetFiles(t,s){var o,n;const r=((o=(await le.post("/modules/target-files",{target:t},{signal:s})).data)==null?void 0:o.data)||{};return{files:r.files||[],count:r.total||((n=r.files)==null?void 0:n.length)||0}},async scanTarget(t,s){var n;const r=((n=(await le.post("/modules/scan",{target:t},{signal:s,timeout:6e5})).data)==null?void 0:n.data)||{};return{recipes:r.recipes||r.result||[],scannedFiles:r.scannedFiles||[],message:r.message||"",noAi:!!r.noAi}},async scanTargetStream(t,s,a){let r;const o=await fetch("/api/v1/modules/scan/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({target:t}),signal:a});if(!o.ok)throw new Error(`Scan stream start failed: ${o.status}`);if(r=(await o.json()).sessionId,!r)throw new Error("No sessionId returned");return new Promise((d,u)=>{const c=`/api/v1/modules/scan/events/${r}`,x=new EventSource(c);let v=!1,g={recipes:[],scannedFiles:[],message:"",noAi:!1};function m(){x.close()}if(x.onmessage=i=>{try{const f=JSON.parse(i.data);s(f),f.type==="scan:result"&&(g={recipes:f.recipes||[],scannedFiles:f.scannedFiles||[],message:f.message||"",noAi:!!f.noAi}),f.type==="stream:done"&&(m(),v=!0,d(g)),f.type==="stream:error"&&(m(),v=!0,u(new Error(f.message||"Scan stream error")))}catch{}},x.onerror=()=>{v||(m(),v=!0,g.recipes.length>0?d(g):u(new Error("EventSource connection failed")))},a){const i=()=>{v||(m(),v=!0,u(new DOMException("The operation was aborted.","AbortError")))};if(a.aborted){i();return}a.addEventListener("abort",i,{once:!0})}})},async scanProject(t){var r;const a=((r=(await le.post("/modules/scan-project",{},{signal:t,timeout:6e5})).data)==null?void 0:r.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 o,n;const a=new URLSearchParams;return t&&a.set("path",t),s&&a.set("depth",String(s)),((n=(o=(await le.get(`/modules/browse-dirs?${a.toString()}`)).data)==null?void 0:o.data)==null?void 0:n.directories)||[]},async scanFolderStream(t,s,a){const r=await fetch("/api/v1/modules/scan-folder/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t}),signal:a});if(!r.ok)throw new Error(`Scan folder start failed: ${r.status}`);const n=(await r.json()).sessionId;if(!n)throw new Error("No sessionId returned");return new Promise((d,u)=>{const c=`/api/v1/modules/scan/events/${n}`,x=new EventSource(c);let v=!1,g={recipes:[],scannedFiles:[],message:"",noAi:!1};function m(){x.close()}if(x.onmessage=i=>{try{const f=JSON.parse(i.data);s(f),f.type==="scan:result"&&(g={recipes:f.recipes||[],scannedFiles:f.scannedFiles||[],message:f.message||"",noAi:!!f.noAi}),f.type==="stream:done"&&(m(),v=!0,d(g)),f.type==="stream:error"&&(m(),v=!0,u(new Error(f.message||"Scan folder stream error")))}catch{}},x.onerror=()=>{v||(m(),v=!0,g.recipes.length>0?d(g):u(new Error("EventSource connection failed")))},a){const i=()=>{v||(m(),v=!0,u(new DOMException("The operation was aborted.","AbortError")))};if(a.aborted){i();return}a.addEventListener("abort",i,{once:!0})}})},async bootstrap(t){var r;const a=((r=(await le.post("/modules/bootstrap",{},{signal:t,timeout:3e5})).data)==null?void 0:r.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 le.get("/modules/bootstrap/status")).data)==null?void 0:s.data)||{status:"idle"}},async getDepGraph(t){var a;return((a=(await le.get(`/modules/dep-graph?level=${t}`)).data)==null?void 0:a.data)||{}},async getProjectInfo(){var t;try{return((t=(await le.get("/modules/project-info")).data)==null?void 0:t.data)||{}}catch{return{primaryLanguage:"unknown",discoverers:[],hasSpm:!1}}},async syncSnippets(t="all"){return(await le.post("/commands/install",{target:t})).data},async refreshProject(){try{await le.post("/modules/update-map")}catch{await le.post("/commands/spm-map")}},async extractFromPath(t){var r;const a=((r=(await le.post("/extract/path",{relativePath:t})).data)==null?void 0:r.data)||{};return{result:a.result||[],isMarked:a.isMarked||!1}},async extractFromText(t,s){var o;const r=((o=(await le.post("/extract/text",{text:t,...s?{relativePath:s}:{}})).data)==null?void 0:o.data)||{};return Array.isArray(r.result)&&r.result.length>0?r.result[0]:r},async saveRecipe(t,s){const a=hl(s),r=a.title||t.replace(/\.md$/,""),o={trigger:a.trigger,headers:a.headers,difficulty:a.difficulty,authority:a.authority,version:a.version},n={pattern:a.codePattern||"",rationale:a.rationaleText||"",steps:a.bestPracticesText?[a.bestPracticesText]:[],codeChanges:[],verification:null,markdown:a.usageGuide||""},d={};if(a.standardsText){const c=a.standardsText.split(`
23
+ `).map(g=>g.trim()).filter(Boolean),x=c.filter(g=>g.startsWith("- ")).map(g=>g.slice(2).trim());x.length>0&&(d.preconditions=x);const v=c.filter(g=>!g.startsWith("- ")&&!g.startsWith("**"));v.length>0&&(d.boundaries=v)}const u={title:r,language:a.language,category:a.category,description:a.summary,knowledgeType:a.knowledgeType||"code-pattern",complexity:a.complexity||"intermediate",scope:a.scope||null,tags:a.tags||[],content:n,constraints:d,dimensions:o};a.kind&&(u.kind=a.kind),a.doClause&&(u.doClause=a.doClause),a.dontClause&&(u.dontClause=a.dontClause),a.whenClause&&(u.whenClause=a.whenClause),a.topicHint&&(u.topicHint=a.topicHint);try{const c=await Wt(t);await le.patch(`/knowledge/${c}`,u);return}catch{}await le.post("/knowledge",u)},async deleteRecipe(t){const s=await Wt(t);await le.delete(`/knowledge/${s}`)},async getRecipeByName(t){var n;const s=await Wt(t),r=(n=(await le.get(`/knowledge/${s}`)).data)==null?void 0:n.data;if(!r)throw new Error("Recipe not found");const o=r.content||{};return{name:t,content:o.pattern||o.markdown||""}},async setRecipeAuthority(t,s){const a=await Wt(t);await le.patch(`/knowledge/${a}/quality`,{codeCompleteness:s,projectAdaptation:s,documentationClarity:s})},async updateRecipeRelations(t,s){const a=await Wt(t);await le.patch(`/knowledge/${a}`,{relations:s})},async getCandidate(t){var r;const a=(r=(await le.get(`/knowledge/${t}`)).data)==null?void 0:r.data;if(!a)throw new Error("Knowledge entry not found");return a},async deleteCandidate(t){await le.delete(`/knowledge/${t}`)},async promoteCandidateToRecipe(t,s){var o;const r=(o=(await le.patch(`/knowledge/${t}/publish`)).data)==null?void 0:o.data;return{recipe:r,candidate:r}},async enrichCandidates(t){var a;return((a=(await le.post("/candidates/enrich",{candidateIds:t})).data)==null?void 0:a.data)||{enriched:0,total:0,results:[]}},async bootstrapRefine(t,s,a){var o;return((o=(await le.post("/candidates/bootstrap-refine",{candidateIds:t,userPrompt:s,dryRun:a},{timeout:3e5})).data)==null?void 0:o.data)||{refined:0,total:0,errors:[],results:[]}},async refinePreview(t,s){var r;return((r=(await le.post("/candidates/refine-preview",{candidateId:t,userPrompt:s},{timeout:12e4})).data)==null?void 0:r.data)||{}},async refineApply(t,s,a){var o;return((o=(await le.post("/candidates/refine-apply",{candidateId:t,userPrompt:s,preview:a},{timeout:12e4})).data)==null?void 0:o.data)||{}},async getKnowledgeGraph(t=500){var a;return((a=(await le.get(`/search/graph/all?limit=${t}`)).data)==null?void 0:a.data)||{edges:[],nodeLabels:{},nodeTypes:{},nodeCategories:{}}},async getGraphStats(){var s;return((s=(await le.get("/search/graph/stats")).data)==null?void 0:s.data)||{totalEdges:0,byRelation:{},nodeTypes:[]}},async discoverRelations(t=20){var a,r,o,n;const s=await le.post("/recipes/discover-relations",{batchSize:t});if(!((a=s.data)!=null&&a.success))throw new Error(((o=(r=s.data)==null?void 0:r.error)==null?void 0:o.message)||"启动失败");return((n=s.data)==null?void 0:n.data)||{status:"unknown"}},async getDiscoverRelationsStatus(){var s;return((s=(await le.get("/recipes/discover-relations/status")).data)==null?void 0:s.data)||{status:"idle"}},async deleteAllCandidatesInTarget(t){var o,n;const a=((n=(o=(await le.get(`/knowledge?category=${encodeURIComponent(t)}&limit=1000`)).data)==null?void 0:o.data)==null?void 0:n.data)||[];let r=0;for(const d of a)try{await le.delete(`/knowledge/${d.id}`),r++}catch{}return{deleted:r}},async promoteToCandidate(t,s){var o,n;const a=fl(t,s,"review-promote");return{ok:!0,candidateId:((n=(o=(await le.post("/knowledge",a)).data)==null?void 0:o.data)==null?void 0:n.id)||""}},async getCandidateSimilarity(t,s){var r;return((r=(await le.post("/search/similarity",{code:t,language:s}).catch(()=>({data:{data:{similar:[]}}}))).data)==null?void 0:r.data)||{similar:[]}},async getCandidateSimilarityEx(t){var a;return((a=(await le.post("/search/similarity",t).catch(()=>({data:{data:{similar:[]}}}))).data)==null?void 0:a.data)||{similar:[]}},async getRecipeContentByName(t){var u;const s=await Wt(t),r=(u=(await le.get(`/knowledge/${s}`)).data)==null?void 0:u.data;if(!r)throw new Error("Recipe not found");const n=ka(r).content,d=[n==null?void 0:n.pattern,n==null?void 0:n.markdown].filter(Boolean).join(`
24
+
25
+ `)||"";return{name:t,content:d}},async getAiProviders(){var s;return((s=(await le.get("/ai/providers")).data)==null?void 0:s.data)||[]},async setAiConfig(t,s){var r;return((r=(await le.post("/ai/config",{provider:t,model:s})).data)==null?void 0:r.data)||{provider:t,model:s}},async chat(t,s,a){var n;const o=((n=(await le.post("/ai/chat",{prompt:t,history:s},{signal:a})).data)==null?void 0:n.data)||{};return{text:o.reply||o.text||"",hasContext:o.hasContext}},async chatStream(t,s,a,r,o){const n=await fetch("/api/v1/ai/chat/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:t,history:s,...o?{lang:o}:{}}),signal:r});if(!n.ok)throw new Error(`Chat start failed: ${n.status}`);if((n.headers.get("content-type")||"").includes("text/event-stream")){let x={text:""};const v=await bl(n,g=>{a(g),g.type==="stream:done"&&(g.text&&(x.text=g.text),x.toolCalls=g.toolCalls,x.hasContext=g.hasContext)});return!x.text&&v&&(x.text=v),x}const u=await n.json(),c=u.sessionId;if(!c)throw new Error(`No sessionId returned: ${JSON.stringify(u)}`);return new Promise((x,v)=>{const g=`/api/v1/ai/chat/events/${c}`,m=new EventSource(g);let i="",f={text:""},j=!1;function C(){m.close()}if(m.onmessage=I=>{try{const D=JSON.parse(I.data);if(D.type==="stream:start")return;a(D),D.type==="text:delta"&&D.delta&&(i+=D.delta),D.type==="stream:done"&&(f={text:D.text||i,toolCalls:D.toolCalls,hasContext:D.hasContext},C(),j=!0,x(f)),D.type==="stream:error"&&(C(),j=!0,v(new Error(D.message||"Stream error")))}catch{}},m.onerror=()=>{j||(C(),i?(j=!0,x({text:i})):(j=!0,v(new Error("EventSource connection failed"))))},r){const I=()=>{j||(C(),j=!0,v(new DOMException("The operation was aborted.","AbortError")))};r.aborted?I():r.addEventListener("abort",I,{once:!0})}})},async refinePreviewStream(t,s,a,r){const o=await fetch("/api/v1/candidates/refine-preview-stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({candidateId:t,userPrompt:s}),signal:r});if(!o.ok)throw new Error(`Refine stream start failed: ${o.status}`);const d=(await o.json()).sessionId;if(!d)throw new Error("No sessionId returned");return new Promise((u,c)=>{const x=`/api/v1/candidates/refine-preview/events/${d}`,v=new EventSource(x);let g=!1;function m(){v.close()}r&&r.addEventListener("abort",()=>{m(),g||(g=!0,c(new DOMException("Aborted","AbortError")))},{once:!0}),v.onmessage=i=>{try{const f=JSON.parse(i.data);a(f),f.type==="stream:done"&&(m(),g=!0,u({candidateId:f.candidateId||t,before:f.before||{},after:f.after||{},preview:f.preview||null})),f.type==="stream:error"&&(m(),g=!0,c(new Error(f.message||"Refine stream error")))}catch{}},v.onerror=()=>{m(),g||(g=!0,c(new Error("Refine EventSource connection lost")))}})},async summarizeCode(t,s){var r;const a=await le.post("/ai/summarize",{code:t,language:s});return((r=a.data)==null?void 0:r.data)||a.data||{}},async translate(t,s){var o,n;const a=await le.post("/ai/translate",{summary:t,usageGuide:s}),r=((o=a.data)==null?void 0:o.data)||{summaryEn:"",usageGuideEn:""};return(n=a.data)!=null&&n.warning&&(r.warning=a.data.warning),r},async search(t,s={}){var m,i;const{mode:a="bm25",type:r,limit:o=20,signal:n,context:d}=s,u=f=>{if(!f)return{};if(typeof f=="object")return f;try{return JSON.parse(f)}catch{return{markdown:f}}};if(d){const j=((m=(await le.post("/search/context-aware",{keyword:t,limit:o,language:d.language,sessionHistory:d.sessionHistory||[]},{signal:n}).catch(()=>({data:{data:{}}}))).data)==null?void 0:m.data)||{},C=(j.results||[]).map(I=>{const D=u(I.content);return{title:(I.name||"").replace(/\.md$/,""),content:D,score:I.similarity||0,qualityScore:I.qualityScore||0,usageCount:I.usageCount||0,authorityScore:I.authority||0,matchType:I.matchType}});return{items:C,total:j.total||C.length,mode:"bm25",ranked:!0}}const c=new URLSearchParams({q:t,mode:a,limit:String(o)});r&&c.set("type",r);const v=((i=(await le.get(`/search?${c}`,{signal:n})).data)==null?void 0:i.data)||{},g=(v.items||[]).map(f=>({...f,content:u(f.content)}));return{items:g,total:v.totalResults||v.total||g.length,mode:v.mode,ranked:v.ranked}},async semanticSearch(t,s=10){return(await this.search(t,{mode:"semantic",limit:s})).items.map(r=>{var o,n,d;return{name:(r.title||r.name||"")+".md",content:((o=r.content)==null?void 0:o.pattern)||((n=r.content)==null?void 0:n.markdown)||((d=r.content)==null?void 0:d.code)||"",similarity:r.score||0,metadata:{type:"recipe",name:(r.title||r.name||"")+".md"}}})},async contextAwareSearch(t){var a;return((a=(await le.post("/search/context-aware",t).catch(()=>({data:{data:{}}}))).data)==null?void 0:a.data)||{}},async xcodeSimulateSearch(t){var a;return((a=(await le.post("/search/xcode-simulate",t).catch(()=>({data:{data:{}}}))).data)==null?void 0:a.data)||{}},async getGuardRules(){var o;const s=((o=(await le.get("/rules?limit=100")).data)==null?void 0:o.data)||{},a=s.data||s.items||[],r={};for(const n of a)r[n.id]=n;return{rules:r,projectLanguages:s.projectLanguages||[]}},async getGuardViolations(){var a;const s=((a=(await le.get("/violations")).data)==null?void 0:a.data)||{};return{runs:s.data||s.items||[]}},async clearViolations(){await le.post("/violations/clear")},async saveGuardRule(t){var a;return((a=(await le.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(r=>({name:(r.title||r.name||"")+".md",path:"",content:r.content,qualityScore:(r.quality||{}).overall||r.qualityScore||0,recommendReason:""})),total:a.total}},async listSkills(){var s;return((s=(await le.get("/skills")).data)==null?void 0:s.data)||{skills:[],total:0}},async loadSkill(t,s){var o;const a=s?`?section=${encodeURIComponent(s)}`:"";return((o=(await le.get(`/skills/${encodeURIComponent(t)}${a}`)).data)==null?void 0:o.data)||{}},async createSkill(t){var a;return((a=(await le.post("/skills",t)).data)==null?void 0:a.data)||{}},async updateSkill(t,s){var r;return((r=(await le.put(`/skills/${encodeURIComponent(t)}`,s)).data)==null?void 0:r.data)||{}},async deleteSkill(t){var a;return((a=(await le.delete(`/skills/${encodeURIComponent(t)}`)).data)==null?void 0:a.data)||{}},async suggestSkills(){var s;return((s=(await le.get("/skills/suggest")).data)==null?void 0:s.data)||{suggestions:[],analysisContext:{}}},async getSignalStatus(){var s;return((s=(await le.get("/skills/signal-status")).data)==null?void 0:s.data)||{running:!1,mode:"off",snapshot:null}},async aiGenerateSkill(t){var r;return((r=(await le.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:r.data)||{reply:""}},async getLlmEnvConfig(){var s;return((s=(await le.get("/ai/env-config")).data)==null?void 0:s.data)||{vars:{},hasEnvFile:!1,llmReady:!1}},async getTokenUsage7Days(){var s;return((s=(await le.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 le.post("/ai/env-config",t)).data)==null?void 0:a.data)||{vars:{},hasEnvFile:!1,llmReady:!1}},async knowledgeList(t={}){var o;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((o=(await le.get(`/knowledge${a?`?${a}`:""}`)).data)==null?void 0:o.data)||{data:[],pagination:{page:1,pageSize:20,total:0}}},async knowledgeStats(){var s;return((s=(await le.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 le.get(`/knowledge/${t}`)).data)==null?void 0:a.data},async knowledgeCreate(t){var a;return(a=(await le.post("/knowledge",t)).data)==null?void 0:a.data},async knowledgeUpdate(t,s){var r;return(r=(await le.patch(`/knowledge/${t}`,s)).data)==null?void 0:r.data},async knowledgeDelete(t){await le.delete(`/knowledge/${t}`)},async knowledgeLifecycle(t,s,a){var o;return(o=(await le.patch(`/knowledge/${t}/${s}`,a?{reason:a}:{})).data)==null?void 0:o.data},async knowledgeBatchPublish(t){var a;return((a=(await le.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 le.post(`/knowledge/${t}/usage`,{type:s,feedback:a})},async knowledgeUpdateQuality(t){var a;return((a=(await le.patch(`/knowledge/${t}/quality`)).data)==null?void 0:a.data)||{quality:{}}},async wikiGenerate(){await le.post("/wiki/generate")},async wikiUpdate(){await le.post("/wiki/update")},async wikiAbort(){await le.post("/wiki/abort")},async wikiStatus(){var s;return((s=(await le.get("/wiki/status")).data)==null?void 0:s.data)||{task:{status:"idle"}}},async wikiFiles(){var s;return((s=(await le.get("/wiki/files")).data)==null?void 0:s.data)||{files:[],exists:!1}},async wikiFileContent(t){var a;return((a=(await le.get(`/wiki/file/${t}`)).data)==null?void 0:a.data)||{path:t,content:"",size:0}},async getLang(){var s,a;return((a=(s=(await le.get("/ai/lang")).data)==null?void 0:s.data)==null?void 0:a.lang)||"zh"},async setLang(t){await le.post("/ai/lang",{lang:t})}},vl=!1,_s="auth_token",Bs="auth_user";function yl(){const[t,s]=l.useState(()=>localStorage.getItem(_s)),[a,r]=l.useState(()=>{try{const x=localStorage.getItem(Bs);return x?JSON.parse(x):null}catch{return null}}),[o,n]=l.useState(!1),d=l.useCallback(async(x,v)=>{var g,m,i,f;n(!0);try{const C=(await ds.post("/api/v1/auth/login",{username:x,password:v})).data;if(C.success){const I=C.data.token,D=C.data.user??{username:x,role:"developer"};return localStorage.setItem(_s,I),localStorage.setItem(Bs,JSON.stringify(D)),s(I),r(D),{success:!0}}return{success:!1,error:((g=C.error)==null?void 0:g.message)||"登录失败"}}catch(j){return{success:!1,error:((f=(i=(m=j.response)==null?void 0:m.data)==null?void 0:i.error)==null?void 0:f.message)||j.message||"网络错误"}}finally{n(!1)}},[]),u=l.useCallback(()=>{localStorage.removeItem(_s),localStorage.removeItem(Bs),s(null),r(null)},[]);l.useEffect(()=>{},[]);const c=l.useMemo(()=>!0,[t,a]);return{authEnabled:vl,isAuthenticated:c,isLoading:o,user:a,login:d,logout:u}}const jl={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 wl(t){const[s,a]=l.useState(()=>"developer"),[r,o]=l.useState("anonymous"),[n,d]=l.useState("probe"),[u,c]=l.useState(!0),[x,v]=l.useState(null),g=l.useCallback(async()=>{c(!0);try{const C=localStorage.getItem("auth_token"),I={};C&&(I.Authorization=`Bearer ${C}`);const D=await ds.get("/api/v1/auth/probe",{headers:I});if(D.data.success){const $=D.data.data;a($.role),o($.user),d($.mode),v($.probeCache??null)}}catch{a("developer")}finally{c(!1)}},[]);l.useEffect(()=>{g()},[t,g]);const m=l.useCallback((C,I)=>{const D=jl[s]||[];if(D.includes("*"))return!0;const $=I?`${C}:${I}`:C;if(D.includes($))return!0;const O=C.split(":")[0];return!!(D.includes(`${O}:*`)||O==="read"&&D.includes("read:*"))},[s]),i=l.useMemo(()=>s==="developer",[s]),f=l.useMemo(()=>s==="developer",[s]),j=l.useMemo(()=>s!=="developer",[s]);return{role:s,user:r,mode:n,isLoading:u,isAdmin:i,canWrite:f,isReadOnly:j,can:m,probeCache:x,refresh:g}}let es=null;function oa(){return es||(es=Wr(window.location.origin,{path:"/socket.io",transports:["websocket"],reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:2e3,reconnectionDelayMax:1e4}),es.on("connect",()=>{es.emit("join-notifications")})),es}const Gs={activeRound:0,round1:{status:"idle"},round2:{status:"idle"},round3:{status:"idle"}};function Nl(){const[t,s]=l.useState(null),[a,r]=l.useState(!1),[o,n]=l.useState(Gs),[d,u]=l.useState(0),c=l.useRef(null),x=l.useRef(null);l.useEffect(()=>{const i=oa(),f=()=>{r(!0),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>C(),500)},j=()=>r(!1),C=async()=>{try{const h=await ne.getBootstrapStatus();h&&h.status==="running"&&h.tasks&&s(L=>!L||L.id===h.id||h.progress>((L==null?void 0:L.progress)??0)?(c.current=h.id,h):L)}catch{}},I=()=>C(),D=h=>{c.current=h.sessionId,n(Gs),s({id:h.sessionId,status:"running",progress:0,total:h.total,completed:0,failed:0,filling:0,skeleton:h.total,startedAt:h.startedAt||Date.now(),totalToolCalls:0,elapsedMs:0,tasks:h.tasks.map(L=>({id:L.id,status:"skeleton",meta:{type:L.type,dimId:L.dimId,label:L.label,skillWorthy:L.skillWorthy,skillMeta:L.skillMeta}}))})},$=h=>{s(L=>{if(!L)return L;const ie=L.tasks.map(Y=>Y.id===h.taskId?{...Y,status:"filling",startedAt:Date.now()}:Y);return{...L,progress:h.progress,tasks:ie,filling:ie.filter(Y=>Y.status==="filling").length,skeleton:ie.filter(Y=>Y.status==="skeleton").length}})},O=h=>{var ie,Y;s(ge=>{if(!ge)return ge;const Ne=ge.tasks.map(fe=>fe.id===h.taskId?{...fe,status:"completed",completedAt:Date.now(),result:h.result}:fe);return{...ge,progress:h.progress,completed:h.completed,total:h.total,totalToolCalls:h.totalToolCalls??ge.totalToolCalls,elapsedMs:h.elapsedMs??ge.elapsedMs,tasks:Ne,filling:Ne.filter(fe=>fe.status==="filling").length,skeleton:Ne.filter(fe=>fe.status==="skeleton").length}}),(Number((ie=h.result)==null?void 0:ie.created)||Number((Y=h.result)==null?void 0:Y.extracted)||0)>0&&u(ge=>ge+1)},T=h=>{s(L=>{if(!L)return L;const ie=L.tasks.map(Y=>Y.id===h.taskId?{...Y,status:"failed",completedAt:Date.now(),error:h.error}:Y);return{...L,progress:h.progress,failed:ie.filter(Y=>Y.status==="failed").length,tasks:ie,filling:ie.filter(Y=>Y.status==="filling").length,skeleton:ie.filter(Y=>Y.status==="skeleton").length}})},Z=h=>{s(L=>{if(!L||h.sessionId&&L.id!==h.sessionId)return L;const ie=L.tasks.map(Y=>Y.status==="skeleton"||Y.status==="filling"?{...Y,status:"completed",completedAt:Date.now()}:Y);return{...L,status:ie.some(Y=>Y.status==="failed")?"completed_with_errors":"completed",progress:100,completed:ie.filter(Y=>Y.status==="completed").length,summary:h.summary,tasks:ie,filling:0,skeleton:0}})},W=h=>{n(L=>({...L,activeRound:1,round1:{status:"running",total:h.total}}))},M=h=>{n(L=>({...L,activeRound:1,round1:{status:"completed",total:h.total,kept:h.kept,dropped:h.dropped,merged:h.merged}}))},F=h=>{n(L=>({...L,activeRound:2,round2:{status:"running",total:h.total}}))},k=h=>{n(L=>({...L,activeRound:2,round2:{...L.round2,status:"running",current:h.current,total:h.total,progress:h.progress}}))},E=h=>{n(L=>({...L,activeRound:2,round2:{status:"completed",total:h.total,refined:h.refined,progress:100}}))},B=h=>{n(L=>({...L,activeRound:3,round3:{status:"running",total:h.total}}))},b=h=>{n(L=>({...L,activeRound:3,round3:{status:"completed",total:h.total,afterDedup:h.afterDedup,relationsFound:h.relationsFound}}))};return i.on("connect",f),i.on("disconnect",j),i.io.on("reconnect",I),i.on("bootstrap:started",D),i.on("bootstrap:task-started",$),i.on("bootstrap:task-completed",O),i.on("bootstrap:task-failed",T),i.on("bootstrap:all-completed",Z),i.on("review:round1-started",W),i.on("review:round1-completed",M),i.on("review:round2-started",F),i.on("review:round2-progress",k),i.on("review:round2-completed",E),i.on("review:round3-started",B),i.on("review:round3-completed",b),r(i.connected),i.connected&&C(),()=>{x.current&&clearTimeout(x.current),i.off("connect",f),i.off("disconnect",j),i.io.off("reconnect",I),i.off("bootstrap:started",D),i.off("bootstrap:task-started",$),i.off("bootstrap:task-completed",O),i.off("bootstrap:task-failed",T),i.off("bootstrap:all-completed",Z),i.off("review:round1-started",W),i.off("review:round1-completed",M),i.off("review:round2-started",F),i.off("review:round2-progress",k),i.off("review:round2-completed",E),i.off("review:round3-started",B),i.off("review:round3-completed",b)}},[]);const v=l.useCallback(()=>{c.current=null,s(null),n(Gs)},[]),g=l.useCallback(i=>{i&&s(f=>{if(f&&f.id===i.id){const j=(f.filling??0)+(f.completed??0)+(f.failed??0),C=(i.filling??0)+(i.completed??0)+(i.failed??0);if(f.progress>i.progress||j>C)return f}return c.current=i.id,i})},[]),m=(t==null?void 0:t.status)==="completed"||(t==null?void 0:t.status)==="completed_with_errors";return{session:t,isConnected:a,isAllDone:m,reviewState:o,candidateCreatedTick:d,resetSession:v,initFromApiResponse:g}}const K={xs:12,sm:14,md:16,lg:20,xl:24,xxl:32,xxxl:48};function ve(...t){return Vr(Jr(t))}const kr=Qr,Ht=Xr,Ot=Zr,At=l.forwardRef(({className:t,sideOffset:s=6,...a},r)=>e.jsx(Yr,{children:e.jsx($a,{ref:r,sideOffset:s,className:ve("z-50 overflow-hidden rounded-[var(--radius-md)] bg-[var(--bg-emphasis)] px-2.5 py-1.5 text-xs font-medium text-[var(--fg-on-emphasis)] shadow-[var(--shadow-lg)]","animate-in fade-in-0 zoom-in-95","data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95","data-[side=bottom]:slide-in-from-top-1 data-[side=left]:slide-in-from-right-1 data-[side=right]:slide-in-from-left-1 data-[side=top]:slide-in-from-bottom-1",t),...a})}));At.displayName=$a.displayName;function Ca({item:t,active:s,onClick:a}){return e.jsxs(Ht,{delayDuration:300,children:[e.jsx(Ot,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:a,className:ve("relative flex items-center justify-center w-10 h-10 rounded-[var(--radius-md)] transition-all duration-200",s?"bg-[var(--accent)] text-white shadow-[0_0_16px_var(--accent-glow)]":"text-[var(--fg-subtle)] hover:bg-[var(--bg-muted)]/60 hover:text-[var(--fg-default)]"),children:[e.jsx(t.icon,{size:18,className:"shrink-0"}),t.badge!=null&&e.jsxs("span",{className:"absolute -top-0.5 -right-0.5 flex h-2.5 w-2.5 items-center justify-center",children:[e.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-[var(--warning)] opacity-40"}),e.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-[var(--warning)]"})]})]})}),e.jsx(At,{side:"right",className:"flex items-center gap-1.5",children:e.jsx("span",{children:t.label})})]})}const kl=({activeTab:t,navigateToTab:s,candidateCount:a,signalSuggestionCount:r=0,currentUser:o,onLogout:n})=>{const{t:d,lang:u,setLang:c}=Me(),{isDark:x,toggle:v}=Fs(),g=[{tab:"recipes",icon:ir,label:d("sidebar.recipes")},{tab:"spm",icon:Dt,label:d("sidebar.moduleExplorer")},{tab:"candidates",icon:it,label:d("sidebar.candidates",{count:a})},{tab:"knowledge",icon:Zs,label:d("sidebar.batchManage")},{tab:"depgraph",icon:ta,label:d("sidebar.depGraph")},{tab:"knowledgegraph",icon:Rs,label:d("sidebar.knowledgeGraph")},{tab:"guard",icon:mt,label:d("sidebar.guard")},{tab:"skills",icon:Qe,label:d("sidebar.skills"),badge:r>0?r:void 0},{tab:"wiki",icon:ft,label:d("sidebar.repoWiki")},{tab:"ai",icon:It,label:d("sidebar.aiAssistant")},{tab:"help",icon:cr,label:d("sidebar.help")}],m=g.slice(0,9),i=g.slice(9);return e.jsx(kr,{children:e.jsxs("aside",{className:"w-[var(--sidebar-width)] flex flex-col shrink-0 glass-surface select-none z-10",children:[e.jsx("div",{className:"flex items-center justify-center h-[var(--topbar-height)] border-b border-[var(--border-muted)]",children:e.jsx("div",{className:"w-9 h-9 rounded-[var(--radius-md)] flex items-center justify-center text-white shadow-[0_0_20px_var(--accent-glow)]",style:{background:"var(--accent-gradient)"},children:e.jsx("span",{className:"text-[11px] font-black italic tracking-tighter leading-none",children:"AS"})})}),e.jsxs("nav",{className:"flex-1 flex flex-col items-center gap-1 py-3 overflow-y-auto scrollbar-hidden",children:[m.map(f=>e.jsx(Ca,{item:f,active:t===f.tab,onClick:()=>s(f.tab)},f.tab)),e.jsx("div",{className:"w-6 separator-gradient my-2"}),i.map(f=>e.jsx(Ca,{item:f,active:t===f.tab,onClick:()=>s(f.tab)},f.tab))]}),e.jsxs("div",{className:"flex flex-col items-center gap-1 py-3 border-t border-[var(--border-muted)]",children:[e.jsxs(Ht,{delayDuration:300,children:[e.jsx(Ot,{asChild:!0,children:e.jsx("button",{onClick:()=>c(u==="zh"?"en":"zh"),className:"flex items-center justify-center w-10 h-10 rounded-[var(--radius-md)] text-[var(--fg-subtle)] hover:bg-[var(--bg-muted)] hover:text-[var(--fg-default)] transition-colors",children:e.jsx(vn,{size:18})})}),e.jsx(At,{side:"right",children:d("header.langSwitch")})]}),e.jsxs(Ht,{delayDuration:300,children:[e.jsx(Ot,{asChild:!0,children:e.jsx("button",{onClick:v,className:"flex items-center justify-center w-10 h-10 rounded-[var(--radius-md)] text-[var(--fg-subtle)] hover:bg-[var(--bg-muted)] hover:text-[var(--fg-default)] transition-colors",children:x?e.jsx(yn,{size:18}):e.jsx(jn,{size:18})})}),e.jsx(At,{side:"right",children:d(x?"header.lightMode":"header.darkMode")})]}),o&&e.jsxs(Ht,{delayDuration:300,children:[e.jsx(Ot,{asChild:!0,children:e.jsx("button",{onClick:n,className:"flex items-center justify-center w-10 h-10 rounded-[var(--radius-md)] text-[var(--fg-subtle)] hover:bg-[var(--bg-muted)] hover:text-[var(--danger)] transition-colors",children:e.jsx(dr,{size:18})})}),e.jsxs(At,{side:"right",className:"flex items-center gap-2",children:[e.jsx("span",{children:o}),n&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[var(--fg-subtle)]",children:"·"}),e.jsxs("span",{className:"flex items-center gap-1 text-[var(--danger)]",children:[e.jsx(wn,{size:12}),d("sidebar.logout")]})]})]})]})]})]})})},Cl={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 ia(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 St=({code:t,language:s="text",className:a="",showLineNumbers:r=!1})=>{const o=Cl[s==null?void 0:s.toLowerCase()]||(s==null?void 0:s.toLowerCase())||"text",n=a.includes("!rounded-none"),d=ia(t);return e.jsx("div",{className:`rounded-xl overflow-x-auto text-sm min-w-0 ${a}`,children:e.jsx(Ha,{language:o,style:Oa,showLineNumbers:r,customStyle:{margin:0,padding:"1rem 1.25rem",fontSize:"0.8125rem",lineHeight:1.5,borderRadius:n?0:"0.75rem",overflowX:"auto"},codeTagProps:{className:"language-highlighted",style:{fontFamily:"ui-monospace, monospace"}},PreTag:"div",children:d})})};let Sl=0,Sa="";function Al(t){const s=t?"dark":"default";s!==Sa&&(Ka.initialize({startOnLoad:!1,theme:s,securityLevel:"loose",fontFamily:"ui-sans-serif, system-ui, -apple-system, sans-serif",...t?{themeVariables:{darkMode:!0,background:"#1e1e1e",primaryColor:"#2d3748",primaryTextColor:"#e2e8f0",primaryBorderColor:"#4a5568",lineColor:"#94a3b8",secondaryColor:"#283040",tertiaryColor:"#1a2332",noteBkgColor:"#283040",noteTextColor:"#e2e8f0",noteBorderColor:"#4a5568"}}:{}}),Sa=s)}const Cr=({code:t})=>{const{t:s}=Me(),{isDark:a}=Fs(),[r,o]=l.useState(""),[n,d]=l.useState("");return l.useEffect(()=>{let u=!1;const c=`mermaid_${Sl++}`;async function x(){var v;Al(a);try{const{svg:g}=await Ka.render(c,t.trim());u||(o(g),d(""))}catch(g){u||(d((g==null?void 0:g.message)||"Mermaid render failed"),o(""));try{(v=document.getElementById("d"+c))==null||v.remove()}catch{}}}return x(),()=>{u=!0}},[t,a]),n?e.jsx("div",{className:"my-4 p-4 bg-slate-800 text-slate-200 rounded-lg overflow-x-auto text-sm font-mono whitespace-pre-wrap",children:t}):r?e.jsx("div",{className:"my-5 flex justify-center overflow-x-auto rounded-lg border p-4 border-[var(--border-default)] bg-[var(--bg-surface)]",dangerouslySetInnerHTML:{__html:r}}):e.jsx("div",{className:"my-4 flex items-center justify-center py-8 text-[var(--fg-muted)] text-sm",children:s("shared.renderingChart")})};function ca(t){return!t||typeof t!="string"?t:t.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/,"").trim()||t}function Dl(t){return!t||typeof t!="string"?t:t.replace(/\\\\n/g,`
51
+ `)}function Il(t){if(!t||typeof t!="string")return t;const s=t.split(`
52
+ `),a=[];let r=!1;for(let o=0;o<s.length;o++){const n=s[o];if(/^\s*(`{3,}|~{3,})/.test(n)){r=!r,a.push(n);continue}if(r){a.push(n);continue}const d=s[o+1];n!==""&&d!==void 0&&d!==""?a.push(n+" "):a.push(n)}return a.join(`
53
+ `)}const Rl=/^\s*(graph|flowchart|sequenceDiagram|classDiagram|stateDiagram|erDiagram|gantt|pie|gitGraph|mindmap|timeline|journey|quadrantChart|sankey|xychart|block)\b/i;function Tl(t){const s=[],a=t.split(`
54
+ `);let r=[],o=!1,n=!1,d=[];for(let u=0;u<a.length;u++){const c=a[u],x=/^\s*(`{3,}|~{3,})(.*)$/.exec(c);if(x&&!n&&!o)if(x[2].trim().toLowerCase()==="mermaid"){r.length>0&&(s.push({type:"markdown",content:r.join(`
55
+ `)}),r=[]),o=!0,d=[];continue}else{n=!0,r.push(c);continue}if(o&&x){s.push({type:"mermaid",content:d.join(`
56
+ `)}),o=!1,d=[];continue}if(n&&x){n=!1,r.push(c);continue}o?d.push(c):r.push(c)}return o&&d.length>0&&s.push({type:"mermaid",content:d.join(`
57
+ `)}),r.length>0&&s.push({type:"markdown",content:r.join(`
58
+ `)}),s}const El=t=>({pre({children:s}){return e.jsx("div",{className:"min-w-0",children:s})},code({node:s,className:a,children:r,...o}){const n=/language-(\w+)/.exec(a||""),d=Array.isArray(r)?r.join(""):String(r),u=d.replace(/\n$/,""),c=d.includes(`
59
+ `)||!!n;return c&&Rl.test(u)?e.jsx(Cr,{code:u}):c&&n?e.jsx(St,{code:u,language:n[1],showLineNumbers:t}):c?e.jsx(St,{code:u,language:"text",showLineNumbers:t}):e.jsx("code",{className:"px-1.5 py-0.5 bg-[var(--bg-subtle)] text-[var(--fg-primary)] rounded text-[0.9em] font-mono border border-[var(--border-default)]",...o,children:r})},p:({children:s})=>e.jsx("p",{className:"mb-4 leading-7 last:mb-0",children:s}),h1:({children:s,...a})=>{const r=typeof s=="string"?s.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g,"-").replace(/(^-|-$)/g,""):void 0;return e.jsx("h1",{id:r,className:"text-[1.75rem] font-bold mb-4 mt-8 first:mt-0 pb-2 border-b border-[var(--border-default)] text-[var(--fg-primary)] leading-tight scroll-mt-20",...a,children:s})},h2:({children:s,...a})=>{const r=typeof s=="string"?s.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g,"-").replace(/(^-|-$)/g,""):void 0;return e.jsx("h2",{id:r,className:"text-xl font-bold mb-3 mt-8 pb-1.5 border-b border-[var(--border-default)] text-[var(--fg-primary)] leading-snug scroll-mt-20",...a,children:s})},h3:({children:s,...a})=>{const r=typeof s=="string"?s.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g,"-").replace(/(^-|-$)/g,""):void 0;return e.jsx("h3",{id:r,className:"text-lg font-semibold mb-2 mt-6 text-[var(--fg-primary)] leading-snug scroll-mt-20",...a,children:s})},h4:({children:s,...a})=>{const r=typeof s=="string"?s.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g,"-").replace(/(^-|-$)/g,""):void 0;return e.jsx("h4",{id:r,className:"text-base font-semibold mb-2 mt-5 text-[var(--fg-primary)] scroll-mt-20",...a,children:s})},strong:({children:s})=>e.jsx("strong",{className:"font-semibold text-[var(--fg-primary)]",children:s}),em:({children:s})=>e.jsx("em",{className:"italic text-[var(--fg-secondary)]",children:s}),del:({children:s})=>e.jsx("del",{className:"line-through text-[var(--fg-muted)]",children:s}),hr:()=>e.jsx("hr",{className:"my-8 border-0 h-px bg-[var(--border-default)]"}),ul:({children:s})=>e.jsx("ul",{className:"list-disc pl-6 mb-4 space-y-1.5 marker:text-[var(--fg-muted)]",children:s}),ol:({children:s})=>e.jsx("ol",{className:"list-decimal pl-6 mb-4 space-y-1.5 marker:text-[var(--fg-secondary)]",children:s}),li:({children:s,...a})=>{var n,d,u,c;const r=a.node,o=((d=(n=r==null?void 0:r.children)==null?void 0:n[0])==null?void 0:d.type)==="element"&&((c=(u=r==null?void 0:r.children)==null?void 0:u[0])==null?void 0:c.tagName)==="input";return e.jsx("li",{className:`leading-7 ${o?"list-none -ml-6 flex items-start gap-2":""}`,children:s})},blockquote:({children:s})=>e.jsx("blockquote",{className:"border-l-4 border-blue-300 bg-blue-50/40 pl-4 pr-3 py-2 my-4 text-[var(--fg-secondary)] rounded-r-lg [&>p]:mb-2 [&>p:last-child]:mb-0",children:s}),a:({href:s,children:a})=>s!=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-[var(--border-default)] my-4",loading:"lazy"}),table:({children:s})=>e.jsx("div",{className:"my-5 overflow-x-auto rounded-lg border border-[var(--border-default)]",children:e.jsx("table",{className:"w-full border-collapse text-sm",children:s})}),thead:({children:s})=>e.jsx("thead",{className:"bg-[var(--bg-subtle)] border-b border-[var(--border-default)]",children:s}),tbody:({children:s})=>e.jsx("tbody",{className:"divide-y divide-[var(--border-default)]",children:s}),tr:({children:s})=>e.jsx("tr",{className:"hover:bg-[var(--bg-subtle)] transition-colors",children:s}),th:({children:s})=>e.jsx("th",{className:"px-4 py-2.5 text-left text-xs font-semibold text-[var(--fg-secondary)] uppercase tracking-wider",children:s}),td:({children:s})=>e.jsx("td",{className:"px-4 py-2.5 text-[var(--fg-primary)] align-top",children:s}),input:({checked:s})=>e.jsx("input",{type:"checkbox",checked:s,readOnly:!0,className:"mt-1 w-4 h-4 rounded border-[var(--border-default)] text-blue-600 cursor-default"})}),Et=({content:t,className:s="",showLineNumbers:a=!1,stripFrontmatter:r=!1})=>{const o=l.useMemo(()=>El(a),[a]),n=l.useMemo(()=>{let d=r?ca(t):t;return d=Dl(d),d=Il(d),Tl(d)},[t,r]);return e.jsx("div",{className:`markdown-body text-[var(--fg-primary)] ${s}`,children:n.map((d,u)=>d.type==="mermaid"?e.jsx(Cr,{code:d.content},`mermaid-${u}`):e.jsx(en,{remarkPlugins:[tn],components:o,children:d.content},`md-${u}`))})},Sr="asd-chat-topics",Pl=50;function Ll(){return Date.now().toString(36)+Math.random().toString(36).substring(2,8)}function Ml(t){const s=t.find(r=>r.role==="user");if(!s)return"新话题";const a=s.content.trim().replace(/\n/g," ");return a.length>30?a.slice(0,30)+"…":a}function Fl(){try{const t=localStorage.getItem(Sr);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s:[]}catch{return[]}}function zl(t){try{const s=t.slice(0,Pl);localStorage.setItem(Sr,JSON.stringify(s))}catch(s){console.warn("[ChatTopics] localStorage save failed:",s)}}function Ar(){const[t,s]=l.useState(()=>Fl()),[a,r]=l.useState(null),o=l.useRef(t);l.useEffect(()=>{o.current=t},[t]);const n=l.useCallback(m=>{s(i=>{const f=typeof m=="function"?m(i):m;return zl(f),f})},[]),d=l.useCallback(m=>{const i=Ll(),f={id:i,title:m||"新话题",messages:[],createdAt:Date.now(),updatedAt:Date.now()};return n(j=>[f,...j]),r(i),i},[n]),u=l.useCallback(m=>{n(i=>i.filter(f=>f.id!==m)),r(i=>i===m?null:i)},[n]),c=l.useCallback((m,i)=>{n(f=>{const j=f.findIndex($=>$.id===m);if(j<0)return f;const C={...f[j],messages:i,updatedAt:Date.now()},I=Ml(i);I!=="新话题"&&(C.title=I);const D=[...f];return D[j]=C,D.splice(j,1),D.unshift(C),D})},[n]),x=l.useCallback(m=>o.current.find(i=>i.id===m),[]),v=l.useCallback(m=>{r(m)},[]),g=t.find(m=>m.id===a)??null;return{topics:t,activeTopicId:a,activeTopic:g,createTopic:d,deleteTopic:u,saveTopic:c,getTopic:x,switchTopic:v,setActiveTopicId:r}}function _l(t,s){const a=`chatStream.tools.${s}`,r=t(a);return r===a?s:r}function Bl(t,s,a){if(!a)return"";switch(s){case"read_project_file":{const r=a.filePath||(Array.isArray(a.filePaths)?a.filePaths[0]:"");if(!r)return"";const o=String(r).split("/").pop()||r,n=Array.isArray(a.filePaths)&&a.filePaths.length>1?t("chatStream.andNFiles",{n:a.filePaths.length}):"";return`${o}${n}`}case"list_project_structure":{const r=a.directory||a.path||"";return r?String(r):""}case"search_project_code":{const r=a.patterns||a.pattern||a.query||"";return Array.isArray(r)?r.slice(0,2).join(", ")+(r.length>2?" …":""):String(r).slice(0,40)}case"semantic_search_code":case"search_knowledge":case"search_recipes":case"search_candidates":{const r=a.query||a.keyword||"";return String(r).slice(0,40)}case"get_class_info":case"get_protocol_info":return a.className||a.name||a.protocolName||"";case"get_file_summary":{const r=a.filePath||"";return r&&String(r).split("/").pop()||""}case"summarize_code":case"analyze_code":{const r=a.language||"";return r?`${r}`:""}case"get_class_hierarchy":return a.rootClass||"";case"check_duplicate":return a.title||"";default:return""}}function Aa(t,s,a){const r=_l(t,s),o=Bl(t,s,a);return o?`${r}: ${o}`:r}function Dr(t,s,a){const r=[],o=[];let n="";function d(c){s(x=>x.map(v=>v.id===t?{...v,content:c}:v))}function u(c){switch(c.type){case"step:start":{const x=c.phase==="user"?"":` [${c.phase}]`,v=a("chatStream.stepProgress",{step:c.step,maxSteps:c.maxSteps})+x+"...",g=r.length>0?r.join(`
60
+ `)+`
61
+
62
+ `+v:v;d(g);break}case"tool:start":{r.push(`🔧 ${Aa(a,c.tool,c.args)}...`),o.push({tool:c.tool,args:c.args}),d(r.join(`
63
+ `));break}case"tool:end":{const x=r.length-1;if(x>=0){const v=o[x]||{tool:c.tool},g=Aa(a,v.tool,v.args);if(c.status==="error"||c.error)r[x]=`❌ ${g} ${a("chatStream.toolFailed")} (${c.duration}ms)`;else{const m=c.resultSize>1e3?`${(c.resultSize/1024).toFixed(1)}KB`:a("chatStream.toolResultChars",{size:c.resultSize});r[x]=`✅ ${g} → ${m} (${c.duration}ms)`}d(r.join(`
64
+ `))}break}case"text:start":{n="";break}case"text:delta":{n+=c.delta||"";const x=r.length>0?r.join(`
65
+ `)+`
66
+
67
+ ---
68
+
69
+ `:"";d(x+n);break}}}return{onEvent:u,getState:()=>({answerText:n,toolLogs:r})}}const Ir=l.createContext({openChat:()=>{},openRefine:()=>{},close:()=>{},toggle:()=>{},newTopic:()=>{},isOpen:!1}),xs=()=>l.useContext(Ir),Vt=()=>Math.random().toString(36).substring(2,10),Gl=[{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 $l(t,s,a){const r=[];for(const o of Gl){const n=o.format||(c=>String(c??"")),d=n(t[o.key]),u=n(s[o.key]);u&&u!==d&&r.push({field:o.key,label:a(o.labelKey),before:d,after:u})}return r}function Da(t){var s,a,r,o;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:((r=t.content)==null?void 0:r.rationale)||"",tags:t.tags||[],confidence:((o=t.reasoning)==null?void 0:o.confidence)??.6,relations:t.relations||{},aiInsight:t.aiInsight||null,agentNotes:t.agentNotes||null}}const Hl=({diff:t,excludedFields:s=[],onToggleField:a})=>{const{t:r}=Me();return t.length===0?e.jsx("p",{className:"text-xs text-[var(--fg-muted)] italic py-2",children:r("globalChat.diff.noChanges")}):e.jsx("div",{className:"space-y-2 mt-2",children:t.map(o=>{const n=s.includes(o.field);return e.jsxs("div",{className:`border rounded-lg overflow-hidden transition-opacity ${n?"border-[var(--border-default)] opacity-45":"border-[var(--border-default)]"}`,children:[e.jsxs("div",{className:"px-2.5 py-1.5 border-b flex items-center gap-1.5 bg-[var(--bg-subtle)] border-[var(--border-default)]",children:[e.jsx(pr,{size:10,className:n?"text-[var(--fg-muted)]":"text-emerald-500"}),e.jsx("span",{className:`text-[10px] font-bold flex-1 ${n?"text-[var(--fg-muted)] line-through":"text-[var(--fg-secondary)]"}`,children:o.label}),a&&(n?e.jsx("button",{onClick:()=>a(o.field),className:"px-2 py-0.5 text-[9px] font-bold rounded-full bg-[var(--bg-subtle)] text-[var(--fg-secondary)] hover:bg-emerald-100 hover:text-emerald-600 transition-colors",title:r("globalChat.diff.excludedRestore"),children:r("globalChat.diff.excludedRestore")}):e.jsxs("button",{onClick:()=>a(o.field),className:"group flex items-center gap-0.5 px-1.5 py-0.5 text-[9px] font-medium rounded-full text-[var(--fg-muted)] hover:bg-red-50 hover:text-red-500 transition-colors",title:r("globalChat.diff.exclude"),children:[e.jsx(Xe,{size:10,className:"opacity-60 group-hover:opacity-100"}),r("globalChat.diff.exclude")]}))]}),!n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"p-2 bg-red-50/30 border-b border-[var(--border-default)]",children:[e.jsx("div",{className:"text-[9px] font-bold text-red-400 mb-0.5 uppercase",children:r("globalChat.diff.before")}),e.jsx("pre",{className:"text-[11px] text-[var(--fg-secondary)] whitespace-pre-wrap break-words max-h-40 overflow-auto font-mono leading-relaxed scrollbar-light",children:o.before||e.jsx("span",{className:"italic text-[var(--fg-muted)]",children:r("globalChat.diff.empty")})})]}),e.jsxs("div",{className:"p-2 bg-emerald-50/30",children:[e.jsx("div",{className:"text-[9px] font-bold text-emerald-500 mb-0.5 uppercase",children:r("globalChat.diff.after")}),e.jsx("pre",{className:"text-[11px] text-[var(--fg-primary)] whitespace-pre-wrap break-words max-h-40 overflow-auto font-mono leading-relaxed scrollbar-light",children:o.after})]})]})]},o.field)})})},Rr=l.createContext(null),Ol=({children:t})=>{const{t:s}=Me(),[a,r]=l.useState(!1),[o,n]=l.useState([]),[d,u]=l.useState(!1),[c,x]=l.useState(!1),[v,g]=l.useState(null),[m,i]=l.useState(new Set),[f,j]=l.useState(""),C=l.useRef([]),I=!!v,D=v?v.candidateIds[v.currentIdx]:null,$=v?v.candidates.find(B=>B.id===D):void 0,O=v?v.candidateIds.length>1:!1;l.useEffect(()=>{v&&$&&(n(B=>[...B,{id:Vt(),role:"system",content:s("globalChat.system.refinePrefix",{title:$.title,description:$.description||s("globalChat.system.noDescription")}),timestamp:Date.now()}]),j(""))},[v==null?void 0:v.currentIdx]);const T=l.useCallback(()=>{g(null),r(!0)},[]),Z=l.useCallback(B=>{g({...B,currentIdx:0}),i(new Set),n([]),C.current=[],r(!0)},[]),W=l.useCallback(()=>r(!1),[]),M=l.useCallback(()=>r(B=>!B),[]),F=l.useCallback(()=>{n([]),C.current=[],j(""),g(null),i(new Set)},[]),k={openChat:T,openRefine:Z,close:W,toggle:M,newTopic:F,isOpen:a},E={messages:o,setMessages:n,loading:d,setLoading:u,applying:c,setApplying:x,refineCtx:v,setRefineCtx:g,applied:m,setApplied:i,lastPrompt:f,setLastPrompt:j,chatHistoryRef:C,isRefineMode:I,currentRefineId:D,currentRefineCandidate:$,isBatchRefine:O,close:W};return e.jsx(Ir.Provider,{value:k,children:e.jsx(Rr.Provider,{value:E,children:t})})},Kl=()=>{const{t,lang:s}=Me(),a=l.useContext(Rr),{messages:r,setMessages:o,loading:n,setLoading:d,applying:u,setApplying:c,refineCtx:x,setRefineCtx:v,applied:g,setApplied:m,lastPrompt:i,setLastPrompt:f,chatHistoryRef:j,isRefineMode:C,currentRefineId:I,currentRefineCandidate:D,isBatchRefine:$,close:O}=a,T=l.useRef(null),Z=l.useRef(null),[W,M]=l.useState(""),F=Ar(),k=l.useRef(null),E=l.useRef(!1);l.useEffect(()=>{if(C&&D){E.current=!0;const w=F.createTopic(t("globalChat.refineTopicPrefix",{title:D.title||t("globalChat.untitled")}));k.current=w,setTimeout(()=>{E.current=!1},50)}},[x]),l.useEffect(()=>{E.current||k.current&&r.length>0&&F.saveTopic(k.current,r)},[r]);const B=l.useCallback(()=>{if(!k.current){E.current=!0;const w=F.createTopic();k.current=w,setTimeout(()=>{E.current=!1},50)}},[F]);l.useEffect(()=>{var w;(w=T.current)==null||w.scrollIntoView({behavior:"smooth"})},[r,n]),l.useEffect(()=>{setTimeout(()=>{var w;return(w=Z.current)==null?void 0:w.focus()},200)},[]);const b=C&&I&&r.some(w=>{if(w.role!=="assistant"||!w.diff||w.diff.length===0)return!1;const N=w.excludedFields||[];return w.diff.some(P=>!N.includes(P.field))})&&!g.has(I),h=l.useCallback((w,N)=>{o(P=>P.map(U=>{if(U.id!==w)return U;const Q=U.excludedFields||[],ue=Q.includes(N)?Q.filter(ce=>ce!==N):[...Q,N];return{...U,excludedFields:ue}}))},[]),L=l.useRef(null),ie=l.useCallback(async()=>{const w=W.trim();if(!(!w||n)){if(C||B(),M(""),o(N=>[...N,{id:Vt(),role:"user",content:w,timestamp:Date.now()}]),d(!0),C&&I){f(w);const N=Vt();o(U=>[...U,{id:N,role:"assistant",content:t("globalChat.system.refining"),timestamp:Date.now()}]);const P=new AbortController;L.current=P;try{const U=await ne.refinePreviewStream(I,w,ce=>{if(ce.type==="data:progress"){const ke=ce.message||ce.stage||t("globalChat.system.processing");o(Le=>Le.map(Ie=>Ie.id===N?{...Ie,content:`🔄 ${ke}`}:Ie))}},P.signal),Q=U.before||(D?Da(D):{}),ue=$l(Q,U.after||{},t);o(ce=>ce.map(ke=>ke.id===N?{...ke,content:ue.length>0?t("globalChat.previewGenerated",{count:ue.length}):t("globalChat.noChangeHint"),diff:ue.length>0?ue:void 0,preview:ue.length>0?U.preview??void 0:void 0,excludedFields:[]}:ke))}catch(U){U.name==="AbortError"?o(Q=>Q.map(ue=>ue.id===N?{...ue,content:t("globalChat.system.cancelled")}:ue)):o(Q=>Q.map(ue=>{var ce,ke;return ue.id===N?{...ue,content:t("globalChat.refinePreviewFailed",{error:((ke=(ce=U.response)==null?void 0:ce.data)==null?void 0:ke.error)||U.message})}:ue}))}finally{L.current=null}}else{j.current.push({role:"user",content:w});const N=Vt();o(ce=>[...ce,{id:N,role:"assistant",content:t("globalChat.system.thinking"),timestamp:Date.now()}]);const P=new AbortController;L.current=P;const{onEvent:U,getState:Q}=Dr(N,o,t);let ue="";try{const ke=(await ne.chatStream(w,j.current,Le=>{U(Le),ue=Q().answerText},P.signal,s)).text||ue;j.current.push({role:"model",content:ke}),o(Le=>Le.map(Ie=>Ie.id===N?{...Ie,content:ke}:Ie))}catch(ce){if(ce.name==="AbortError"){const{answerText:ke,toolLogs:Le}=Q(),Ie=ke||(Le.length>0?Le.join(`
71
+ `)+`
72
+
73
+ `+t("globalChat.system.cancelled"):t("globalChat.system.cancelled"));ke&&j.current.push({role:"model",content:ke}),o(Be=>Be.map(H=>H.id===N?{...H,content:Ie}:H))}else o(ke=>ke.map(Le=>Le.id===N?{...Le,content:t("globalChat.requestFailed",{error:ce.message})}:Le))}finally{L.current=null}}d(!1)}},[W,n,C,I,D,B]),Y=l.useCallback(async()=>{var w,N,P,U;if(!(u||!I||!x)){c(!0);try{const Q=[...r].reverse().find(ce=>ce.role==="assistant"&&ce.preview);let ue=Q==null?void 0:Q.preview;if(ue&&((w=Q==null?void 0:Q.excludedFields)!=null&&w.length)&&Q.diff){ue={...ue};const ce=D?Da(D):{};for(const ke of Q.excludedFields)ke in ce&&(ue[ke]=ce[ke])}await ne.refineApply(I,i,ue),m(ce=>new Set(ce).add(I)),(N=x.onCandidateUpdated)==null||N.call(x,I),o(ce=>[...ce,{id:Vt(),role:"system",content:t("globalChat.system.changesApplied"),timestamp:Date.now()}]),re(t("globalChat.applySuccess"),{title:t("globalChat.applySuccessTitle")})}catch(Q){const ue=(U=(P=Q.response)==null?void 0:P.data)==null?void 0:U.error;re(typeof ue=="string"?ue:(ue==null?void 0:ue.message)||Q.message,{title:t("globalChat.applyFailed"),type:"error"})}finally{c(!1)}}},[u,I,i,x]),ge=l.useCallback(()=>{!x||x.currentIdx>=x.candidateIds.length-1||v(w=>w?{...w,currentIdx:w.currentIdx+1}:null)},[x]),Ne=l.useCallback(()=>{k.current=null,v(null),o(w=>[...w,{id:Vt(),role:"system",content:t("globalChat.system.exitedRefine"),timestamp:Date.now()}])},[]),fe=l.useCallback(w=>{w.key==="Enter"&&!w.shiftKey&&(w.preventDefault(),ie())},[ie]);return e.jsxs("aside",{className:"w-[420px] h-full bg-[var(--bg-surface)] border-l border-[var(--border-default)] flex flex-col shrink-0",children:[e.jsxs("div",{className:"px-4 h-[var(--topbar-height)] border-b border-[var(--border-default)] flex items-center justify-between shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-gradient-to-br from-blue-50 to-indigo-50 border border-blue-100 flex items-center justify-center",children:C?e.jsx(Je,{className:"text-emerald-500",size:16}):e.jsx(It,{className:"text-blue-600",size:16})}),e.jsxs("div",{children:[e.jsxs("h3",{className:"text-[13px] font-bold text-[var(--fg-primary)] flex items-center gap-2",children:[t(C?"globalChat.refineTitle":"globalChat.chatTitle"),C&&$&&e.jsxs("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-emerald-50 text-emerald-600 font-medium",children:[((x==null?void 0:x.currentIdx)??0)+1,"/",x==null?void 0:x.candidateIds.length]})]}),e.jsx("p",{className:"text-[10px] text-[var(--fg-muted)] truncate max-w-[250px]",children:C?(D==null?void 0:D.title)||t("globalChat.refineSubtitle"):t("globalChat.chatSubtitle")})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[C&&e.jsx("button",{onClick:Ne,className:"px-2 py-1 text-[10px] font-medium text-[var(--fg-secondary)] hover:text-[var(--fg-primary)] hover:bg-[var(--bg-subtle)] rounded-md transition-colors",children:t("globalChat.exitRefine")}),!C&&r.length>0&&e.jsx("button",{onClick:()=>{k.current=null,o([]),j.current=[],f("")},className:"p-1.5 hover:bg-[var(--bg-subtle)] rounded-lg transition-colors",title:t("globalChat.newTopic"),children:e.jsx(kt,{size:16,className:"text-[var(--fg-muted)]"})}),e.jsx("button",{onClick:O,className:"p-1.5 hover:bg-[var(--bg-subtle)] rounded-lg transition-colors",title:t("globalChat.closeChat"),children:e.jsx(Xe,{size:16,className:"text-[var(--fg-muted)]"})})]})]}),C&&D&&e.jsx("div",{className:"border-b border-[var(--border-default)] bg-emerald-50/30 px-4 py-2 shrink-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] font-bold text-emerald-700 truncate flex-1",children:D.title}),D.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:D.language})]})}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-3 min-h-0 scrollbar-light",children:[r.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(It,{className:"text-blue-500",size:20})}),e.jsx("h4",{className:"text-sm font-bold text-[var(--fg-primary)] mb-1",children:t("globalChat.emptyTitle")}),e.jsx("p",{className:"text-xs text-[var(--fg-muted)] max-w-[280px] leading-relaxed mb-3",children:t("globalChat.emptyDesc")}),e.jsx("div",{className:"flex flex-wrap gap-1.5 justify-center",children:[t("globalChat.quickPrompts.analyzeArch"),t("globalChat.quickPrompts.findDuplicates"),t("globalChat.quickPrompts.suggestOptimize")].map(w=>e.jsx("button",{onClick:()=>{var N;M(w),(N=Z.current)==null||N.focus()},className:"text-[10px] px-2.5 py-1 rounded-md bg-[var(--bg-subtle)] text-[var(--fg-secondary)] hover:bg-blue-50 hover:text-blue-700 transition-colors",children:w},w))})]}),C&&r.length<=1&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-2",children:[t("globalChat.refinePrompts.addExamples"),t("globalChat.refinePrompts.optimizeComments"),t("globalChat.refinePrompts.addCaveats"),t("globalChat.refinePrompts.improveSummary"),t("globalChat.refinePrompts.addPerformance")].map(w=>e.jsx("button",{onClick:()=>{var N;M(w),(N=Z.current)==null||N.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:w},w))}),r.map(w=>e.jsx("div",{className:`flex ${w.role==="user"?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[95%] ${w.role==="user"?"bg-blue-600 text-white rounded-2xl rounded-tr-md px-3.5 py-2":w.role==="system"?"bg-[var(--bg-subtle)] border border-[var(--border-default)] text-[var(--fg-secondary)] rounded-2xl px-3.5 py-2 w-full":"bg-[var(--bg-surface)] border border-[var(--border-default)] rounded-2xl rounded-tl-md px-3.5 py-2.5 shadow-sm w-full"}`,children:[w.role==="assistant"&&e.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[e.jsx(us,{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")})]}),w.role==="assistant"&&!w.diff?e.jsx(Et,{content:w.content,className:"text-xs text-[var(--fg-primary)]"}):e.jsx("p",{className:`text-xs leading-relaxed whitespace-pre-wrap ${w.role==="user"?"":w.role==="system"?"text-[var(--fg-secondary)]":"text-[var(--fg-primary)]"}`,children:w.content}),w.diff&&w.diff.length>0&&e.jsx(Hl,{diff:w.diff,excludedFields:w.excludedFields,onToggleField:C&&!g.has(I)?N=>h(w.id,N):void 0})]})},w.id)),n&&e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"bg-[var(--bg-surface)] border border-[var(--border-default)] rounded-2xl rounded-tl-md px-3.5 py-2.5 shadow-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pe,{size:12,className:`animate-spin ${C?"text-emerald-500":"text-blue-500"}`}),e.jsx("span",{className:"text-xs text-[var(--fg-secondary)]",children:t(C?"globalChat.loading.analyzing":"globalChat.loading.thinking")}),L.current&&e.jsx("button",{onClick:()=>{var w;return(w=L.current)==null?void 0:w.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:T})]}),C&&b&&!n&&(()=>{var Q,ue;const w=[...r].reverse().find(ce=>ce.role==="assistant"&&ce.diff&&ce.diff.length>0),N=((Q=w==null?void 0:w.diff)==null?void 0:Q.length)||0,P=((ue=w==null?void 0:w.excludedFields)==null?void 0:ue.length)||0,U=N-P;return e.jsxs("div",{className:"px-4 py-2 border-t border-[var(--border-default)] bg-emerald-50/50 flex items-center gap-2 shrink-0",children:[e.jsxs("button",{onClick:Y,disabled:u,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:[u?e.jsx(Pe,{size:11,className:"animate-spin"}):e.jsx(yt,{size:11}),u?t("globalChat.applyingBtn"):P>0?t("globalChat.confirmApplyN",{i:U,total:N}):t("globalChat.confirmApply")]}),e.jsxs("button",{className:"flex items-center gap-1 px-2.5 py-1.5 text-[11px] font-bold text-[var(--fg-secondary)] hover:text-[var(--fg-primary)] rounded-lg hover:bg-[var(--bg-subtle)] transition-colors",children:[e.jsx(ur,{size:11})," ",t("globalChat.continueAdjust")]}),$&&g.has(I)&&x.currentIdx<x.candidateIds.length-1&&e.jsxs("button",{onClick:ge,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&&!b&&!n&&$&&g.has(I)&&x.currentIdx<x.candidateIds.length-1&&e.jsx("div",{className:"px-4 py-2 border-t border-[var(--border-default)] flex items-center justify-center shrink-0",children:e.jsxs("button",{onClick:ge,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")," (",((x==null?void 0:x.currentIdx)??0)+2,"/",x==null?void 0:x.candidateIds.length,") ",e.jsx(rt,{size:12})]})}),e.jsxs("div",{className:"px-4 py-2.5 border-t border-[var(--border-default)] bg-[var(--bg-surface)] shrink-0",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx("textarea",{ref:Z,value:W,onChange:w=>M(w.target.value),onKeyDown:fe,placeholder:t(C?"globalChat.refinePlaceholder":"globalChat.chatPlaceholder"),rows:2,className:`flex-1 px-3 py-2 text-sm border border-[var(--border-default)] rounded-xl focus:outline-none focus:ring-2 ${C?"focus:ring-emerald-200 focus:border-emerald-400":"focus:ring-blue-200 focus:border-blue-400"} resize-none placeholder:text-[var(--fg-muted)]`,disabled:n||u}),e.jsx("button",{onClick:ie,disabled:!W.trim()||n||u,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(sa,{size:14})})]}),e.jsx("p",{className:"text-[9px] text-[var(--fg-muted)] mt-1",children:t(C?"globalChat.inputHintRefine":"globalChat.inputHintChat")})]})]})},ql=qa("inline-flex items-center justify-center gap-2 whitespace-nowrap font-medium transition-all cursor-pointer select-none disabled:pointer-events-none disabled:opacity-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--accent)]/40 focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--bg-root)] active:scale-[0.97]",{variants:{variant:{primary:"bg-[var(--bg-emphasis)] text-[var(--fg-on-emphasis)] hover:opacity-90 shadow-[var(--shadow-sm)]",secondary:"bg-[var(--bg-surface)] text-[var(--fg-default)] border border-[var(--border-default)] hover:bg-[var(--bg-subtle)] hover:border-[var(--border-emphasis)] shadow-[var(--shadow-sm)]",ghost:"bg-transparent text-[var(--fg-muted)] hover:bg-[var(--bg-subtle)] hover:text-[var(--fg-default)]",danger:"bg-[var(--danger)] text-white hover:opacity-90 shadow-[0_0_12px_rgba(239,68,68,0.2)]",accent:"text-white hover:opacity-90 shadow-[0_0_16px_var(--accent-glow)]"},size:{sm:"h-7 px-2.5 text-xs rounded-[var(--radius-md)]",md:"h-9 px-4 text-sm rounded-[var(--radius-md)]",lg:"h-11 px-5 text-base rounded-[var(--radius-lg)]",icon:"h-8 w-8 rounded-[var(--radius-md)]","icon-sm":"h-7 w-7 rounded-[var(--radius-sm)]"}},defaultVariants:{variant:"primary",size:"md"}}),We=l.forwardRef(({className:t,variant:s,size:a,loading:r,disabled:o,children:n,style:d,...u},c)=>{const x=s==="accent"?{background:"var(--accent-gradient)",...d}:d;return e.jsxs("button",{ref:c,className:ve(ql({variant:s,size:a,className:t})),disabled:o||r,style:x,...u,children:[r&&e.jsxs("svg",{className:"h-4 w-4 animate-spin",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),n]})});We.displayName="Button";const Tr=an,Er=rn,Ul=l.forwardRef(({className:t,inset:s,children:a,...r},o)=>e.jsxs(Ua,{ref:o,className:ve("flex cursor-default select-none items-center rounded-[var(--radius-sm)] px-2 py-1.5 text-sm outline-none","focus:bg-[var(--bg-subtle)] data-[state=open]:bg-[var(--bg-subtle)]",s&&"pl-8",t),...r,children:[a,e.jsx(rt,{className:"ml-auto h-4 w-4"})]}));Ul.displayName=Ua.displayName;const Wl=l.forwardRef(({className:t,...s},a)=>e.jsx(Wa,{ref:a,className:ve("z-50 min-w-[8rem] overflow-hidden rounded-[var(--radius-md)] border border-[var(--border-default)] bg-[var(--bg-surface)] p-1 text-[var(--fg-default)] shadow-[var(--shadow-lg)]","data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95","data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95","data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...s}));Wl.displayName=Wa.displayName;const da=l.forwardRef(({className:t,sideOffset:s=4,...a},r)=>e.jsx(sn,{children:e.jsx(Va,{ref:r,sideOffset:s,className:ve("z-50 min-w-[8rem] overflow-hidden rounded-[var(--radius-lg)] border border-[var(--border-default)] bg-[var(--bg-surface)] p-1 text-[var(--fg-default)] shadow-[var(--shadow-xl)]","dark:bg-[var(--bg-surface)]/95 dark:backdrop-blur-xl dark:border-[var(--glass-border)] dark:shadow-[0_16px_64px_rgba(0,0,0,0.5),0_0_1px_rgba(255,255,255,0.06)]","data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95","data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95","data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2","data-[side=bottom]:origin-top data-[side=top]:origin-bottom data-[side=left]:origin-right data-[side=right]:origin-left","data-[align=end]:data-[side=bottom]:origin-top-right data-[align=end]:data-[side=top]:origin-bottom-right","data-[align=start]:data-[side=bottom]:origin-top-left data-[align=start]:data-[side=top]:origin-bottom-left",t),...a})}));da.displayName=Va.displayName;const Kt=l.forwardRef(({className:t,inset:s,...a},r)=>e.jsx(Ja,{ref:r,className:ve("relative flex cursor-default select-none items-center gap-2 rounded-[var(--radius-sm)] px-2 py-1.5 text-sm outline-none transition-colors","focus:bg-[var(--bg-subtle)] focus:text-[var(--fg-default)]","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s&&"pl-8",t),...a}));Kt.displayName=Ja.displayName;const Vl=l.forwardRef(({className:t,children:s,checked:a,...r},o)=>e.jsxs(Ya,{ref:o,className:ve("relative flex cursor-default select-none items-center rounded-[var(--radius-sm)] py-1.5 pl-8 pr-2 text-sm outline-none transition-colors","focus:bg-[var(--bg-subtle)] focus:text-[var(--fg-default)]","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:a,...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Qa,{children:e.jsx(yt,{className:"h-4 w-4"})})}),s]}));Vl.displayName=Ya.displayName;const Jl=l.forwardRef(({className:t,children:s,...a},r)=>e.jsxs(Xa,{ref:r,className:ve("relative flex cursor-default select-none items-center rounded-[var(--radius-sm)] py-1.5 pl-8 pr-2 text-sm outline-none transition-colors","focus:bg-[var(--bg-subtle)] focus:text-[var(--fg-default)]","data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...a,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Qa,{children:e.jsx(Nn,{className:"h-2 w-2 fill-current"})})}),s]}));Jl.displayName=Xa.displayName;const Pr=l.forwardRef(({className:t,inset:s,...a},r)=>e.jsx(Za,{ref:r,className:ve("px-2 py-1.5 text-xs font-medium text-[var(--fg-subtle)]",s&&"pl-8",t),...a}));Pr.displayName=Za.displayName;const Ps=l.forwardRef(({className:t,...s},a)=>e.jsx(er,{ref:a,className:ve("-mx-1 my-1 h-px bg-[var(--border-muted)]",t),...s}));Ps.displayName=er.displayName;function Yl(t){return t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"k":String(t)}function Ql(t,s){if(t.length<=s)return t;const a=Math.floor((s-1)/2);return t.slice(0,a)+"…"+t.slice(t.length-a)}const Xl={recipes:"sidebar.recipes",spm:"sidebar.moduleExplorer",candidates:"sidebar.candidates",knowledge:"sidebar.batchManage",depgraph:"sidebar.depGraph",knowledgegraph:"sidebar.knowledgeGraph",guard:"sidebar.guard",skills:"sidebar.skills",wiki:"sidebar.repoWiki",ai:"sidebar.aiAssistant",help:"sidebar.help"},Zl=({setShowCreateModal:t,handleSyncSnippets:s,aiConfig:a,llmReady:r=!0,onOpenLlmConfig:o,onBeforeAiSwitch:n,onAiConfigChange:d,activeTab:u,onOpenCommandPalette:c,projectName:x,candidateCount:v=0})=>{const{toggle:g,isOpen:m}=xs(),{t:i}=Me(),[f,j]=l.useState([]),[C,I]=l.useState(!1),[D,$]=l.useState(null),O=l.useCallback(()=>{ne.getTokenUsage7Days().then(M=>$(M.summary)).catch(()=>{})},[]);l.useEffect(()=>{O();const M=oa(),F=()=>O();return M.on("candidate-created",F),M.on("bootstrap:all-completed",F),M.on("token-usage-updated",F),()=>{M.off("candidate-created",F),M.off("bootstrap:all-completed",F),M.off("token-usage-updated",F)}},[O]);const T=async M=>{I(!0);try{n==null||n(),await ne.setAiConfig(M.id,M.defaultModel),d&&d()}catch(F){console.error("AI config update failed",F)}finally{I(!1)}},Z=()=>{f.length===0&&ne.getAiProviders().then(j).catch(()=>{})},W=u?i(Xl[u],{count:v}):"";return e.jsx(kr,{children:e.jsxs("header",{className:"h-[var(--topbar-height)] flex items-center justify-between px-5 border-b border-[var(--border-muted)] glass shrink-0 gap-3 select-none z-10",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"text-sm text-[var(--fg-subtle)] font-medium truncate max-w-[160px]",title:x||"AutoSnippet",children:x||"AutoSnippet"}),W&&e.jsxs(e.Fragment,{children:[e.jsx(rt,{size:14,className:"text-[var(--fg-subtle)]/50 shrink-0"}),e.jsx("span",{className:"text-sm text-[var(--fg-default)] font-semibold truncate",children:W})]})]}),e.jsxs("button",{onClick:c,className:ve("flex items-center gap-2 h-8 px-3 rounded-[var(--radius-full)] border border-[var(--border-default)] bg-[var(--bg-subtle)]/60","text-sm text-[var(--fg-subtle)] hover:border-[var(--accent)]/40 hover:text-[var(--fg-muted)] hover:shadow-[0_0_12px_var(--accent-glow)] transition-all","w-64 justify-between backdrop-blur-sm"),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ct,{size:14}),e.jsx("span",{children:i("header.searchPlaceholder")})]}),e.jsx("kbd",{className:"hidden sm:inline-flex items-center gap-0.5 rounded-[var(--radius-sm)] border border-[var(--border-default)] bg-[var(--bg-root)]/60 px-1.5 py-0.5 text-[10px] font-mono text-[var(--fg-subtle)]",children:"⌘K"})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[!r&&e.jsxs(We,{variant:"ghost",size:"sm",onClick:o,className:"text-[var(--warning)] animate-pulse",children:[e.jsx(Ts,{size:14}),e.jsx("span",{className:"text-xs",children:i("header.configureLlm")})]}),r&&a&&e.jsxs(Tr,{onOpenChange:M=>M&&Z(),children:[e.jsx(Er,{asChild:!0,children:e.jsxs(We,{variant:"ghost",size:"sm",className:"gap-1.5 focus-visible:ring-0 focus-visible:ring-offset-0",children:[e.jsx(ps,{size:14,className:"shrink-0"}),e.jsx("span",{className:"text-xs",title:`${a.provider}/${a.model}`,children:Ql(a.model,28)}),D&&D.total_tokens>0&&e.jsxs("span",{className:"flex items-center gap-0.5 ml-0.5 text-[10px] text-[var(--fg-subtle)] tabular-nums shrink-0",children:[e.jsx(et,{size:9,className:"text-amber-500/70"}),Yl(D.total_tokens)]}),e.jsx(Rt,{size:12,className:"shrink-0"})]})}),e.jsxs(da,{align:"end",className:"w-56",children:[e.jsx(Pr,{children:i("header.switchAi")}),e.jsx(Ps,{}),f.length===0?e.jsx(Kt,{disabled:!0,children:i("common.loading")}):f.map(M=>e.jsxs(Kt,{onClick:()=>T(M),disabled:C,className:ve(a.provider===M.id&&"bg-[var(--accent-subtle)] text-[var(--accent)] font-medium",M.hasKey===!1&&"opacity-50"),children:[e.jsxs("span",{className:"flex items-center gap-2 flex-1",children:[e.jsx("span",{className:ve("inline-block w-1.5 h-1.5 rounded-full shrink-0",M.hasKey!==!1?"bg-emerald-500":"bg-[var(--fg-subtle)]")}),M.label]}),a.provider===M.id&&e.jsx("span",{className:"text-xs",children:"✓"})]},M.id)),e.jsx(Ps,{}),e.jsxs(Kt,{onClick:o,children:[e.jsx(Ts,{size:14}),e.jsx("span",{children:i("header.editEnvConfig")})]})]})]}),e.jsxs(Ht,{children:[e.jsx(Ot,{asChild:!0,children:e.jsx(We,{variant:"ghost",size:"icon-sm",onClick:()=>t(!0),children:e.jsx(kt,{size:16})})}),e.jsx(At,{children:i("header.newRecipe")})]}),e.jsxs(Ht,{children:[e.jsx(Ot,{asChild:!0,children:e.jsx(We,{variant:"ghost",size:"icon-sm",onClick:s,children:e.jsx(jt,{size:16})})}),e.jsx(At,{children:i("header.syncSnippets")})]}),e.jsxs(Ht,{children:[e.jsx(Ot,{asChild:!0,children:e.jsx(We,{variant:m?"accent":"ghost",size:"icon-sm",onClick:g,children:e.jsx(It,{size:16})})}),e.jsx(At,{children:i(m?"header.closeAiChat":"header.openAiChat")})]})," "]})]})})},eo=on,to=nn,Lr=l.forwardRef(({className:t,...s},a)=>e.jsx(tr,{ref:a,className:ve("fixed inset-0 z-50 bg-black/40 backdrop-blur-md","data-[state=open]:animate-in data-[state=open]:fade-in-0","data-[state=closed]:animate-out data-[state=closed]:fade-out-0",t),...s}));Lr.displayName=tr.displayName;const Mr=l.forwardRef(({className:t,children:s,size:a="md",hideClose:r=!1,...o},n)=>e.jsxs(to,{children:[e.jsx(Lr,{}),e.jsxs(sr,{ref:n,className:ve("fixed left-1/2 top-1/2 z-50 -translate-x-1/2 -translate-y-1/2","w-full rounded-[var(--radius-xl)] border border-[var(--border-default)] bg-[var(--bg-surface)] shadow-[var(--shadow-xl)]","dark:bg-[var(--bg-surface)]/95 dark:backdrop-blur-xl dark:border-[var(--glass-border)]","dark:shadow-[0_24px_80px_rgba(0,0,0,0.6),0_0_1px_rgba(255,255,255,0.08)]","data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%]","data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%]","duration-200",{"max-w-md":a==="sm","max-w-lg":a==="md","max-w-3xl":a==="lg","max-w-5xl":a==="xl","max-w-[calc(100vw-4rem)] max-h-[calc(100vh-4rem)]":a==="full"},t),...o,children:[s,!r&&e.jsxs(ln,{className:"absolute right-4 top-4 rounded-[var(--radius-sm)] p-1 text-[var(--fg-subtle)] opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-[var(--accent)] focus:ring-offset-2",children:[e.jsx(Xe,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Mr.displayName=sr.displayName;const so=l.forwardRef(({className:t,...s},a)=>e.jsx(ar,{ref:a,className:ve("text-lg font-semibold text-[var(--fg-default)]",t),...s}));so.displayName=ar.displayName;const ao=l.forwardRef(({className:t,...s},a)=>e.jsx(rr,{ref:a,className:ve("text-sm text-[var(--fg-muted)]",t),...s}));ao.displayName=rr.displayName;const Fr=l.forwardRef(({className:t,...s},a)=>e.jsx(ct,{ref:a,className:ve("flex h-full w-full flex-col overflow-hidden rounded-[var(--radius-xl)] text-[var(--fg-default)]",t),...s}));Fr.displayName=ct.displayName;const zr=l.forwardRef(({className:t,...s},a)=>e.jsxs("div",{className:"flex items-center border-b border-[var(--border-muted)] px-3",children:[e.jsx(Ct,{className:"mr-2 h-4 w-4 shrink-0 text-[var(--fg-subtle)]"}),e.jsx(ct.Input,{ref:a,className:ve("flex h-12 w-full bg-transparent py-3 text-sm text-[var(--fg-default)] outline-none placeholder:text-[var(--fg-subtle)]","disabled:cursor-not-allowed disabled:opacity-50",t),...s})]}));zr.displayName=ct.Input.displayName;const _r=l.forwardRef(({className:t,...s},a)=>e.jsx(ct.List,{ref:a,className:ve("max-h-[300px] overflow-y-auto overflow-x-hidden p-1",t),...s}));_r.displayName=ct.List.displayName;const Br=l.forwardRef((t,s)=>e.jsx(ct.Empty,{ref:s,className:"py-6 text-center text-sm text-[var(--fg-subtle)]",...t}));Br.displayName=ct.Empty.displayName;const As=l.forwardRef(({className:t,...s},a)=>e.jsx(ct.Group,{ref:a,className:ve("overflow-hidden p-1 text-[var(--fg-default)]","[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-[var(--fg-subtle)]",t),...s}));As.displayName=ct.Group.displayName;const Qs=l.forwardRef(({className:t,...s},a)=>e.jsx(ct.Separator,{ref:a,className:ve("-mx-1 h-px bg-[var(--border-muted)]",t),...s}));Qs.displayName=ct.Separator.displayName;const zt=l.forwardRef(({className:t,...s},a)=>e.jsx(ct.Item,{ref:a,className:ve("relative flex cursor-default gap-2 select-none items-center rounded-[var(--radius-md)] px-2.5 py-2 text-sm outline-none transition-colors","data-[selected=true]:bg-[var(--accent-subtle)] data-[selected=true]:text-[var(--accent)]","data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50",t),...s}));zt.displayName=ct.Item.displayName;function $s({className:t,...s}){return e.jsx("span",{className:ve("ml-auto text-xs tracking-widest text-[var(--fg-subtle)]",t),...s})}const ro={recipes:ir,spm:Dt,candidates:it,knowledge:Zs,depgraph:ta,knowledgegraph:Rs,guard:mt,skills:Qe,wiki:ft,ai:It,help:cr},Hs={recipes:"sidebar.recipes",spm:"sidebar.moduleExplorer",candidates:"sidebar.candidates",knowledge:"sidebar.batchManage",depgraph:"sidebar.depGraph",knowledgegraph:"sidebar.knowledgeGraph",guard:"sidebar.guard",skills:"sidebar.skills",wiki:"sidebar.repoWiki",ai:"sidebar.aiAssistant",help:"sidebar.help"},no=({open:t,onOpenChange:s,navigateToTab:a,setShowCreateModal:r,handleSyncSnippets:o,onSemanticSearch:n,searchQuery:d,setSearchQuery:u,onOpenLlmConfig:c,candidateCount:x=0})=>{const{t:v}=Me(),[g,m]=l.useState([]);l.useEffect(()=>{t&&g.length===0&&ne.fetchData().then(j=>{const C=(j==null?void 0:j.recipes)||[];m(C.slice(0,5).map(I=>({name:I.name||I.title,title:I.title||I.name})))}).catch(()=>{})},[t]),l.useEffect(()=>{const j=C=>{(C.metaKey||C.ctrlKey)&&C.key==="k"&&(C.preventDefault(),s(!t))};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[t,s]);const i=l.useCallback(j=>{j(),s(!1)},[s]),f=Object.keys(Hs);return e.jsx(eo,{open:t,onOpenChange:s,children:e.jsx(Mr,{size:"md",hideClose:!0,className:"!p-0 !top-[15vh] !translate-y-0 overflow-hidden",style:{backgroundColor:"var(--bg-root)"},children:e.jsxs(Fr,{className:"[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-[var(--fg-subtle)] [&_[cmdk-item]]:px-3 [&_[cmdk-item]]:py-2.5",children:[e.jsx(zr,{placeholder:v("commandPalette.searchPlaceholder")||"搜索知识、命令、页面...",value:d,onValueChange:u}),e.jsxs(_r,{className:"max-h-[360px]",children:[e.jsx(Br,{children:v("commandPalette.noResults")||"没有找到结果"}),g.length>0&&e.jsx(As,{heading:v("commandPalette.recent")||"最近",children:g.map(j=>e.jsxs(zt,{value:j.title,onSelect:()=>i(()=>{a("recipes"),u(j.title)}),children:[e.jsx(ft,{className:"mr-2 h-4 w-4 text-[var(--fg-subtle)]"}),e.jsx("span",{children:j.title})]},j.name))}),e.jsx(Qs,{}),e.jsx(As,{heading:v("commandPalette.pages")||"页面",children:f.map(j=>{const C=ro[j],I=j==="candidates"?{count:x}:void 0;return e.jsxs(zt,{value:v(Hs[j],I),onSelect:()=>i(()=>a(j)),children:[e.jsx(C,{className:"mr-2 h-4 w-4 text-[var(--fg-subtle)]"}),e.jsx("span",{children:v(Hs[j],I)})]},j)})}),e.jsx(Qs,{}),e.jsxs(As,{heading:v("commandPalette.commands")||"命令",children:[e.jsxs(zt,{value:"new recipe",onSelect:()=>i(()=>r(!0)),children:[e.jsx(kt,{className:"mr-2 h-4 w-4 text-[var(--fg-subtle)]"}),e.jsx("span",{children:v("header.newRecipe")}),e.jsx($s,{children:"⌘N"})]}),e.jsxs(zt,{value:"sync snippets",onSelect:()=>i(o),children:[e.jsx(jt,{className:"mr-2 h-4 w-4 text-[var(--fg-subtle)]"}),e.jsx("span",{children:v("header.syncSnippets")}),e.jsx($s,{children:"⌘S"})]}),n&&e.jsxs(zt,{value:"semantic search",onSelect:()=>i(()=>n(d)),children:[e.jsx(kn,{className:"mr-2 h-4 w-4 text-[var(--fg-subtle)]"}),e.jsx("span",{children:v("header.semanticSearch")}),e.jsx($s,{children:"⌘⇧F"})]}),c&&e.jsxs(zt,{value:"llm config",onSelect:()=>i(()=>c()),children:[e.jsx(Ts,{className:"mr-2 h-4 w-4 text-[var(--fg-subtle)]"}),e.jsx("span",{children:v("header.configureLlm")})]})]})]})]})})})},Gr="asd-drawer-wide";function lo(){try{return localStorage.getItem(Gr)==="1"}catch{return!1}}function ua(){const[t,s]=l.useState(lo),a=l.useCallback(()=>{s(r=>{const o=!r;try{localStorage.setItem(Gr,o?"1":"0")}catch{}return o})},[]);return{isWide:t,toggle:a}}const oo={xs:"h-6 text-[10px] px-1.5 gap-1 rounded",sm:"h-7 text-[11px] px-2 gap-1.5 rounded-md",md:"h-9 text-sm px-3 gap-2 rounded-lg"},io={xs:"text-[10px] px-1.5 py-1",sm:"text-[11px] px-2 py-1.5",md:"text-sm px-3 py-2"},lt=({value:t,onChange:s,options:a,className:r,contentClassName:o,placeholder:n="—",disabled:d=!1,size:u="sm",minWidth:c,direction:x="auto",id:v,name:g})=>{const[m,i]=l.useState(!1),[f,j]=l.useState(-1),[C,I]=l.useState(!1),D=l.useRef(null),$=l.useRef(null),O=a.find(F=>F.value===t),T=l.useCallback(()=>{if(x==="up")return!0;if(x==="down"||!D.current)return!1;const F=D.current.getBoundingClientRect(),k=window.innerHeight-F.bottom,E=Math.min(a.length*28+8,248);return k<E&&F.top>E},[x,a.length]),Z=l.useCallback(()=>{I(T()),i(!0),j(a.findIndex(F=>F.value===t))},[T,a,t]);l.useEffect(()=>{if(!m)return;const F=k=>{var E,B;(E=D.current)!=null&&E.contains(k.target)||(B=$.current)!=null&&B.contains(k.target)||i(!1)};return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[m]);const W=l.useCallback(F=>{if(d)return;const k=a.filter(E=>!E.disabled);F.key==="Enter"||F.key===" "?(F.preventDefault(),m?f>=0&&f<k.length&&(s(k[f].value),i(!1)):Z()):F.key==="Escape"?i(!1):F.key==="ArrowDown"?(F.preventDefault(),m?j(E=>Math.min(E+1,k.length-1)):Z()):F.key==="ArrowUp"&&(F.preventDefault(),j(E=>Math.max(E-1,0)))},[d,m,f,a,t,s,Z]);l.useEffect(()=>{var k;if(!m||f<0||!$.current)return;(k=$.current.querySelectorAll("[data-select-item]")[f])==null||k.scrollIntoView({block:"nearest"})},[f,m]);const M=F=>{var k;s(F),i(!1),(k=D.current)==null||k.focus()};return e.jsxs("div",{className:"relative inline-block",style:c?{minWidth:c}:void 0,children:[g&&e.jsx("input",{type:"hidden",name:g,value:t}),e.jsxs("button",{ref:D,id:v,type:"button",role:"combobox","aria-expanded":m,"aria-haspopup":"listbox",disabled:d,onClick:()=>{d||(m?i(!1):Z())},onKeyDown:W,className:ve("inline-flex items-center justify-between border border-[var(--border-default)] bg-[var(--bg-surface)] text-[var(--fg-default)] font-medium transition-colors","hover:border-[var(--border-emphasis)] hover:bg-[var(--bg-subtle)]","disabled:opacity-50 disabled:pointer-events-none",oo[u],r),children:[e.jsx("span",{className:"truncate",children:O?e.jsxs(e.Fragment,{children:[O.icon&&e.jsx("span",{className:"mr-1",children:O.icon}),O.label]}):n}),e.jsx(Rt,{size:u==="xs"?10:u==="sm"?12:14,className:ve("shrink-0 text-[var(--fg-muted)] transition-transform",m&&"rotate-180")})]}),m&&e.jsx("div",{ref:$,role:"listbox",className:ve("absolute z-50 min-w-full max-h-60 overflow-y-auto","rounded-[var(--radius-md)] border border-[var(--border-default)] bg-[var(--bg-surface)] shadow-[var(--shadow-lg)] p-0.5",C?"bottom-full mb-1 animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-1":"top-full mt-1 animate-in fade-in-0 zoom-in-95 slide-in-from-top-1",o),children:a.map((F,k)=>{const E=F.value===t,B=k===f;return e.jsxs("div",{"data-select-item":!0,role:"option","aria-selected":E,onClick:()=>!F.disabled&&M(F.value),onMouseEnter:()=>!F.disabled&&j(k),className:ve("flex items-center justify-between cursor-pointer rounded-[var(--radius-sm)] transition-colors",io[u],F.disabled&&"opacity-40 pointer-events-none",B&&"bg-[var(--bg-subtle)]",E&&"text-[var(--accent)] font-semibold"),children:[e.jsxs("span",{className:"flex items-center gap-1.5 truncate",children:[F.icon&&e.jsx("span",{children:F.icon}),F.label]}),E&&e.jsx(yt,{size:u==="xs"?10:12,className:"shrink-0 text-[var(--accent)]"})]},F.value)})})]})},pa=({currentPage:t,totalPages:s,totalItems:a,pageSize:r,onPageChange:o,onPageSizeChange:n,pageSizeOptions:d=[12,24,48,96]})=>{if(s<=1&&a<=d[0])return null;const{t:u}=Me(),c=(t-1)*r+1,x=Math.min(t*r,a),v=()=>{const g=[];if(s<=7)for(let i=1;i<=s;i++)g.push(i);else if(t<=3){for(let i=1;i<=5;i++)g.push(i);g.push("..."),g.push(s)}else if(t>=s-2){g.push(1),g.push("...");for(let i=s-5+1;i<=s;i++)g.push(i)}else{g.push(1),g.push("...");for(let i=t-1;i<=t+1;i++)g.push(i);g.push("..."),g.push(s)}return g};return e.jsxs("div",{className:"flex items-center justify-between mt-6 px-2",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("span",{className:"text-sm text-[var(--fg-secondary)]",children:u("pagination.showing",{start:c,end:x,total:a})}),n&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-[var(--fg-secondary)]",children:u("pagination.perPage")}),e.jsx(lt,{value:String(r),onChange:g=>n(Number(g)),options:d.map(g=>({value:String(g),label:String(g)})),size:"sm"}),e.jsx("span",{className:"text-sm text-[var(--fg-secondary)]",children:u("pagination.unit")})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>o(1),disabled:t===1,className:"p-1.5 rounded-md hover:bg-[var(--bg-subtle)] disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:u("pagination.firstPage"),children:e.jsx(Cn,{size:K.md,className:"text-[var(--fg-secondary)]"})}),e.jsx("button",{onClick:()=>o(t-1),disabled:t===1,className:"p-1.5 rounded-md hover:bg-[var(--bg-subtle)] disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:u("pagination.prevPage"),children:e.jsx(aa,{size:K.md,className:"text-[var(--fg-secondary)]"})}),e.jsx("div",{className:"flex items-center gap-1 mx-2",children:v().map((g,m)=>typeof g=="number"?e.jsx("button",{onClick:()=>o(g),className:`min-w-[32px] h-8 px-2 rounded-md text-sm font-medium transition-colors ${t===g?"bg-blue-600 text-white":"hover:bg-[var(--bg-subtle)] text-[var(--fg-secondary)]"}`,children:g},m):e.jsx("span",{className:"px-1 text-[var(--fg-muted)]",children:g},m))}),e.jsx("button",{onClick:()=>o(t+1),disabled:t===s,className:"p-1.5 rounded-md hover:bg-[var(--bg-subtle)] disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:u("pagination.nextPage"),children:e.jsx(rt,{size:K.md,className:"text-[var(--fg-secondary)]"})}),e.jsx("button",{onClick:()=>o(s),disabled:t===s,className:"p-1.5 rounded-md hover:bg-[var(--bg-subtle)] disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:u("pagination.lastPage"),children:e.jsx(Sn,{size:K.md,className:"text-[var(--fg-secondary)]"})})]})]})},co=Pt.memo(({code:t,lang:s,editorStyles:a})=>e.jsx(Ha,{language:s,style:Oa,showLineNumbers:!1,customStyle:{margin:0,padding:a.padding,fontSize:a.fontSize,lineHeight:a.lineHeight,borderRadius:"0",whiteSpace:"pre",verticalAlign:"top",display:"inline-block",minWidth:"100%",minHeight:"100%",backgroundColor:"#282c34"},codeTagProps:{style:{fontFamily:a.fontFamily,whiteSpace:"pre",verticalAlign:"top",fontSize:a.fontSize,lineHeight:a.lineHeight}},PreTag:"div",children:(()=>{const r=t;return r[r.length-1]===`
74
+ `?r+" ":r})()})),hs=19.5,uo=Pt.memo(({totalLines:t,scrollTop:s,viewportHeight:a,fontSize:r,lineHeight:o,fontFamily:n})=>{const u=Math.max(0,Math.floor(s/hs)-10),c=Math.ceil(a/hs)+20,x=Math.min(t,u+c),v=u*hs,g=Math.max(0,(t-x)*hs),m=[];for(let i=u;i<x;i++)m.push(e.jsx("div",{children:i+1},i));return e.jsx("div",{style:{paddingTop:v,paddingBottom:g,fontSize:r,lineHeight:o,fontFamily:n},children:m})}),Ls=({value:t,onChange:s,onCursorChange:a,language:r="javascript",height:o="400px",className:n="",placeholder:d="",rows:u,showLineNumbers:c=!0})=>{const x=l.useRef(null),v=l.useRef(null),g=l.useRef(null),m=l.useRef(null),[i,f]=l.useState(t),j=l.useRef(void 0);l.useEffect(()=>{const F=t.length>5e3?200:t.length>1e3?80:0;if(F===0){f(t);return}return j.current=setTimeout(()=>f(t),F),()=>clearTimeout(j.current)},[t]);const[C,I]=l.useState({top:0,height:400}),$={objectivec:"objectivec","objective-c":"objectivec","obj-c":"objectivec",objc:"objectivec",swift:"swift",javascript:"javascript",js:"javascript",typescript:"typescript",ts:"typescript",python:"python",py:"python",bash:"bash",shell:"bash",markdown:"markdown",md:"markdown",json:"json",text:"text"}[r==null?void 0:r.toLowerCase()]||(r==null?void 0:r.toLowerCase())||"text",O=l.useMemo(()=>({padding:"1rem 1.25rem",fontSize:"0.8125rem",lineHeight:1.5,fontFamily:"ui-monospace, monospace",minHeight:"200px"}),[]),T=l.useCallback(F=>{const k=F.currentTarget;g.current&&(g.current.scrollTop=k.scrollTop,g.current.scrollLeft=k.scrollLeft),m.current&&(m.current.scrollTop=k.scrollTop),I({top:k.scrollTop,height:k.clientHeight})},[]),Z=l.useCallback(F=>{s(F.target.value),a&&a(F.target.selectionStart||0)},[s,a]),W=l.useCallback(F=>{a&&a(F.currentTarget.selectionStart||0)},[a]),M=l.useMemo(()=>(t||"").split(`
75
+ `).length,[t]);return l.useEffect(()=>{v.current&&I(F=>({...F,height:v.current.clientHeight}))},[]),e.jsxs("div",{ref:x,className:`relative overflow-hidden ${n}`,style:{height:u?"auto":o,minHeight:O.minHeight,display:"flex",borderRadius:"0",backgroundColor:"#282c34"},children:[c&&e.jsx("div",{ref:m,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(uo,{totalLines:M,scrollTop:C.top,viewportHeight:C.height,fontSize:O.fontSize,lineHeight:O.lineHeight,fontFamily:O.fontFamily})}),e.jsxs("div",{className:"relative flex-1",style:{borderRadius:"0",backgroundColor:"#282c34"},children:[e.jsx("div",{ref:g,className:"absolute inset-0 pointer-events-none highlight-scroll-hidden",style:{zIndex:0,overflow:"scroll"},children:e.jsx(co,{code:i||d,lang:$,editorStyles:O})}),e.jsx("textarea",{ref:v,value:t,onChange:Z,onSelect:W,onKeyUp:W,onClick:W,onScroll:T,rows:u,placeholder:d,className:"absolute inset-0 w-full h-full resize-none outline-none editor-with-dark-scrollbar",style:{padding:O.padding,lineHeight:O.lineHeight,fontSize:O.fontSize,fontFamily:O.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"}})]})]})},ma=({badges:t,metadata:s,tags:a,maxTags:r,id:o,sourceFile:n,sourceFileLabel:d="源文件"})=>{const u=r&&a?a.slice(0,r):a;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)] space-y-3",children:[t.length>0&&e.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:t.map((c,x)=>{const v=c.icon;return e.jsxs("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border inline-flex items-center gap-1 ${c.className}`,children:[v&&e.jsx(v,{size:10}),c.label]},x)})}),(s.length>0||o||n)&&e.jsxs("div",{className:"flex flex-wrap gap-x-5 gap-y-2 text-xs",children:[s.map((c,x)=>{const v=c.icon;return e.jsxs("div",{className:`flex items-center gap-1.5${c.fullWidth?" basis-full mt-0.5":""}`,children:[e.jsx(v,{size:11,className:`${c.iconClass} shrink-0`}),e.jsx("span",{className:"text-[var(--fg-muted)]",children:c.label}),c.isCode?e.jsx("code",{className:"font-mono text-[11px] text-[var(--fg-secondary)] break-all",children:c.value}):e.jsx("span",{className:`font-medium text-[var(--fg-secondary)]${c.mono?" font-mono text-[11px]":""}`,children:c.value})]},x)}),o&&e.jsxs("div",{className:"flex items-center gap-1.5 basis-full mt-0.5",children:[e.jsx(ea,{size:11,className:"text-[var(--fg-muted)] shrink-0"}),e.jsx("span",{className:"text-[var(--fg-muted)]",children:"ID"}),e.jsx("code",{className:"font-mono text-[11px] text-[var(--fg-secondary)] break-all",children:o})]}),n&&e.jsxs("div",{className:"flex items-center gap-1.5 basis-full",children:[e.jsx(Dt,{size:11,className:"text-[var(--fg-muted)] shrink-0"}),e.jsx("span",{className:"text-[var(--fg-muted)]",children:d}),e.jsx("code",{className:"font-mono text-[11px] text-[var(--fg-secondary)] break-all",title:n,children:n})]})]})]}),u&&u.length>0&&e.jsxs("div",{className:"px-6 py-3 border-b border-[var(--border-default)] flex flex-wrap items-center gap-1.5",children:[e.jsx(mr,{size:11,className:"text-[var(--fg-muted)] mr-0.5"}),u.map((c,x)=>e.jsx("span",{className:"text-[9px] px-2 py-0.5 rounded bg-[var(--accent-subtle)] text-[var(--accent)] border border-[var(--border-default)] font-medium",children:typeof c=="string"?c:String(c)},x))]})]})},po=({label:t,text:s})=>s?e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-1.5 block",children:t}),e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] leading-relaxed",children:s})]}):null,mo=({reasoning:t,labels:s,filterSubmitted:a=!1})=>{if(!t)return null;const r=t,o=r.whyStandard&&(!a||!/^Submitted via /i.test(r.whyStandard));return o||r.sources&&r.sources.length>0||r.confidence!=null&&r.confidence>0?e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(Ut,{size:11,className:"text-amber-400"})," ",s.section]}),e.jsxs("div",{className:"bg-amber-50/30 border border-amber-100 rounded-xl p-4 space-y-2.5",children:[o&&e.jsx("p",{className:"text-sm text-[var(--fg-primary)] leading-relaxed",children:r.whyStandard}),r.sources&&r.sources.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] font-bold",children:s.source}),r.sources.map((d,u)=>e.jsx("code",{className:"text-[10px] px-2 py-0.5 bg-[var(--bg-surface)] border border-amber-200 rounded text-amber-700 font-mono",children:d},u))]}),r.confidence!=null&&r.confidence>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] font-bold",children:s.confidence}),e.jsx("div",{className:"flex-1 max-w-[160px] h-1.5 bg-[var(--border-default)] rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-amber-400 rounded-full",style:{width:`${Math.round((r.confidence??0)*100)}%`}})}),e.jsxs("span",{className:"text-[10px] font-bold text-amber-600",children:[Math.round((r.confidence??0)*100),"%"]})]}),r.alternatives&&r.alternatives.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 pt-1",children:[e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] font-bold",children:s.alternatives}),r.alternatives.map((d,u)=>e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded text-[var(--fg-secondary)]",children:d},u))]})]})]}):null},xo=({quality:t,labels:s,formatFixed:a=!1})=>{if(!(t!=null&&t.grade)||t.grade==="F")return null;const r=o=>a?o.toFixed(2):String(o);return e.jsxs("div",{className:"px-6 py-3 border-b border-[var(--border-default)]",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:s.section}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("span",{className:`text-2xl font-black ${t.grade==="A"?"text-emerald-600":t.grade==="B"?"text-blue-600":t.grade==="C"?"text-amber-600":t.grade==="D"?"text-orange-600":"text-[var(--fg-muted)]"}`,children:t.grade}),e.jsxs("div",{className:"flex-1 grid grid-cols-3 gap-2 text-xs",children:[t.completeness!=null&&t.completeness>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-sm font-bold text-[var(--fg-primary)]",children:r(t.completeness)}),e.jsx("div",{className:"text-[var(--fg-muted)]",children:s.completeness})]}),t.adaptation!=null&&t.adaptation>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-sm font-bold text-[var(--fg-primary)]",children:r(t.adaptation)}),e.jsx("div",{className:"text-[var(--fg-muted)]",children:s.adaptation})]}),t.documentation!=null&&t.documentation>0&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-sm font-bold text-[var(--fg-primary)]",children:r(t.documentation)}),e.jsx("div",{className:"text-[var(--fg-muted)]",children:s.documentation})]})]})]})]})},go=({label:t,content:s})=>s?e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(ft,{size:11,className:"text-blue-400"})," ",t]}),e.jsx("div",{className:"bg-blue-50/30 border border-blue-100 rounded-xl p-4",children:e.jsx("div",{className:"markdown-body text-sm text-[var(--fg-primary)] leading-relaxed",children:e.jsx(Et,{content:s})})})]}):null,ho=({label:t,code:s,language:a})=>{if(!s)return null;const r=a==="objc"||a==="objective-c"?"objectivec":a||"text";return e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(Tt,{size:11,className:"text-emerald-500"})," ",t]}),e.jsx(St,{code:s,language:r,showLineNumbers:!0})]})},fo=({label:t,headers:s})=>!s||s.length===0?null:e.jsxs("div",{className:"px-6 py-3 border-b border-[var(--border-default)]",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:t}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map((a,r)=>e.jsx("code",{className:"px-2.5 py-1 bg-violet-50 text-violet-700 border border-violet-100 rounded-md text-[10px] font-mono font-medium",children:a},r))})]}),bo=({label:t,text:s})=>s?e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:t}),e.jsx("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-xl p-4",children:e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] leading-relaxed",children:s})})]}):null,vo=({label:t,steps:s})=>!s||s.length===0?null:e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:t}),e.jsx("div",{className:"space-y-2",children:s.map((a,r)=>{if(typeof a=="string")return e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-lg p-3 border border-[var(--border-default)] flex items-start gap-2.5",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0 mt-0.5",children:r+1}),e.jsx("p",{className:"text-xs text-[var(--fg-primary)] leading-relaxed",children:a})]},r);const o=typeof a.title=="string"?a.title:"",n=typeof a.description=="string"?a.description:"",d=typeof a.code=="string"?a.code:"";return e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-lg p-3 border border-[var(--border-default)]",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0",children:r+1}),o&&e.jsx("span",{className:"text-xs font-bold text-[var(--fg-primary)]",children:o})]}),n&&e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] ml-7 leading-relaxed",children:n}),d&&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:d})]},r)})})]}),yo=({label:t,constraints:s})=>{var o,n,d,u,c,x,v,g;if(!s)return null;const a=s,r=(((o=a.guards)==null?void 0:o.length)||0)+(((n=a.boundaries)==null?void 0:n.length)||0)+(((d=a.preconditions)==null?void 0:d.length)||0)+(((u=a.sideEffects)==null?void 0:u.length)||0);return r?e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(mt,{size:11,className:"text-amber-500"})," ",t," ",e.jsx("span",{className:"text-amber-500 font-mono",children:r})]}),e.jsxs("div",{className:"space-y-1.5 text-xs text-[var(--fg-secondary)]",children:[(c=a.guards)==null?void 0:c.map((m,i)=>e.jsxs("div",{className:"flex gap-1.5 items-start",children:[e.jsx("span",{className:`text-xs mt-0.5 ${m.severity==="error"?"text-[var(--status-error)]":"text-[var(--status-warning)]"}`,children:"●"}),e.jsx("code",{className:"font-mono text-[10px] bg-[var(--bg-subtle)] px-1.5 py-0.5 rounded",children:m.pattern}),m.message&&e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)]",children:["— ",m.message]})]},i)),(x=a.boundaries)==null?void 0:x.map((m,i)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("span",{className:"text-[var(--status-warning)]",children:"●"}),m]},i)),(v=a.preconditions)==null?void 0:v.map((m,i)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("span",{className:"text-[var(--accent)]",children:"◆"}),m]},i)),(g=a.sideEffects)==null?void 0:g.map((m,i)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("span",{className:"text-pink-400",children:"⚡"}),m]},i))]})]}):null},jo=({delivery:t,language:s})=>{if(!t)return null;const{topicHint:a,whenClause:r,doClause:o,dontClause:n,coreCode:d}=t;if(!o&&!r&&!n&&!a&&!d)return null;const u=s==="objectivec"||s==="objc"||s==="objective-c"?"objectivec":s||"text";return e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(ht,{size:11,className:"text-indigo-400"})," Cursor Delivery"]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-xl p-4 text-xs space-y-1.5",children:[a&&e.jsxs("div",{children:[e.jsx("span",{className:"text-indigo-400 font-medium",children:"Topic:"}),e.jsx("span",{className:"text-[var(--fg-primary)]",children:a})]}),r&&e.jsxs("div",{children:[e.jsx("span",{className:"text-blue-400 font-medium",children:"When:"}),e.jsx("span",{className:"text-[var(--fg-primary)]",children:r})]}),o&&e.jsxs("div",{children:[e.jsx("span",{className:"text-emerald-400 font-medium",children:"Do:"}),e.jsx("span",{className:"text-[var(--fg-primary)]",children:o})]}),n&&e.jsxs("div",{children:[e.jsx("span",{className:"text-red-400 font-medium",children:"Don't:"}),e.jsx("span",{className:"text-[var(--fg-primary)]",children:n})]}),d&&e.jsxs("div",{children:[e.jsx("span",{className:"text-purple-400 font-medium",children:"Core Code:"}),e.jsx("div",{className:"mt-1",children:e.jsx(St,{code:d,language:u})})]})]})]})},$e={Description:po,Reasoning:mo,Quality:xo,MarkdownSection:go,CodePattern:ho,Headers:fo,Rationale:bo,Steps:vo,Constraints:yo,Delivery:jo},wo=qa("inline-flex items-center rounded-[var(--radius-sm)] px-2 py-0.5 text-xs font-medium leading-none whitespace-nowrap transition-all",{variants:{variant:{default:"bg-[var(--bg-subtle)] text-[var(--fg-muted)] border border-[var(--border-default)]",blue:"bg-[var(--accent-subtle)] text-[var(--accent)] border border-[var(--accent)]/15",green:"bg-[var(--success-subtle)] text-[var(--success)] border border-[var(--success)]/15",amber:"bg-[var(--warning-subtle)] text-[var(--warning)] border border-[var(--warning)]/15",red:"bg-[var(--danger-subtle)] text-[var(--danger)] border border-[var(--danger)]/15",info:"bg-[var(--info-subtle)] text-[var(--info)] border border-[var(--info)]/15",outline:"border border-[var(--border-default)] text-[var(--fg-muted)] bg-transparent",gradient:"text-white border-0"}},defaultVariants:{variant:"default"}}),Xs=l.forwardRef(({className:t,variant:s,style:a,...r},o)=>{const n=s==="gradient"?{background:"var(--accent-gradient)",...a}:a;return e.jsx("span",{ref:o,className:ve(wo({variant:s,className:t})),style:n,...r})});Xs.displayName="Badge";const No=420,ko=({className:t="bg-black/20 backdrop-blur-[1px]"})=>e.jsx("div",{className:`absolute inset-0 ${t}`}),Ze=({children:t,onClick:s,className:a="",style:r})=>{const{isOpen:o}=xs();return e.jsx("div",{className:`fixed inset-0 overflow-hidden ${a}`,style:{right:o?No:0,...r},onClick:s,children:t})};Ze.Backdrop=ko;const Co=l.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,className:ve("rounded-[var(--radius-lg)] border border-[var(--border-default)] bg-[var(--bg-surface)]","transition-all duration-250 ease-out","hover:border-[var(--border-emphasis)] hover:shadow-[var(--shadow-lg)] hover:-translate-y-0.5","dark:hover:shadow-[0_8px_32px_rgba(0,0,0,0.4),0_0_1px_rgba(255,255,255,0.06)]",t),...s}));Co.displayName="Card";const So=l.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,className:ve("flex items-center justify-between p-5 pb-0",t),...s}));So.displayName="CardHeader";const Ao=l.forwardRef(({className:t,...s},a)=>e.jsx("h3",{ref:a,className:ve("text-sm font-semibold text-[var(--fg-default)] leading-tight tracking-tight",t),...s}));Ao.displayName="CardTitle";const Do=l.forwardRef(({className:t,...s},a)=>e.jsx("p",{ref:a,className:ve("text-sm text-[var(--fg-muted)] leading-relaxed",t),...s}));Do.displayName="CardDescription";const Io=l.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,className:ve("p-5",t),...s}));Io.displayName="CardContent";const Ro=l.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,className:ve("flex items-center px-5 pb-5 pt-0",t),...s}));Ro.displayName="CardFooter";const To=l.forwardRef(({className:t,...s},a)=>e.jsx(cn,{ref:a,className:ve("border-b border-[var(--border-muted)]",t),...s}));To.displayName="AccordionItem";const Eo=l.forwardRef(({className:t,children:s,...a},r)=>e.jsx(dn,{className:"flex",children:e.jsxs(nr,{ref:r,className:ve("flex flex-1 items-center justify-between py-3 text-sm font-medium text-[var(--fg-default)] transition-all","hover:text-[var(--fg-default)] [&[data-state=open]>svg]:rotate-180",t),...a,children:[s,e.jsx(Rt,{className:"h-4 w-4 shrink-0 text-[var(--fg-subtle)] transition-transform duration-200"})]})}));Eo.displayName=nr.displayName;const Po=l.forwardRef(({className:t,children:s,...a},r)=>e.jsx(lr,{ref:r,className:"overflow-hidden text-sm data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...a,children:e.jsx("div",{className:ve("pb-4 pt-0",t),children:s})}));Po.displayName=lr.displayName;function xt({className:t,...s}){return e.jsx("div",{className:ve("rounded-[var(--radius-md)] animate-shimmer",t),...s})}const $r={sm:"w-[min(92vw,560px)]",md:"w-[min(92vw,700px)]","md-lg":"w-[min(92vw,800px)]",lg:"w-[min(92vw,960px)]",xl:"w-[min(92vw,1100px)]",full:"w-[min(96vw,1280px)]"};function Lo({title:t,subtitle:s,className:a,children:r}){return e.jsxs("div",{className:ve("flex items-center justify-between px-5 py-3 border-b border-[var(--border-default)] bg-[var(--bg-surface)] shrink-0",a),children:[t&&e.jsxs("div",{className:"flex-1 min-w-0 mr-3",children:[e.jsx("h3",{className:"font-bold text-[var(--fg-primary)] text-lg leading-snug break-words",children:t}),s&&e.jsx("span",{className:"text-xs text-[var(--fg-muted)] mt-0.5 block truncate",children:s})]}),r&&e.jsx("div",{className:"flex items-center gap-1 shrink-0",children:r})]})}function Mo({currentIndex:t,total:s,onPrev:a,onNext:r,hasPrev:o,hasNext:n}){const d=o!==void 0?!o:t<=0,u=n!==void 0?!n:t>=s-1;return e.jsxs(e.Fragment,{children:[e.jsx(We,{variant:"ghost",size:"icon-sm",onClick:a,disabled:d,children:e.jsx(aa,{size:16})}),e.jsxs("span",{className:"text-xs text-[var(--fg-muted)] tabular-nums",children:[t+1,"/",s]}),e.jsx(We,{variant:"ghost",size:"icon-sm",onClick:r,disabled:u,children:e.jsx(rt,{size:16})})]})}function Fo({isWide:t,onToggle:s,title:a}){return e.jsx(We,{variant:"ghost",size:"icon-sm",onClick:s,title:a,children:t?e.jsx(An,{size:16}):e.jsx(xr,{size:16})})}function zo({children:t}){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-px h-5 bg-[var(--border-default)] mx-1"}),t]})}function _o({onClose:t}){return e.jsx(We,{variant:"ghost",size:"icon-sm",onClick:t,children:e.jsx(Xe,{size:16})})}function Bo({className:t,padded:s=!1,children:a}){return e.jsx("div",{className:ve("flex-1 overflow-y-auto",s&&"p-5 space-y-5",t),children:a})}function Go({className:t,children:s}){return e.jsx("div",{className:ve("shrink-0 border-t border-[var(--border-default)] px-5 py-3 bg-[var(--bg-surface)] flex items-center justify-between",t),children:s})}function $o({width:t,size:s="md",animationDuration:a="0.25s",className:r,children:o}){return e.jsx("div",{className:ve("relative h-full bg-[var(--bg-surface)] dark:bg-[var(--bg-surface)]/95 dark:backdrop-blur-xl shadow-2xl flex flex-col border-l border-[var(--border-default)] dark:border-[var(--glass-border)]",t||$r[s],r),style:{animation:`slideInRight ${a} ease-out`},onClick:n=>n.stopPropagation(),children:o})}function Te({open:t,onClose:s,size:a="md",className:r,animationDuration:o="0.25s",children:n}){return t?e.jsxs(Ze,{className:"z-30 flex justify-end",onClick:s,children:[e.jsx(Ze.Backdrop,{className:"bg-black/20 dark:bg-black/40 backdrop-blur-sm"}),e.jsx("div",{className:ve("relative h-full bg-[var(--bg-surface)] dark:bg-[var(--bg-surface)]/95 dark:backdrop-blur-xl shadow-2xl flex flex-col border-l border-[var(--border-default)] dark:border-[var(--glass-border)] dark:shadow-[0_0_80px_rgba(0,0,0,0.5)]",$r[a],r),style:{animation:`slideInRight ${o} ease-out`},onClick:d=>d.stopPropagation(),children:n})]}):null}Te.Header=Lo;Te.Nav=Mo;Te.WidthToggle=Fo;Te.HeaderActions=zo;Te.CloseButton=_o;Te.Body=Bo;Te.Footer=Go;Te.Panel=$o;const Os={rule:{label:"Rule",color:"text-red-700",bg:"bg-red-50",border:"border-red-200",icon:mt},pattern:{label:"Pattern",color:"text-violet-700",bg:"bg-violet-50",border:"border-violet-200",icon:Ut},fact:{label:"Fact",color:"text-cyan-700",bg:"bg-cyan-50",border:"border-cyan-200",icon:Qe}},fs={"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 Ho(t){var s;return((s=t.content)==null?void 0:s.pattern)||""}function Oo(t){const s=(t.language||"").toLowerCase();return["objectivec","objc","objective-c","obj-c"].includes(s)?"objectivec":t.language||"text"}function Hr(t){if(t==null)return!1;const s=typeof t=="string"?new Date(t).getTime():t;return!isNaN(s)&&s>9466848e5}function Ia(t){return Hr(t)?(typeof t=="string"?new Date(t):new Date(t)).toLocaleDateString("zh-CN",{year:"numeric",month:"2-digit",day:"2-digit"}):""}const Ko=({recipes:t,handleDeleteRecipe:s,onRefresh:a,idTitleMap:r,currentPage:o,onPageChange:n,pageSize:d,onPageSizeChange:u})=>{const{t:c}=Me(),[x,v]=l.useState("default"),[g,m]=l.useState("desc"),i=[{key:"default",label:c("recipes.sortNewest"),defaultDir:"desc"},{key:"authorityScore",label:c("recipes.qualityAuthorityScore"),defaultDir:"desc"},{key:"authority",label:c("recipes.qualityExcellent"),defaultDir:"desc"},{key:"totalUsage",label:c("recipes.qualityBasic"),defaultDir:"desc"},{key:"lastUsed",label:c("recipes.sortQuality"),defaultDir:"desc"},{key:"name",label:c("recipes.sortAlpha"),defaultDir:"asc"},{key:"category",label:c("recipes.knowledgeType"),defaultDir:"asc"}],[f,j]=l.useState(1),[C,I]=l.useState(12),D=o??f,$=d??C,O=n??j,T=u?y=>u(y):y=>{I(y),j(1)},{isWide:Z,toggle:W}=ua(),[M,F]=l.useState(null),[k,E]=l.useState("view"),[B,b]=l.useState({title:"",description:"",markdown:"",codePattern:"",rationale:"",tags:[],tagInput:""}),[h,L]=l.useState(!1),ie=l.useRef(!0),[Y,ge]=l.useState(!1),[Ne,fe]=l.useState("related"),[w,N]=l.useState("");l.useEffect(()=>()=>{ie.current=!1},[]);const P=[{key:"related",label:c("knowledgeGraph.relationAssociates"),icon:"∼"},{key:"dependsOn",label:c("knowledgeGraph.relationDependsOn"),icon:"⊕"},{key:"inherits",label:c("knowledgeGraph.relationInherits"),icon:"↑"},{key:"implements",label:c("knowledgeGraph.relationImplements"),icon:"◇"},{key:"calls",label:c("knowledgeGraph.relationCalls"),icon:"→"},{key:"dataFlow",label:c("knowledgeGraph.relationDataFlow"),icon:"⇢"},{key:"conflicts",label:c("knowledgeGraph.relationConflicts"),icon:"✕"},{key:"extends",label:c("knowledgeGraph.relationExtends"),icon:"⊃"}],U=y=>{var p,z,G,A;F(y),E("view"),b({title:((p=y.name)==null?void 0:p.replace(/\.md$/,""))||"",description:y.description||"",markdown:((z=y.content)==null?void 0:z.markdown)||"",codePattern:((G=y.content)==null?void 0:G.pattern)||"",rationale:((A=y.content)==null?void 0:A.rationale)||"",tags:y.tags||[],tagInput:""}),ge(!1),N("")},Q=()=>{F(null),E("view"),ge(!1),N("")},ue=async()=>{if(!(!M||h)){L(!0);try{const y=M.id||M.name;await ne.knowledgeUpdate(y,{title:B.title,description:B.description,tags:B.tags,content:{...M.content||{},pattern:B.codePattern,markdown:B.markdown,rationale:B.rationale}}),ie.current&&(E("view"),a==null||a())}catch(y){re((y==null?void 0:y.message)||c("common.saveFailed"),{title:c("common.operationFailed"),type:"error"})}finally{ie.current&&L(!1)}}},ce=async y=>{if(M)try{await ne.setRecipeAuthority(M.id||M.name,y),a==null||a()}catch(p){re((p==null?void 0:p.message)||c("common.operationFailed"),{title:c("common.operationFailed"),type:"error"})}},ke=y=>{const p=y.replace(/\.md$/i,"").toLowerCase();return t.find(z=>at(z).toLowerCase()===p)},Le=l.useMemo(()=>{const y=new Map;if(r)for(const[p,z]of Object.entries(r))y.set(p,z);for(const p of t)p.id&&y.set(p.id,at(p)),p.name&&y.set(p.name,at(p));return y},[t,r]),[Ie,Be]=l.useState(!1),H=async(y,p)=>{if(!M||Ie)return;const z={};if(M.relations)for(const[J,ae]of Object.entries(M.relations))z[J]=[...ae];const G=z[y]||[],A=p.replace(/\.md$/i,"");if(G.some(J=>(typeof J=="string"?J:J.target||J.id||J.title||"").replace(/\.md$/i,"").toLowerCase()===A.toLowerCase()))return;z[y]=[...G,A];const _=M;F({...M,relations:z}),ge(!1),N(""),Be(!0);try{await ne.updateRecipeRelations(M.id||M.name,z)}catch(J){F(_),re((J==null?void 0:J.message)||c("common.operationFailed"),{title:c("common.operationFailed"),type:"error"})}finally{Be(!1)}},S=async(y,p)=>{if(!M||Ie)return;const z={};if(M.relations)for(const[_,J]of Object.entries(M.relations))z[_]=[...J];const G=z[y]||[];z[y]=G.filter(_=>(typeof _=="string"?_:_.target||_.id||_.title||"").replace(/\.md$/i,"").toLowerCase()!==p.replace(/\.md$/i,"").toLowerCase()),z[y].length===0&&delete z[y];const A=M;F({...M,relations:z}),Be(!0);try{await ne.updateRecipeRelations(M.id||M.name,z)}catch(_){F(A),re((_==null?void 0:_.message)||c("common.operationFailed"),{title:c("common.operationFailed"),type:"error"})}finally{Be(!1)}};l.useEffect(()=>{M&&!t.find(y=>at(y)===at(M))&&Q()},[t,M]),l.useEffect(()=>{o==null&&j(1)},[t.length,o]);const se=Pt.useMemo(()=>{if(x==="default")return t;const y=[...t],p=g==="asc"?1:-1;return y.sort((z,G)=>{var J,ae,be,X,xe,he,Fe,Oe,qe,te,de,Ke;let A=0,_=0;switch(x){case"name":return A=at(z).toLowerCase(),_=at(G).toLowerCase(),p*(A<_?-1:A>_?1:0);case"authorityScore":A=((J=z.stats)==null?void 0:J.authorityScore)??-1,_=((ae=G.stats)==null?void 0:ae.authorityScore)??-1;break;case"authority":A=((be=z.stats)==null?void 0:be.authority)??-1,_=((X=G.stats)==null?void 0:X.authority)??-1;break;case"totalUsage":A=(((xe=z.stats)==null?void 0:xe.guardUsageCount)??0)+(((he=z.stats)==null?void 0:he.humanUsageCount)??0)+(((Fe=z.stats)==null?void 0:Fe.aiUsageCount)??0),_=(((Oe=G.stats)==null?void 0:Oe.guardUsageCount)??0)+(((qe=G.stats)==null?void 0:qe.humanUsageCount)??0)+(((te=G.stats)==null?void 0:te.aiUsageCount)??0);break;case"lastUsed":{const He=(de=z.stats)!=null&&de.lastUsedAt?new Date(z.stats.lastUsedAt).getTime():0,Ue=(Ke=G.stats)!=null&&Ke.lastUsedAt?new Date(G.stats.lastUsedAt).getTime():0;A=isNaN(He)?0:He,_=isNaN(Ue)?0:Ue;break}case"category":return A=(z.category||"").toLowerCase(),_=(G.category||"").toLowerCase(),p*(A<_?-1:A>_?1:0)}return p*(A-_)}),y},[t,x,g]),we=Math.ceil(se.length/$),V=(D-1)*$,ye=se.slice(V,V+$),Re=y=>{O(y),window.scrollTo({top:0,behavior:"smooth"})},je=M?se.findIndex(y=>at(y)===at(M)):-1,pe=()=>{je>0&&U(se[je-1])},_e=()=>{je<se.length-1&&U(se[je+1])},q=({recipe:y})=>{const p=y.kind?Os[y.kind]:null,z=y.category||"Utility",G=y.knowledgeType,A=[];return p&&A.push(p.label),A.push(z),G&&fs[G]&&A.push(c(fs[G])),y.language&&A.push(y.language.toUpperCase()),y.trigger&&A.push(y.trigger),e.jsx("span",{className:"text-[11px] text-[var(--fg-muted)] truncate",children:A.join(" · ")})};return e.jsxs("div",{className:"relative pb-6",children:[t.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-24 text-center",children:[e.jsx(Dn,{size:48,className:"text-[var(--fg-muted)] mb-4 opacity-40"}),e.jsx("p",{className:"font-medium text-[var(--fg-secondary)] mb-1",children:c("recipes.noResults")}),e.jsx("p",{className:"text-sm text-[var(--fg-muted)]",children:c("recipes.noContent")})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-4 border-b border-[var(--border-default)] pb-3",children:[i.map(y=>{const p=x===y.key;return e.jsxs("button",{onClick:()=>{p?m(z=>z==="asc"?"desc":"asc"):(v(y.key),m(y.defaultDir)),O(1)},className:ve("px-4 py-1.5 rounded-md text-xs font-medium transition-colors flex items-center gap-1",p?"bg-[var(--accent-subtle)] text-[var(--accent)] border border-[var(--accent-emphasis)]":"text-[var(--fg-muted)] hover:bg-[var(--bg-subtle)] border border-transparent"),children:[y.label,p&&x!=="default"&&(g==="asc"?e.jsx(In,{size:12}):e.jsx(Rn,{size:12}))]},y.key)}),e.jsx("span",{className:"ml-auto text-xs text-[var(--fg-muted)]",children:c("recipes.totalCount",{count:t.length})})]}),e.jsx("div",{children:ye.map(y=>{var _;const p=at(y),z=y.description||y.usageGuide||"",G=M&&at(M)===p,A=y.kind?Os[y.kind]:null;return e.jsx("div",{onClick:()=>U(y),className:ve("group relative cursor-pointer py-4 px-4 rounded-lg transition-colors hover:bg-[var(--bg-subtle)] after:absolute after:bottom-0 after:left-4 after:right-4 after:h-px after:bg-[var(--border-default)] last:after:hidden",G&&"bg-[var(--accent-subtle)]"),children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] text-sm break-words leading-snug truncate",children:p}),A&&e.jsx(Xs,{variant:A.label==="Rule"?"red":A.label==="Pattern"?"blue":"default",className:"text-[9px] uppercase shrink-0",children:A.label}),((_=y.stats)==null?void 0:_.authority)!=null&&y.stats.authority>=4&&e.jsxs("span",{className:"text-amber-500 text-[11px] shrink-0",children:["★ ",y.stats.authority]})]}),z&&e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] line-clamp-1 leading-relaxed mb-1.5",children:z.replace(/^#+\s*/gm,"").replace(/\*\*/g,"")}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(q,{recipe:y,compact:!0}),y.tags&&y.tags.length>0&&e.jsxs("span",{className:"text-[11px] text-[var(--fg-muted)]",children:[y.tags.slice(0,3).join(", "),y.tags.length>3&&` +${y.tags.length-3}`]})]})]}),e.jsx("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity shrink-0",children:e.jsxs(Tr,{children:[e.jsx(Er,{asChild:!0,children:e.jsx(We,{variant:"ghost",size:"icon-sm",onClick:J=>J.stopPropagation(),children:e.jsx(Tn,{size:14})})}),e.jsxs(da,{align:"end",children:[e.jsxs(Kt,{onClick:J=>{J.stopPropagation(),U(y)},children:[e.jsx(Es,{size:14,className:"mr-2"})," ",c("common.preview")]}),e.jsxs(Kt,{onClick:J=>{J.stopPropagation(),U(y),E("edit")},children:[e.jsx($t,{size:14,className:"mr-2"})," ",c("common.edit")]}),e.jsx(Ps,{}),e.jsxs(Kt,{className:"text-[var(--status-error)]",onClick:J=>{J.stopPropagation(),s(y.name||y.id)},children:[e.jsx(ot,{size:14,className:"mr-2"})," ",c("recipes.deleteRecipe")]})]})]})})]})},y.id||p)})})]}),t.length>0&&e.jsx(pa,{currentPage:D,totalPages:we,totalItems:se.length,pageSize:$,onPageChange:Re,onPageSizeChange:T}),M&&(()=>{var _,J,ae,be;const y=M,p=at(y),z=Ho(y),G=Oo(y),A=y.content;return e.jsxs(Te,{open:!!M,onClose:Q,size:Z?"lg":"md",children:[e.jsxs(Te.Header,{title:p,children:[e.jsx(Te.Nav,{currentIndex:je,total:se.length,onPrev:pe,onNext:_e}),e.jsxs(Te.HeaderActions,{children:[e.jsxs("div",{className:"flex bg-[var(--bg-subtle)] p-0.5 rounded-lg mr-1",children:[e.jsxs("button",{onClick:()=>E("view"),className:ve("px-2.5 py-1 rounded-md text-xs font-bold transition-all flex items-center gap-1",k==="view"?"bg-[var(--bg-surface)] shadow-sm text-[var(--accent)]":"text-[var(--fg-muted)] hover:text-[var(--fg-secondary)]"),children:[e.jsx(Es,{size:K.sm})," ",c("common.preview")]}),e.jsxs("button",{onClick:()=>{E("edit")},className:ve("px-2.5 py-1 rounded-md text-xs font-bold transition-all flex items-center gap-1",k==="edit"?"bg-[var(--bg-surface)] shadow-sm text-[var(--accent)]":"text-[var(--fg-muted)] hover:text-[var(--fg-secondary)]"),children:[e.jsx($t,{size:K.sm})," ",c("common.edit")]})]}),e.jsx(Te.WidthToggle,{isWide:Z,onToggle:W}),e.jsx(We,{variant:"danger",size:"icon-sm",onClick:()=>{s(y.name||y.id),Q()},children:e.jsx(ot,{size:16})}),e.jsx(Te.CloseButton,{onClose:Q})]})]}),k==="edit"?e.jsxs(e.Fragment,{children:[e.jsxs(Te.Body,{padded:!0,children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-1.5 block",children:c("recipes.recipeDetail")}),e.jsx("input",{type:"text",value:B.title,onChange:X=>b(xe=>({...xe,title:X.target.value})),className:"w-full px-3 py-2 text-sm border border-[var(--border-default)] rounded-lg bg-[var(--bg-root)] text-[var(--fg-primary)] focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)] focus:border-[var(--accent-emphasis)]"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-1.5 block",children:c("recipes.description")}),e.jsx("textarea",{value:B.description,onChange:X=>b(xe=>({...xe,description:X.target.value})),rows:2,className:"w-full px-3 py-2 text-sm border border-[var(--border-default)] rounded-lg bg-[var(--bg-root)] text-[var(--fg-primary)] focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)] resize-none"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-1.5 block",children:c("recipes.tags")}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:B.tags.map((X,xe)=>e.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] px-2 py-0.5 rounded bg-[var(--accent-subtle)] text-[var(--accent)] border border-[var(--border-default)] font-medium",children:[X,e.jsx("button",{onClick:()=>b(he=>({...he,tags:he.tags.filter((Fe,Oe)=>Oe!==xe)})),className:"text-[var(--fg-muted)] hover:text-[var(--status-error)]",children:e.jsx(Xe,{size:10})})]},xe))}),e.jsx("div",{className:"flex gap-2",children:e.jsx("input",{type:"text",value:B.tagInput,onChange:X=>b(xe=>({...xe,tagInput:X.target.value})),onKeyDown:X=>{X.key==="Enter"&&B.tagInput.trim()&&(X.preventDefault(),b(xe=>({...xe,tags:[...xe.tags,xe.tagInput.trim()],tagInput:""})))},placeholder:c("recipes.tags"),className:"flex-1 px-3 py-1.5 text-xs border border-[var(--border-default)] rounded-lg bg-[var(--bg-root)] text-[var(--fg-primary)] focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)]"})})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-1.5 block flex items-center gap-1.5",children:[e.jsx(ft,{size:11,className:"text-[var(--accent)]"})," ",c("recipes.markdown")]}),e.jsx("textarea",{value:B.markdown,onChange:X=>b(xe=>({...xe,markdown:X.target.value})),rows:4,className:"w-full px-3 py-2 text-sm border border-[var(--border-default)] rounded-lg bg-[var(--bg-root)] text-[var(--fg-primary)] focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)] resize-y font-mono",placeholder:c("recipes.markdown")})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-1.5 block flex items-center gap-1.5",children:[e.jsx(Yt,{size:11,className:"text-[var(--status-success)]"})," ",c("recipes.code")]}),e.jsx("div",{className:"border border-[var(--border-default)] rounded-lg overflow-hidden",style:{minHeight:200},children:e.jsx(Ls,{value:B.codePattern,onChange:X=>b(xe=>({...xe,codePattern:X})),language:G,height:"200px",showLineNumbers:!0})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-1.5 block",children:c("recipes.designRationale")}),e.jsx("textarea",{value:B.rationale,onChange:X=>b(xe=>({...xe,rationale:X.target.value})),rows:3,className:"w-full px-3 py-2 text-sm border border-[var(--border-default)] rounded-lg bg-[var(--bg-root)] text-[var(--fg-primary)] focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)] resize-y",placeholder:c("recipes.designRationale")})]})]}),e.jsxs(Te.Footer,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-[var(--fg-muted)]",children:c("recipes.qualityAuthorityScore")}),e.jsx(lt,{value:String(((_=y.stats)==null?void 0:_.authority)??3),onChange:X=>ce(parseInt(X)),options:[1,2,3,4,5].map(X=>({value:String(X),label:`${"⭐".repeat(X)} ${X}`})),size:"xs",className:"font-bold text-amber-600 bg-amber-50 border-amber-100"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(We,{variant:"ghost",onClick:()=>E("view"),disabled:h,children:c("common.cancel")}),e.jsxs(We,{variant:"primary",onClick:ue,disabled:h,loading:h,children:[!h&&e.jsx(Ms,{size:K.sm}),c(h?"common.saving":"common.save")]})]})]})]}):e.jsxs(Te.Body,{children:[e.jsx(ma,{badges:(()=>{const X=y.kind?Os[y.kind]:null,xe=y.category||"Utility",he=gt[xe]||gt.All,Fe=[];return X&&Fe.push({label:X.label,className:`${X.bg} ${X.color} ${X.border}`,icon:X.icon}),Fe.push({label:xe,className:`font-bold uppercase ${(he==null?void 0:he.bg)||"bg-[var(--bg-subtle)]"} ${(he==null?void 0:he.color)||"text-[var(--fg-muted)]"} ${(he==null?void 0:he.border)||"border-[var(--border-default)]"}`}),y.knowledgeType&&Fe.push({label:fs[y.knowledgeType]?c(fs[y.knowledgeType]):y.knowledgeType,className:"bg-purple-50 text-purple-700 border-purple-200"}),y.language&&Fe.push({label:y.language,className:"uppercase font-bold text-[var(--fg-secondary)] bg-[var(--bg-subtle)] border-[var(--border-default)]"}),y.trigger&&Fe.push({label:y.trigger,className:"font-mono font-bold bg-amber-50 text-amber-700 border-amber-200"}),y.source&&y.source!=="unknown"&&Fe.push({label:y.source,className:"bg-[var(--bg-subtle)] text-[var(--fg-secondary)] border-[var(--border-default)]"}),Fe})(),metadata:(()=>{const X=[];return y.scope&&X.push({icon:qt,iconClass:"text-teal-400",label:c("candidates.path"),value:y.scope==="universal"?c("common.all"):y.scope==="project-specific"?c("candidates.category"):y.scope}),y.complexity&&X.push({icon:ht,iconClass:"text-orange-400",label:c("candidates.category"),value:y.complexity==="advanced"?c("candidates.confidenceHigh"):y.complexity==="intermediate"?c("candidates.confidenceMedium"):y.complexity==="basic"?c("candidates.confidenceLow"):y.complexity}),y.source&&y.source!=="unknown"&&X.push({icon:qt,iconClass:"text-violet-400",label:c("recipes.sourceLabel"),value:y.source==="bootstrap-scan"?c("recipes.sourceBootstrap"):y.source==="agent"?c("recipes.sourceAiScan"):y.source}),y.updatedAt&&Hr(y.updatedAt)&&X.push({icon:it,iconClass:"text-[var(--fg-muted)]",label:c("candidates.updatedAt"),value:Ia(y.updatedAt)}),X})(),tags:y.tags,id:y.id,sourceFile:y.sourceFile,sourceFileLabel:c("candidates.path")}),e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ra,{size:12,className:ve("text-purple-400",Ie&&"animate-spin")}),e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase",children:c("recipes.relations")}),(()=>{const X=y.relations?Object.values(y.relations).flat().length:0;return X>0?e.jsx(Xs,{variant:"blue",className:"text-[9px]",children:X}):null})()]}),e.jsx(We,{variant:Y?"secondary":"primary",size:"sm",onClick:()=>{ge(!Y),N("")},children:Y?e.jsxs(e.Fragment,{children:[e.jsx(Xe,{size:10})," ",c("common.cancel")]}):e.jsxs(e.Fragment,{children:[e.jsx(kt,{size:10})," ",c("recipes.editBtn")]})})]}),Y&&e.jsxs("div",{className:"mb-3 bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-lg p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lt,{value:Ne,onChange:X=>fe(X),options:P.map(X=>({value:X.key,label:`${X.icon} ${X.label}`})),size:"xs",className:"font-bold"}),e.jsxs("div",{className:"flex-1 relative",children:[e.jsx(Ct,{size:12,className:"absolute left-2 top-1/2 -translate-y-1/2 text-[var(--fg-muted)]"}),e.jsx("input",{type:"text",placeholder:c("recipes.searchPlaceholder"),value:w,onChange:X=>N(X.target.value),className:"w-full text-xs bg-[var(--bg-root)] border border-[var(--border-default)] rounded pl-7 pr-2 py-1 outline-none text-[var(--fg-primary)]",autoFocus:!0})]})]}),w.length>0&&e.jsx("div",{className:"max-h-36 overflow-y-auto rounded border border-[var(--border-default)] bg-[var(--bg-root)] divide-y divide-[var(--border-default)]",children:(()=>{const X=t.filter(xe=>at(xe)===p?!1:at(xe).toLowerCase().includes(w.toLowerCase())).slice(0,10);return X.length?X.map(xe=>{const he=at(xe),Fe=y.relations&&Object.values(y.relations).flat().some(Oe=>(typeof Oe=="string"?Oe:Oe.target||Oe.id||Oe.title||"").replace(/\.md$/i,"").toLowerCase()===he.toLowerCase());return e.jsxs("div",{className:ve("flex items-center justify-between px-3 py-1.5 text-xs",Fe||Ie?"bg-[var(--bg-subtle)] text-[var(--fg-muted)]":"hover:bg-[var(--bg-subtle)] cursor-pointer"),onClick:()=>!Fe&&!Ie&&H(Ne,he),children:[e.jsx("span",{className:"font-medium truncate mr-2",children:he}),Fe?e.jsx("span",{className:"text-[9px] text-[var(--fg-muted)] font-bold shrink-0",children:c("recipes.relations")}):e.jsxs("span",{className:"text-[9px] text-[var(--accent)] font-bold shrink-0",children:["+ ",c("recipes.editBtn")]})]},he)}):e.jsx("div",{className:"text-xs text-[var(--fg-muted)] py-3 text-center",children:c("recipes.noResults")})})()})]}),y.relations&&Object.entries(y.relations).some(([,X])=>Array.isArray(X)&&X.length>0)?e.jsx("div",{className:"space-y-1.5",children:P.map(({key:X,label:xe,icon:he})=>{var Oe;const Fe=(Oe=y.relations)==null?void 0:Oe[X];return!Fe||!Array.isArray(Fe)||Fe.length===0?null:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("span",{className:"text-[10px] font-mono text-[var(--fg-muted)] shrink-0 whitespace-nowrap pt-0.5",children:[he," ",xe]}),e.jsx("div",{className:"flex flex-wrap gap-1",children:Fe.map((qe,te)=>{const de=typeof qe=="string"?qe:qe.target||qe.id||qe.title||JSON.stringify(qe),Ke=ke(de)||(Le.has(de)?ke(Le.get(de)):void 0),He=Ke?at(Ke):Le.get(de)||de;return e.jsxs("span",{className:ve("group/rel inline-flex items-center gap-1 px-1.5 py-0.5 border rounded text-[10px] font-mono transition-colors",Ke?"bg-[var(--accent-subtle)] border-[var(--accent-emphasis)] text-[var(--accent)] cursor-pointer hover:brightness-95":"bg-[var(--bg-root)] border-[var(--border-default)] text-[var(--fg-secondary)]"),onClick:()=>Ke&&U(Ke),title:Ke?c("candidates.viewDetail"):He,children:[He.replace(/\.md$/i,""),e.jsx("button",{onClick:Ue=>{Ue.stopPropagation(),!Ie&&window.confirm(`${c("common.delete")}: ${He.replace(/\.md$/i,"")}?`)&&S(X,de)},disabled:Ie,className:"opacity-0 group-hover/rel:opacity-100 text-[var(--danger)] hover:text-[var(--danger)] transition-opacity ml-1 p-0.5 rounded hover:bg-[var(--danger-subtle)]",title:c("common.delete"),children:e.jsx(Xe,{size:10})})]},te)})})]},X)})}):!Y&&e.jsx("div",{className:"text-xs text-[var(--fg-muted)] py-2 text-center",children:c("recipes.noContent")})]}),e.jsxs("div",{className:"px-6 py-3 border-b border-[var(--border-default)]",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-xl p-3 text-center border border-[var(--border-default)]",children:[e.jsx("div",{className:"text-lg font-bold text-amber-600",children:((J=y.stats)==null?void 0:J.authority)??"—"}),e.jsx("div",{className:"text-[10px] text-[var(--fg-muted)] font-medium",children:c("recipes.qualityAuthorityScore")})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-xl p-3 text-center border border-[var(--border-default)]",children:[e.jsx("div",{className:"text-lg font-bold text-[var(--accent)]",children:((ae=y.stats)==null?void 0:ae.authorityScore)!=null?y.stats.authorityScore.toFixed(1):"—"}),e.jsx("div",{className:"text-[10px] text-[var(--fg-muted)] font-medium",children:c("recipes.qualityGreat")})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-xl p-3 text-center border border-[var(--border-default)]",children:[e.jsx("div",{className:"text-lg font-bold text-[var(--fg-primary)]",children:y.stats?y.stats.guardUsageCount+y.stats.humanUsageCount+y.stats.aiUsageCount:0}),e.jsx("div",{className:"text-[10px] text-[var(--fg-muted)] font-medium",children:c("recipes.qualitySolid")})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-xl p-3 text-center border border-[var(--border-default)]",children:[e.jsx("div",{className:"text-sm font-bold text-[var(--fg-secondary)]",children:Ia((be=y.stats)==null?void 0:be.lastUsedAt)||c("recipes.noContent")}),e.jsx("div",{className:"text-[10px] text-[var(--fg-muted)] font-medium",children:c("recipes.qualityGood")})]})]}),y.stats!=null&&(y.stats.guardUsageCount>0||y.stats.humanUsageCount>0||y.stats.aiUsageCount>0)&&e.jsxs("div",{className:"flex items-center gap-4 mt-2 text-[10px] text-[var(--fg-muted)]",children:[e.jsxs("span",{children:["Guard: ",y.stats.guardUsageCount]}),e.jsxs("span",{children:["Human: ",y.stats.humanUsageCount]}),e.jsxs("span",{children:["AI: ",y.stats.aiUsageCount]})]})]}),e.jsx($e.Reasoning,{reasoning:y.reasoning,labels:{section:c("recipes.reasoning"),source:c("recipes.sourceColon"),confidence:c("recipes.confidenceColon"),alternatives:c("recipes.alternativesLabel")}}),e.jsx($e.Quality,{quality:y.quality,labels:{section:c("recipes.qualityGrade"),completeness:c("recipes.qualityCompleteness"),adaptation:c("recipes.qualityAdaptation"),documentation:c("recipes.qualityDocumentation")}}),e.jsx($e.Description,{label:c("recipes.description"),text:y.description}),e.jsx($e.MarkdownSection,{label:c("recipes.markdown"),content:A==null?void 0:A.markdown}),e.jsx($e.Headers,{label:c("recipes.headers"),headers:y.headers}),e.jsx($e.CodePattern,{label:c("recipes.code"),code:z,language:G}),e.jsx($e.Rationale,{label:c("recipes.designRationale"),text:A==null?void 0:A.rationale}),e.jsx($e.Steps,{label:c("recipes.steps"),steps:A==null?void 0:A.steps}),(A==null?void 0:A.codeChanges)&&A.codeChanges.length>0&&e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:c("recipes.codeChanges")}),e.jsx("div",{className:"space-y-2",children:A.codeChanges.map((X,xe)=>e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-3 py-1.5 bg-[var(--bg-subtle)] border-b border-[var(--border-default)] flex items-center gap-2",children:[e.jsx(Tt,{size:11,className:"text-[var(--accent)]"}),e.jsx("code",{className:"text-[10px] font-mono text-[var(--fg-secondary)]",children:X.file})]}),X.explanation&&e.jsx("p",{className:"text-[11px] text-[var(--fg-muted)] px-3 py-1.5 border-b border-[var(--border-default)] bg-[var(--bg-subtle)]",children:X.explanation}),e.jsxs("div",{className:"p-2 bg-red-50/10 border-b border-[var(--border-default)]",children:[e.jsx("div",{className:"text-[9px] font-bold text-[var(--status-error)] mb-0.5 uppercase",children:"Before"}),e.jsx("pre",{className:"text-[11px] text-[var(--fg-secondary)] whitespace-pre-wrap break-words font-mono",children:X.before||c("recipes.emptyValue")})]}),e.jsxs("div",{className:"p-2 bg-emerald-50/10",children:[e.jsx("div",{className:"text-[9px] font-bold text-[var(--status-success)] mb-0.5 uppercase",children:"After"}),e.jsx("pre",{className:"text-[11px] text-[var(--fg-primary)] whitespace-pre-wrap break-words font-mono",children:X.after})]})]},xe))})]}),(A==null?void 0:A.verification)&&e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:c("recipes.validation")}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-xl p-4 space-y-1.5",children:[A.verification.method&&e.jsxs("p",{className:"text-xs text-[var(--fg-secondary)]",children:[e.jsx("span",{className:"font-bold text-[var(--status-success)]",children:c("recipes.verificationMethod")})," ",A.verification.method]}),A.verification.expectedResult&&e.jsxs("p",{className:"text-xs text-[var(--fg-secondary)]",children:[e.jsx("span",{className:"font-bold text-[var(--status-success)]",children:c("recipes.verificationExpected")})," ",A.verification.expectedResult]}),A.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:A.verification.testCode})]})]}),e.jsx($e.Constraints,{label:c("recipes.constraints"),constraints:y.constraints})]})]})})()]})};function Mt(t){return t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"k":String(t)}function qo(t){const s=new Map(t.map(r=>[r.date,r])),a=[];for(let r=6;r>=0;r--){const o=new Date;o.setDate(o.getDate()-r);const n=o.toISOString().slice(0,10);a.push(s.get(n)||{date:n,input_tokens:0,output_tokens:0,total_tokens:0,call_count:0})}return a}const Uo={user:"bg-blue-500",mcp:"bg-purple-500",bootstrap:"bg-amber-500",guard:"bg-rose-500",analyst:"bg-indigo-500",producer:"bg-green-500"},Wo=()=>{const{t}=Me(),[s,a]=l.useState([]),[r,o]=l.useState([]),[n,d]=l.useState({input_tokens:0,output_tokens:0,total_tokens:0,call_count:0,avg_per_call:0}),[u,c]=l.useState(!0),[x,v]=l.useState(null);l.useEffect(()=>{let f=!1;return(async()=>{try{const j=await ne.getTokenUsage7Days();if(f)return;a(j.daily||[]),o(j.bySource||[]),d(j.summary||{input_tokens:0,output_tokens:0,total_tokens:0,call_count:0,avg_per_call:0})}catch(j){f||v(j.message||t("tokenUsageChart.loadFailed"))}finally{f||c(!1)}})(),()=>{f=!0}},[]);const g=l.useMemo(()=>qo(s),[s]),m=l.useMemo(()=>Math.max(...g.map(f=>f.total_tokens),1),[g]);if(u)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(x)return e.jsx("p",{className:"text-red-500 text-sm py-4 text-center",children:x});const i=n.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(bs,{label:t("tokenUsageChart.totalToken"),value:Mt(n.total_tokens),sub:t("tokenUsageChart.totalSub"),color:"blue"}),e.jsx(bs,{label:t("tokenUsageChart.input"),value:Mt(n.input_tokens),sub:"Prompt",color:"green"}),e.jsx(bs,{label:t("tokenUsageChart.output"),value:Mt(n.output_tokens),sub:"Completion",color:"purple"}),e.jsx(bs,{label:t("tokenUsageChart.calls"),value:String(n.call_count),sub:t("tokenUsageChart.avgPerCall",{avg:Mt(n.avg_per_call)}),color:"amber"})]}),i?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:g.map(f=>{const j=f.input_tokens/m*100,C=f.output_tokens/m*100,I=t(`tokenUsageChart.weekday${new Date(f.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:f.date}),e.jsx("p",{children:t("tokenUsageChart.dailyDetail",{input:Mt(f.input_tokens),output:Mt(f.output_tokens)})}),e.jsx("p",{children:t("tokenUsageChart.dailyCalls",{count:String(f.call_count)})})]}),e.jsxs("div",{className:"w-full flex flex-col justify-end",style:{height:"120px"},children:[e.jsx("div",{className:"bg-green-400 rounded-t-sm w-full transition-all",style:{height:`${j}%`,minHeight:f.input_tokens>0?"2px":"0"}}),e.jsx("div",{className:"bg-purple-400 rounded-b-sm w-full transition-all",style:{height:`${C}%`,minHeight:f.output_tokens>0?"2px":"0"}})]}),e.jsx("span",{className:"text-[10px] text-slate-400",children:I})]},f.date)})}),e.jsxs("div",{className:"flex gap-4 mt-2 text-xs text-slate-500 justify-center",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-sm bg-green-400 inline-block"})," ",t("tokenUsageChart.legendInput")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-sm bg-purple-400 inline-block"})," ",t("tokenUsageChart.legendOutput")]})]})]}),r.length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold text-slate-700 mb-3",children:t("tokenUsageChart.sourceDistribution")}),e.jsx("div",{className:"space-y-2",children:r.map(f=>{const j=n.total_tokens>0?f.total_tokens/n.total_tokens*100:0,C=Uo[f.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:f.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:`${j}%`,minWidth:j>0?"4px":"0"}})}),e.jsx("span",{className:"w-16 text-xs text-slate-500 text-right",children:Mt(f.total_tokens)}),e.jsxs("span",{className:"w-12 text-xs text-slate-400 text-right",children:[j.toFixed(0),"%"]})]},f.source)})})]})]})]})};function bs({label:t,value:s,sub:a,color:r}){const o={blue:"bg-blue-50 border-blue-200 text-blue-700",green:"bg-green-50 border-green-200 text-green-700",purple:"bg-purple-50 border-purple-200 text-purple-700",amber:"bg-amber-50 border-amber-200 text-amber-700"},n=o[r]||o.blue;return e.jsxs("div",{className:`rounded-lg border p-3 ${n}`,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 Ft=({id:t,title:s,icon:a,isExpanded:r,onToggle:o,children:n})=>e.jsxs("section",{className:"border border-[var(--border-default)] rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>o(t),className:"w-full flex items-center justify-between p-4 bg-[var(--bg-subtle)] hover:bg-[var(--bg-muted)] active:bg-[var(--bg-muted)] outline-none focus:outline-none focus-visible:outline-none transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[a,e.jsx("h2",{className:"text-lg font-bold text-[var(--fg-primary)]",children:s})]}),r?e.jsx(Rt,{size:K.lg}):e.jsx(rt,{size:K.lg})]}),r&&e.jsx("div",{className:"p-4 bg-[var(--bg-surface)]",children:n})]}),Vo=()=>{const{t}=Me(),[s,a]=l.useState(new Set(["quick-start"])),r=o=>{const n=new Set(s);n.has(o)?n.delete(o):n.add(o),a(n)};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-[var(--fg-primary)] mb-4 flex items-center justify-center gap-3",children:[e.jsx(Qe,{size:K.xxl,className:"text-blue-600"}),t("help.pageTitle")]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-lg max-w-3xl mx-auto text-center",children:t("help.subtitle")}),e.jsx("p",{className:"text-[var(--fg-muted)] text-sm mt-2",children:t("help.techSpecs")}),e.jsxs("div",{className:"mt-6 flex gap-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-[var(--border-default)] text-[var(--fg-primary)] rounded-lg hover:bg-[var(--bg-subtle)] transition-colors",children:t("help.fullDocs")})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ft,{id:"token-usage",title:t("help.tokenUsageLast7Days"),icon:e.jsx(gr,{size:K.xl,className:"text-blue-600"}),isExpanded:s.has("token-usage"),onToggle:r,children:e.jsx(Wo,{})}),e.jsx(Ft,{id:"quick-start",title:t("help.quickStart"),icon:e.jsx(ls,{size:K.xl,className:"text-blue-600"}),isExpanded:s.has("quick-start"),onToggle:r,children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"bg-blue-50 rounded-lg p-4 border border-blue-200",children:[e.jsx("div",{className:"bg-blue-600 text-white rounded-full w-8 h-8 flex items-center justify-center mb-3 font-bold",children:"1"}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:t("help.step1Title")}),e.jsx("pre",{className:"bg-blue-100/70 text-blue-900 px-3 py-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-all",children:e.jsxs("code",{children:["npm install -g autosnippet",`
76
+ `,"cd your-project",`
77
+ `,"asd setup"]})})]}),e.jsxs("div",{className:"bg-green-50 rounded-lg p-4 border border-green-200",children:[e.jsx("div",{className:"bg-green-600 text-white rounded-full w-8 h-8 flex items-center justify-center mb-3 font-bold",children:"2"}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:t("help.step2Title")}),e.jsx("pre",{className:"bg-green-100/70 text-green-900 px-3 py-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-all",children:e.jsx("code",{children:"asd ui"})}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mt-2",children:t("help.step2Desc")})]}),e.jsxs("div",{className:"bg-purple-50 rounded-lg p-4 border border-purple-200",children:[e.jsx("div",{className:"bg-purple-600 text-white rounded-full w-8 h-8 flex items-center justify-center mb-3 font-bold",children:"3"}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:t("help.step3Title")}),e.jsx("pre",{className:"bg-purple-100/70 text-purple-900 px-3 py-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-all",children:e.jsx("code",{children:"asd upgrade"})}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mt-2",children:t("help.step3Desc")})]}),e.jsxs("div",{className:"bg-amber-50 rounded-lg p-4 border border-amber-200",children:[e.jsx("div",{className:"bg-amber-600 text-white rounded-full w-8 h-8 flex items-center justify-center mb-3 font-bold",children:"4"}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:t("help.step4Title")}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-sm mb-1",children:t("help.step4Desc1")}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-sm",children:t("help.step4Desc2")})]})]})}),e.jsxs(Ft,{id:"concepts",title:t("help.coreConcepts"),icon:e.jsx(or,{size:K.xl,className:"text-blue-600"}),isExpanded:s.has("concepts"),onToggle:r,children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-[var(--fg-primary)] mb-3",children:t("help.threeRoles")}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full border border-[var(--border-default)] rounded-lg text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-[var(--bg-subtle)]",children:[e.jsx("th",{className:"px-4 py-3 border-b text-left font-semibold",children:t("help.roleColumn")}),e.jsx("th",{className:"px-4 py-3 border-b text-left font-semibold",children:t("help.responsibilityColumn")}),e.jsx("th",{className:"px-4 py-3 border-b text-left font-semibold",children:t("help.capabilityColumn")})]})}),e.jsxs("tbody",{children:[e.jsxs("tr",{className:"hover:bg-[var(--bg-subtle)]",children:[e.jsx("td",{className:"px-4 py-3 border-b font-medium text-blue-700",children:t("help.roleDeveloper")}),e.jsx("td",{className:"px-4 py-3 border-b",children:t("help.developerResp")}),e.jsx("td",{className:"px-4 py-3 border-b text-xs",dangerouslySetInnerHTML:{__html:t("help.developerCap")}})]}),e.jsxs("tr",{className:"hover:bg-[var(--bg-subtle)]",children:[e.jsx("td",{className:"px-4 py-3 border-b font-medium text-green-700",children:t("help.roleCursorAgent")}),e.jsx("td",{className:"px-4 py-3 border-b",children:t("help.cursorAgentResp")}),e.jsx("td",{className:"px-4 py-3 border-b text-xs",dangerouslySetInnerHTML:{__html:t("help.cursorAgentCap")}})]}),e.jsxs("tr",{className:"hover:bg-[var(--bg-subtle)]",children:[e.jsx("td",{className:"px-4 py-3 font-medium text-purple-700",children:t("help.roleChatAgent")}),e.jsx("td",{className:"px-4 py-3",children:t("help.chatAgentResp")}),e.jsx("td",{className:"px-4 py-3 text-xs",dangerouslySetInnerHTML:{__html:t("help.chatAgentCap")}})]})]})]})})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-[var(--fg-primary)] mb-3",children:t("help.coreComponents")}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",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:K.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(En,{size:K.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(Tt,{size:K.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(Pn,{size:K.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(Ct,{size:K.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(mt,{size:K.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:"bg-cyan-50 rounded-lg p-4 border border-cyan-200",children:[e.jsxs("h4",{className:"font-semibold text-cyan-900 mb-2 flex items-center gap-2",children:[e.jsx(ga,{size:K.lg}),t("help.taskGraphLabel")]}),e.jsx("p",{className:"text-cyan-800 text-sm mb-3",children:t("help.taskGraphDesc")}),e.jsxs("ul",{className:"text-cyan-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.taskGraphBullet1")}),e.jsx("li",{children:t("help.taskGraphBullet2")}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.taskGraphBullet3")}})]})]}),e.jsxs("div",{className:"bg-teal-50 rounded-lg p-4 border border-teal-200",children:[e.jsxs("h4",{className:"font-semibold text-teal-900 mb-2 flex items-center gap-2",children:[e.jsx(ha,{size:K.lg}),t("help.ideIntegrationLabel")]}),e.jsx("p",{className:"text-teal-800 text-sm mb-3",children:t("help.ideIntegrationDesc")}),e.jsxs("ul",{className:"text-teal-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.ideIntegrationBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.ideIntegrationBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.ideIntegrationBullet3")}})]})]}),e.jsxs("div",{className:"bg-orange-50 rounded-lg p-4 border border-orange-200",children:[e.jsxs("h4",{className:"font-semibold text-orange-900 mb-2 flex items-center gap-2",children:[e.jsx(Ln,{size:K.lg}),t("help.securityLabel")]}),e.jsx("p",{className:"text-orange-800 text-sm mb-3",children:t("help.securityDesc")}),e.jsxs("ul",{className:"text-orange-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.securityBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.securityBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.securityBullet3")}})]})]})]})]}),e.jsxs("div",{className:"mt-6 mb-6 p-4 bg-[var(--bg-subtle)] rounded-lg border border-[var(--border-default)]",children:[e.jsx("h3",{className:"text-lg font-semibold text-[var(--fg-primary)] mb-3",children:t("help.archOverviewLabel")}),e.jsxs("div",{className:"flex items-center justify-between gap-1 text-xs overflow-x-auto pb-2",children:[e.jsx("div",{className:"bg-indigo-100 text-indigo-700 px-3 py-2 rounded-lg font-medium text-center shrink-0",children:t("help.archOverviewBootstrap")}),e.jsx("span",{className:"text-[var(--fg-muted)] shrink-0",children:"→"}),e.jsx("div",{className:"bg-blue-100 text-blue-700 px-3 py-2 rounded-lg font-medium text-center shrink-0",children:t("help.archOverviewKB")}),e.jsx("span",{className:"text-[var(--fg-muted)] shrink-0",children:"→"}),e.jsx("div",{className:"bg-blue-100 text-blue-700 px-3 py-2 rounded-lg font-medium text-center shrink-0",children:t("help.archOverviewPipeline")}),e.jsx("span",{className:"text-[var(--fg-muted)] shrink-0",children:"→"}),e.jsx("div",{className:"bg-emerald-100 text-emerald-700 px-3 py-2 rounded-lg font-medium text-center shrink-0",children:t("help.archOverviewAgent")}),e.jsx("span",{className:"text-[var(--fg-muted)] shrink-0",children:"→"}),e.jsx("div",{className:"bg-amber-100 text-amber-700 px-3 py-2 rounded-lg font-medium text-center shrink-0",children:t("help.archOverviewTask")}),e.jsx("span",{className:"text-[var(--fg-muted)] shrink-0",children:"→"}),e.jsx("div",{className:"bg-emerald-100 text-emerald-700 px-3 py-2 rounded-lg font-medium text-center shrink-0",children:t("help.archOverviewOutput")})]}),e.jsxs("div",{className:"mt-2 flex items-center justify-center gap-3 text-xs",children:[e.jsxs("span",{className:"bg-rose-100 text-rose-700 px-3 py-1.5 rounded-lg font-medium",children:["↕ ",t("help.archOverviewSecurity")," ↕"]}),e.jsxs("span",{className:"bg-teal-100 text-teal-700 px-3 py-1.5 rounded-lg font-medium",children:["↕ ",t("help.archOverviewIDE")," ↕"]})]})]}),e.jsxs("div",{className:"mt-6 rounded-lg p-5 border border-[var(--border-default)] bg-[var(--bg-subtle)]",children:[e.jsx("h3",{className:"text-lg font-semibold text-[var(--fg-primary)] mb-5",children:t("help.knowledgeLoop")}),e.jsx("div",{className:"flex items-start justify-between gap-0 overflow-x-auto pb-2",children:[{step:1,color:"blue",key:"loopStep1",subKey:"loopStep1Sub"},{step:2,color:"green",key:"loopStep2",subKey:"loopStep2Sub"},{step:3,color:"purple",key:"loopStep3",subKey:"loopStep3Sub"},{step:4,color:"amber",key:"loopStep4",subKey:"loopStep4Sub"},{step:5,color:"rose",key:"loopStep5",subKey:"loopStep5Sub"}].map((o,n)=>e.jsxs(Pt.Fragment,{children:[e.jsxs("div",{className:"flex-1 min-w-[90px] flex flex-col items-center text-center",children:[e.jsx("div",{className:`w-11 h-11 rounded-full flex items-center justify-center font-bold text-lg text-white shadow-md mb-2.5 bg-${o.color}-500`,children:o.step}),e.jsx("p",{className:"text-[var(--fg-primary)] font-semibold text-sm leading-tight",children:t(`help.${o.key}`)}),e.jsx("p",{className:"text-[var(--fg-muted)] text-xs mt-1 font-mono",children:t(`help.${o.subKey}`)})]}),n<4&&e.jsxs("div",{className:"flex items-center pt-3 px-1 shrink-0",children:[e.jsx("div",{className:"w-6 h-px bg-[var(--border-default)]"}),e.jsx("span",{className:"text-[var(--fg-muted)] text-xs mx-0.5",children:"›"}),e.jsx("div",{className:"w-6 h-px bg-[var(--border-default)]"})]})]},o.step))}),e.jsx("div",{className:"mt-4 flex items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-2 text-xs text-[var(--fg-muted)]",children:[e.jsx("span",{className:"inline-block w-8 h-px bg-rose-400/50"}),e.jsx("span",{className:"italic",children:t("help.loopStep5")}),e.jsx("span",{children:"→"}),e.jsx("span",{className:"italic",children:t("help.loopStep1")}),e.jsx("span",{className:"inline-block w-8 h-px bg-blue-400/50"})]})})]})]}),e.jsxs(Ft,{id:"features",title:t("help.coreFeatures"),icon:e.jsx(et,{size:K.xl,className:"text-blue-600"}),isExpanded:s.has("features"),onToggle:r,children:[e.jsx("p",{className:"text-[var(--fg-secondary)] text-sm mb-5",children:t("help.coreFeaturesDesc")}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5",children:[e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-blue-100 flex items-center justify-center shrink-0",children:e.jsx(hr,{size:K.lg,className:"text-blue-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.knowledgeBuild")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.kbBuildDesc")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.kbBuildBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.kbBuildBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.kbBuildBullet3")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.kbBuildBullet4")}})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-emerald-100 flex items-center justify-center shrink-0",children:e.jsx(Ct,{size:K.lg,className:"text-emerald-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.semanticSearchLabel")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.semSearchDescShort")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.semSearchBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.semSearchBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.semSearchBullet3")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.semSearchBullet4")}})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-purple-100 flex items-center justify-center shrink-0",children:e.jsx(mt,{size:K.lg,className:"text-purple-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.guardCompliance")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.guardComplianceDesc")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditFeatureBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditFeatureBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditFeatureBullet3")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditFeatureBullet4")}})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-amber-100 flex items-center justify-center shrink-0",children:e.jsx(ga,{size:K.lg,className:"text-amber-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.featureTaskGraphTitle")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.featureTaskGraphDesc")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.featureTaskGraphBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.featureTaskGraphBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.featureTaskGraphBullet3")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.featureTaskGraphBullet4")}})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-rose-100 flex items-center justify-center shrink-0",children:e.jsx(Tt,{size:K.lg,className:"text-rose-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.wikiDocGen")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.wikiDocGenDesc")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.wikiDocBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.wikiDocBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.wikiDocBullet3")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.wikiDocBullet4")}})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-teal-100 flex items-center justify-center shrink-0",children:e.jsx(jt,{size:K.lg,className:"text-teal-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.dataSync")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.syncDescShort")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.syncBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.syncBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.syncBullet3")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.syncBullet4")}})]})]})]})]}),e.jsxs(Ft,{id:"editor-directives",title:t("help.editorDirectives"),icon:e.jsx(fa,{size:K.xl,className:"text-blue-600"}),isExpanded:s.has("editor-directives"),onToggle:r,children:[e.jsx("p",{className:"text-[var(--fg-secondary)] text-sm mb-4",children:t("help.editorDirectivesNote")}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-lg p-4 border border-[var(--border-default)]",children:[e.jsxs("h4",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:[e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"// as:create"})," · ",e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"asc"})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-sm mb-2",children:t("help.createDirective")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.createDirBullet1")}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.createDirBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.createDirBullet3")}})]})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-lg p-4 border border-[var(--border-default)]",children:[e.jsxs("h4",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:[e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"// as:search"})," · ",e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"ass"})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-sm mb-2",children:t("help.searchDirective")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.searchDirBullet1")}),e.jsx("li",{children:t("help.searchDirBullet2")}),e.jsx("li",{children:t("help.searchDirBullet3")})]})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-lg p-4 border border-[var(--border-default)]",children:[e.jsxs("h4",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:[e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"// as:audit"})," · ",e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"asa"})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-sm mb-2",children:t("help.auditDirective")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.auditDirBullet1")}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditDirBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditDirBullet3")}})]})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-lg p-4 border border-[var(--border-default)]",children:[e.jsxs("h4",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:[e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"// as:include"})," · ",e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"// as:import"})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-sm mb-2",children:t("help.includeDirective")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.includeDirBullet1")}),e.jsx("li",{children:t("help.includeDirBullet2")})]})]})]})]}),e.jsxs(Ft,{id:"cursor-integration",title:t("help.cursorIntegration"),icon:e.jsx(It,{size:K.xl,className:"text-blue-600"}),isExpanded:s.has("cursor-integration"),onToggle:r,children:[e.jsxs("div",{className:"mb-5",children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-3",children:t("help.skills10")}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-2",children:[{name:"intent",descKey:"help.skillIntent"},{name:"concepts",descKey:"help.skillConcepts"},{name:"candidates",descKey:"help.skillCandidates"},{name:"recipes",descKey:"help.skillRecipes"},{name:"guard",descKey:"help.skillGuard"},{name:"structure",descKey:"help.skillStructure"},{name:"analysis",descKey:"help.skillAnalysis"},{name:"coldstart",descKey:"help.skillColdstart"},{name:"create",descKey:"help.skillCreate"},{name:"lifecycle",descKey:"help.skillLifecycle"},{name:"devdocs",descKey:"help.skillDevdocs"}].map(o=>e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-lg px-3 py-2 text-center",children:[e.jsx("p",{className:"text-xs font-mono text-blue-600",children:o.name}),e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] mt-0.5",children:t(o.descKey)})]},o.name))})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-3",children:t("help.mcp16")}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full border border-[var(--border-default)] rounded-lg text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-[var(--bg-subtle)]",children:[e.jsx("th",{className:"px-3 py-2 border-b text-left",children:t("help.mcpLayerHeader")}),e.jsx("th",{className:"px-3 py-2 border-b text-left",children:t("help.mcpToolHeader")}),e.jsx("th",{className:"px-3 py-2 border-b text-left",children:t("help.mcpDescHeader")})]})}),e.jsxs("tbody",{children:[e.jsx("tr",{className:"bg-blue-50/30",children:e.jsx("td",{colSpan:3,className:"px-3 py-1.5 border-b font-semibold text-blue-700 text-xs",children:t("help.mcpAgentLayerHeader")})}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"health"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpHealthDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"capabilities"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpCapabilitiesDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"search"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpSearchDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"knowledge"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpKnowledgeDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"structure"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpStructureDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"graph"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpGraphDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"guard"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpGuardDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsxs("td",{className:"px-3 py-2 border-b",children:[e.jsx("code",{children:"submit_knowledge"})," / ",e.jsx("code",{children:"submit_knowledge_batch"})," / ",e.jsx("code",{children:"save_document"})]}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpSubmitDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"skill"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpSkillDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"bootstrap"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpBootstrapDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"dimension_complete"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpDimensionCompleteDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsxs("td",{className:"px-3 py-2 border-b",children:[e.jsx("code",{children:"wiki_plan"})," / ",e.jsx("code",{children:"wiki_finalize"})]}),e.jsxs("td",{className:"px-3 py-2 border-b",children:[t("help.mcpWikiPlanDesc")," · ",t("help.mcpWikiFinalizeDesc")]})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"task"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpTaskDesc")})]}),e.jsx("tr",{className:"bg-amber-50/30",children:e.jsx("td",{colSpan:3,className:"px-3 py-1.5 border-b font-semibold text-amber-700 text-xs",children:t("help.mcpAdminLayerHeader")})}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"admin"}),e.jsxs("td",{className:"px-3 py-2 border-b",children:[e.jsx("code",{children:"enrich_candidates"})," / ",e.jsx("code",{children:"validate_candidate"})," / ",e.jsx("code",{children:"check_duplicate"})]}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpEnrichDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-medium",children:"admin"}),e.jsx("td",{className:"px-3 py-2",children:e.jsx("code",{children:"knowledge_lifecycle"})}),e.jsx("td",{className:"px-3 py-2",children:t("help.mcpLifecycleDesc")})]})]})]})}),e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] mt-2",children:t("help.mcpWriteNote")})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-3",children:t("help.usageExamples")}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"bg-blue-50 rounded p-3 border border-blue-200",children:[e.jsx("p",{className:"font-medium text-blue-900 text-sm mb-1",children:t("help.exampleSearchKB")}),e.jsx("p",{className:"text-blue-800 text-xs",children:t("help.exampleSearchKBDesc")})]}),e.jsxs("div",{className:"bg-green-50 rounded p-3 border border-green-200",children:[e.jsx("p",{className:"font-medium text-green-900 text-sm mb-1",children:t("help.exampleBatchScan")}),e.jsx("p",{className:"text-green-800 text-xs",children:t("help.exampleBatchScanDesc")})]}),e.jsxs("div",{className:"bg-purple-50 rounded p-3 border border-purple-200",children:[e.jsx("p",{className:"font-medium text-purple-900 text-sm mb-1",children:t("help.exampleSubmitCode")}),e.jsx("p",{className:"text-purple-800 text-xs",children:t("help.exampleSubmitCodeDesc")})]})]})]}),e.jsxs("div",{className:"mt-5",children:[e.jsxs("h3",{className:"font-semibold text-[var(--fg-primary)] mb-3 flex items-center gap-2",children:[e.jsx(ha,{size:K.lg,className:"text-blue-600"}),t("help.vscodeExtension")]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-sm mb-3",children:t("help.vscodeExtDesc")}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3 mb-3",children:[e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-lg p-3",children:[e.jsx("h4",{className:"font-semibold text-[var(--fg-primary)] text-sm mb-1",children:t("help.vscodeExtTaskTool")}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.vscodeExtTaskToolDesc")})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-lg p-3",children:[e.jsx("h4",{className:"font-semibold text-[var(--fg-primary)] text-sm mb-1",children:t("help.vscodeExtGuardDiag")}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.vscodeExtGuardDiagDesc")})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-lg p-3",children:[e.jsx("h4",{className:"font-semibold text-[var(--fg-primary)] text-sm mb-1",children:t("help.vscodeExtCodeLens")}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.vscodeExtCodeLensDesc")})]})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-lg p-3",children:[e.jsx("h4",{className:"font-semibold text-[var(--fg-primary)] text-sm mb-2",children:"Commands"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-1 text-xs text-[var(--fg-secondary)]",children:[e.jsx("p",{children:t("help.vscodeExtCmd1")}),e.jsx("p",{children:t("help.vscodeExtCmd2")}),e.jsx("p",{children:t("help.vscodeExtCmd3")}),e.jsx("p",{children:t("help.vscodeExtCmd4")}),e.jsx("p",{children:t("help.vscodeExtCmd5")})]})]})]})]}),e.jsx(Ft,{id:"cli-reference",title:t("help.cliReference"),icon:e.jsx(fa,{size:K.xl,className:"text-blue-600"}),isExpanded:s.has("cli-reference"),onToggle:r,children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:t("help.initAndEnv")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd setup"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliSetupDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd status"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliStatusDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd ui"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliUiDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd upgrade"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliUpgradeDesc")})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:t("help.kbManagement")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd sync"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliSyncDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd ais [Target]"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliAisDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd watch"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliWatchDesc")})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:t("help.cliColdstartAndScan")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd coldstart"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliColdstartDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd cursor-rules"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliCursorRulesDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd mirror"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliMirrorDesc")})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:t("help.searchAndAudit")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd search <query>"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliSearchDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd guard <file>"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliGuardDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd guard:ci"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliGuardCiDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd guard:staged"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliGuardStagedDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd server"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliServerDesc")})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:t("help.cliTaskManagement")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd task list"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliTaskListDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd task ready"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliTaskReadyDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd task prime"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliTaskPrimeDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd task stats"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliTaskStatsDesc")})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:t("help.maintenanceUpgrade")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd upgrade"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliUpgradeMcpDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd sync --force"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliSyncForceDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd sync --dry-run"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliSyncDryDesc")})]})]})]})]})})]}),e.jsx("div",{className:"mt-8 p-4 bg-blue-50 border border-blue-200 rounded-lg text-center",children:e.jsx("p",{className:"text-[var(--fg-primary)] text-sm",dangerouslySetInnerHTML:{__html:t("help.footerHint",{link:`<a href="https://github.com/GxFn/AutoSnippet" target="_blank" rel="noopener noreferrer" class="text-blue-600 hover:underline font-medium">${t("help.footerGithubReadme")}</a>`,cmd:'<code class="bg-blue-100 px-1.5 py-0.5 rounded text-xs">asd status</code>'})}})})]})};function Jo(){const[t,s]=l.useState(null);l.useEffect(()=>{const n=oa(),d=g=>{s({status:"running",total:g.total,current:0,progress:0,refined:0,failed:0,items:g.candidateIds.map(m=>({candidateId:m,title:"",status:"pending"}))})},u=g=>{s(m=>m&&{...m,current:g.current,progress:g.progress,items:m.items.map(i=>i.candidateId===g.candidateId?{...i,title:g.title,status:"refining"}:i)})},c=g=>{s(m=>m&&{...m,current:g.current,progress:g.progress,refined:g.refinedSoFar,items:m.items.map(i=>i.candidateId===g.candidateId?{...i,title:g.title,status:"done",refined:g.refined}:i)})},x=g=>{s(m=>m&&{...m,current:g.current,progress:g.progress,failed:m.failed+1,items:m.items.map(i=>i.candidateId===g.candidateId?{...i,title:g.title,status:"failed",error:g.error}:i)})},v=g=>{s(m=>m&&{...m,status:"completed",progress:100,refined:g.refined,failed:g.failed})};return n.on("refine:started",d),n.on("refine:item-started",u),n.on("refine:item-completed",c),n.on("refine:item-failed",x),n.on("refine:completed",v),()=>{n.off("refine:started",d),n.off("refine:item-started",u),n.off("refine:item-completed",c),n.off("refine:item-failed",x),n.off("refine:completed",v)}},[]);const a=l.useCallback(()=>s(null),[]),r=(t==null?void 0:t.status)==="running",o=(t==null?void 0:t.status)==="completed";return{refine:t,isRefining:r,isRefineDone:o,resetRefine:a}}const Yo=({refine:t,isRefineDone:s,onDismiss:a})=>{const{t:r}=Me(),o=l.useRef(!1);if(l.useEffect(()=>{if(s&&t&&!o.current){o.current=!0;const u=t.failed>0?r("refineProgress.doneMsgWithFail",{refined:String(t.refined),failed:String(t.failed)}):r("refineProgress.doneMsg",{refined:String(t.refined)});re(u,{title:r("refineProgress.doneTitle"),type:t.failed>0?"error":"success"})}},[s,t]),l.useEffect(()=>{t||(o.current=!1)},[t]),!t)return null;const n=t.items.find(u=>u.status==="refining"),d=t.items.filter(u=>u.status==="done"||u.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(yt,{className:"w-4 h-4 text-emerald-600"}):e.jsx(Je,{className:"w-4 h-4 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-slate-800",children:r(s?"refineProgress.doneTitle":"refineProgress.runningTitle")}),e.jsxs("p",{className:"text-xs text-slate-500",children:[s?t.failed>0?r("refineProgress.doneMsgWithFail",{refined:String(t.refined),failed:String(t.failed)}):r("refineProgress.doneMsg",{refined:String(t.refined)}):r("refineProgress.progressMsg",{done:String(d),total:String(t.total)}),n&&!s&&e.jsxs("span",{className:"ml-2 text-blue-600",children:[e.jsx(Pe,{className:"w-3 h-3 inline animate-spin mr-1"}),n.title||n.candidateId.slice(0,8)]})]})]})]}),s&&a&&e.jsx("button",{onClick:a,className:"text-xs px-2.5 py-1 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-600 transition-colors",children:r("refineProgress.closeBtn")})]}),e.jsx("div",{className:"w-full h-1.5 bg-slate-100 rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full transition-all duration-500 ease-out ${s?t.failed>0?"bg-amber-400":"bg-emerald-500":"bg-blue-500"}`,style:{width:`${t.progress}%`}})}),s&&t.failed>0&&e.jsxs("div",{className:"mt-2 text-xs text-red-500 flex items-center gap-1",children:[e.jsx(Xe,{className:"w-3 h-3"}),t.items.filter(u=>u.status==="failed").map(u=>u.title||u.candidateId.slice(0,8)).join("、")]})]})},vs={_watch:"silentLabels.watch",_draft:"silentLabels.draft",_cli:"silentLabels.cli",_pending:"silentLabels.pending",_recipe:"silentLabels.recipe"},ys={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 Qo(t,s,a,r){return[...t].sort(([o],[n])=>{const d=r(o),u=r(n);if(d&&!u)return 1;if(!d&&u)return-1;const c=a(o),x=a(n);if(c&&!x)return-1;if(!c&&x)return 1;const v=s(o),g=s(n);return v&&!g?1:!v&&g?-1:o.localeCompare(n)})}function ts(t,s){if(!t)return"";const a=typeof t=="number"?t:Number(t),r=a<1e12?a*1e3:a,o=new Date(r);if(isNaN(o.getTime())||o.getFullYear()<2e3)return"";const d=new Date().getTime()-o.getTime();if(d<0)return o.toLocaleDateString();const u=Math.floor(d/6e4);if(u<1)return s("candidates.timeJustNow");if(u<60)return s("candidates.timeMinutesAgo",{n:u});const c=Math.floor(u/60);if(c<24)return s("candidates.timeHoursAgo",{n:c});const x=Math.floor(c/24);return x<7?s("candidates.timeDaysAgo",{n:x}):o.toLocaleDateString()}function Xo(t,s=4){return t?ia(t).split(`
78
+ `).slice(0,s).join(`
79
+ `):""}function Zo(t){return t==null?{ring:"stroke-slate-200",text:"text-[var(--fg-muted)]",bg:"bg-[var(--bg-subtle)]",labelKey:""}:t>=.8?{ring:"stroke-emerald-500",text:"text-emerald-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 Ra={"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-[var(--fg-secondary)] bg-[var(--bg-subtle)] border-[var(--border-default)]"},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"},"bootstrap-fallback":{labelKey:"candidates.sourceFallbackLabel",color:"text-amber-600 bg-amber-50 border-amber-200"}},ei=({value:t,size:s=36})=>{const a=(s-6)/2,r=2*Math.PI*a,o=t!=null?Math.max(0,Math.min(1,t)):0,n=r*(1-o),{ring:d,text:u}=Zo(t);return e.jsxs("div",{className:"relative flex items-center justify-center",style:{width:s,height:s},children:[e.jsxs("svg",{width:s,height:s,className:"-rotate-90",children:[e.jsx("circle",{cx:s/2,cy:s/2,r:a,fill:"none",stroke:"currentColor",strokeWidth:3,className:"text-[var(--border-default)]"}),e.jsx("circle",{cx:s/2,cy:s/2,r:a,fill:"none",strokeWidth:3,strokeLinecap:"round",className:d,strokeDasharray:r,strokeDashoffset:n,style:{transition:"stroke-dashoffset 0.5s ease"}})]}),e.jsx("span",{className:`absolute text-[9px] font-bold ${u}`,children:t!=null?`${Math.round(t*100)}`:"—"})]})},ti=({data:t,isShellTarget:s,isSilentTarget:a=()=>!1,isPendingTarget:r=()=>!1,handleDeleteCandidate:o,handleDeleteAllInTarget:n,onAuditCandidate:d,onAuditAllInTarget:u,onEditRecipe:c,onColdStart:x,isScanning:v,isBootstrapping:g,onRefresh:m})=>{var _e;const{t:i}=Me(),[f,j]=l.useState(null),{isWide:C,toggle:I}=ua(),[D,$]=l.useState(new Set),[O]=l.useState(new Set),[T,Z]=l.useState(!1),[W]=l.useState(!1),M=xs(),{refine:F,isRefining:k,isRefineDone:E,resetRefine:B}=Jo(),[b,h]=l.useState({}),[L,ie]=l.useState(null),[Y,ge]=l.useState({}),[Ne,fe]=l.useState(null),[w,N]=l.useState({}),[P,U]=l.useState({sort:"default",onlySimilar:!1}),[Q,ue]=l.useState(null),ce=l.useRef(new Set),ke=l.useCallback(async(q,y)=>{if(!ce.current.has(y)){ce.current.add(y),fe(y);try{const p=await ne.getCandidateSimilarityEx({targetName:q,candidateId:y});ge(z=>({...z,[y]:p.similar||[]}))}catch{ge(z=>({...z,[y]:[]}))}finally{fe(null)}}},[]),Le=l.useCallback(async(q,y,p,z=[])=>{var ae,be,X,xe;const G=p.replace(/\.md$/i,"");let A="";const _=(ae=t==null?void 0:t.recipes)==null?void 0:ae.find(he=>he.name===G||he.name.endsWith("/"+G));if(_!=null&&_.content)A=[_.content.pattern,_.content.markdown].filter(Boolean).join(`
80
+
81
+ `)||"";else try{A=(await ne.getRecipeContentByName(G)).content}catch(he){const Fe=(be=he.response)==null?void 0:be.status,Oe=((xe=(X=he.response)==null?void 0:X.data)==null?void 0:xe.message)||he.message;Fe===404?re(`"${G}" ${i("common.operationFailed")}`,{title:i("common.operationFailed"),type:"error"}):re(Oe,{title:i("common.loadFailed"),type:"error"});return}const J={[G]:A};j(q.id),ue({candidate:q,targetName:y,recipeName:G,recipeContent:A,similarList:z.slice(0,3),recipeContents:J})},[t==null?void 0:t.recipes]),Ie=t!=null&&t.candidates?Object.entries(t.candidates):[],Be=Qo(Ie,s,a,r),H=Be.map(([q])=>q),S=L&&H.includes(L)?L:H[0]??null;l.useEffect(()=>{H.length>0&&(!L||!H.includes(L))&&ie(H[0])},[H.join(","),L]),l.useEffect(()=>{f&&S&&ke(S,f)},[f,S,ke]);const se=l.useMemo(()=>{var A;if(!S||!((A=t==null?void 0:t.candidates)!=null&&A[S]))return null;const q=t.candidates[S].items,y=q.length,p=q.reduce((_,J)=>{var ae;return _+(((ae=J.reasoning)==null?void 0:ae.confidence)??0)},0)/(y||1),z=q.filter(_=>{var J;return((J=_.content)==null?void 0:J.pattern)&&_.content.pattern.trim().length>0||_.coreCode&&_.coreCode.trim().length>0}).length,G=new Map;return q.forEach(_=>{const J=_.source||"unknown";G.set(J,(G.get(J)||0)+1)}),{total:y,avgConfidence:p,withCode:z,sources:G}},[S,t==null?void 0:t.candidates]),we=l.useMemo(()=>{const q=new Map;if(t!=null&&t.idTitleMap)for(const[y,p]of Object.entries(t.idTitleMap))q.set(y,p);if(t!=null&&t.candidates)for(const y of Object.values(t.candidates))for(const p of y.items)p.id&&p.title&&q.set(p.id,p.title);if(t!=null&&t.recipes)for(const y of t.recipes)y.id&&y.name&&q.set(y.id,y.name.replace(/\.md$/i,""));return q},[t==null?void 0:t.idTitleMap,t==null?void 0:t.candidates,t==null?void 0:t.recipes]),V=l.useCallback(async q=>{var y,p,z,G,A;if(!D.has(q)){$(_=>new Set(_).add(q));try{const _=await ne.enrichCandidates([q]);_.enriched>0?re(`${((z=(p=(y=_.results)==null?void 0:y[0])==null?void 0:p.filledFields)==null?void 0:z.length)||0} ${i("candidates.approveSuccess")}`,{title:i("candidates.aiRefine")}):re(i("recipes.noContent"),{title:i("candidates.aiRefine"),type:"info"});try{const J=await ne.getCandidate(q);N(ae=>({...ae,[q]:J}))}catch{}}catch(_){const J=(A=(G=_.response)==null?void 0:G.data)==null?void 0:A.error;re(typeof J=="string"?J:(J==null?void 0:J.message)||_.message,{title:i("common.operationFailed"),type:"error"})}finally{$(_=>{const J=new Set(_);return J.delete(q),J})}}},[D,m]),ye=l.useCallback(async()=>{var y,p,z;if(T||!S||!((y=t==null?void 0:t.candidates)!=null&&y[S]))return;const q=t.candidates[S].items;if(q.length!==0){Z(!0);try{let G=0;for(let A=0;A<q.length;A+=20){const _=q.slice(A,A+20).map(ae=>ae.id),J=await ne.enrichCandidates(_);G+=J.enriched}re(`${G}/${q.length} ${i("candidates.batchDeleteDone",{count:G})}`,{title:i("candidates.aiRefine")}),m==null||m()}catch(G){const A=(z=(p=G.response)==null?void 0:p.data)==null?void 0:z.error;re(typeof A=="string"?A:(A==null?void 0:A.message)||G.message,{title:i("common.operationFailed"),type:"error"})}finally{Z(!1)}}},[T,S,t==null?void 0:t.candidates,m]),Re=l.useCallback(async q=>{try{const y=await ne.getCandidate(q);N(p=>({...p,[q]:y}))}catch{}},[]),je=l.useCallback(()=>{var p;if(!S||!((p=t==null?void 0:t.candidates)!=null&&p[S]))return;const q=t.candidates[S].items,y=q.map(z=>z.id);M.openRefine({candidateIds:y,candidates:q,onCandidateUpdated:Re})},[S,t==null?void 0:t.candidates,M,Re]),pe=l.useCallback(q=>{var p;if(!S||!((p=t==null?void 0:t.candidates)!=null&&p[S]))return;ue(null),j(q);const y=t.candidates[S].items;M.openRefine({candidateIds:[q],candidates:y,onCandidateUpdated:Re})},[S,t==null?void 0:t.candidates,M,Re]);return e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"mb-4 flex flex-wrap justify-between items-center gap-3 shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-50 border border-blue-100 flex items-center justify-center shrink-0",children:e.jsx(Je,{className:"text-blue-600",size:20})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-lg xl:text-xl font-bold text-[var(--fg-primary)]",children:"AI Scan Candidates"}),e.jsx("p",{className:"text-xs text-[var(--fg-muted)] mt-0.5 truncate",children:i("candidates.title")})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[x&&!g&&e.jsxs("button",{onClick:x,disabled:v,className:`flex items-center gap-1.5 px-3.5 py-2 rounded-lg text-xs font-bold transition-all ${v?"text-[var(--fg-muted)] bg-[var(--bg-subtle)] 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:i("candidates.coldStartTitle"),children:[v?e.jsx(Pe,{size:14,className:"animate-spin"}):e.jsx(ls,{size:14}),i(v?"common.loading":"candidates.sourceBootstrap")]}),se&&se.total>0&&e.jsxs("button",{onClick:ye,disabled:T||W,className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-all ${T||W?"text-[var(--fg-muted)] bg-[var(--bg-subtle)] cursor-not-allowed":"text-amber-700 bg-amber-50 border border-amber-200 hover:bg-amber-100"}`,title:i("candidates.enrichTitle"),children:[T?e.jsx(Pe,{size:14,className:"animate-spin"}):e.jsx(Ns,{size:14}),i(T?"common.loading":"candidates.aiEnrich")]}),se&&se.total>0&&e.jsxs("button",{onClick:je,disabled:W||T||k,className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-all ${W||T||k?"text-[var(--fg-muted)] bg-[var(--bg-subtle)] cursor-not-allowed":"text-emerald-700 bg-emerald-50 border border-emerald-200 hover:bg-emerald-100"}`,title:i("candidates.refineTitle"),children:[W||k?e.jsx(Pe,{size:14,className:"animate-spin"}):e.jsx(Je,{size:14}),i(W||k?"common.loading":"candidates.aiRefine")]}),se&&e.jsxs("div",{className:"flex items-center gap-3 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-[var(--bg-subtle)] border border-[var(--border-default)]",children:[e.jsx(gr,{size:14,className:"text-[var(--fg-muted)]"}),e.jsx("span",{className:"text-[var(--fg-secondary)]",children:i("candidates.totalCount",{count:se.total})}),se.withCode<se.total&&e.jsx("span",{className:"text-[var(--fg-muted)] ml-1",children:i("candidates.withCode",{count:se.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:i("candidates.confidence")}),e.jsxs("strong",{className:"text-emerald-700",children:[Math.round(se.avgConfidence*100),"%"]})]})]})]})]}),F&&e.jsx(Yo,{refine:F,isRefineDone:E,onDismiss:()=>{B(),m==null||m()}}),Ie.length>0&&e.jsx("div",{className:"shrink-0 bg-[var(--bg-surface)] border border-[var(--border-default)] 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:H.map(q=>{var J;const y=a(q),p=vs[q]?i(vs[q]):void 0,z=t==null?void 0:t.candidates[q],G=((J=z==null?void 0:z.items)==null?void 0:J.length)??0,A=S===q,_=gt[q]||gt.All;return e.jsxs("button",{onClick:()=>ie(q),className:`flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-bold whitespace-nowrap transition-all border
82
+ ${A?`${(_==null?void 0:_.bg)||"bg-blue-50"} ${(_==null?void 0:_.color)||"text-blue-700"} ${(_==null?void 0:_.border)||"border-blue-200"} shadow-sm ring-1 ring-inset ${(_==null?void 0:_.border)||"ring-blue-200"}`:"bg-[var(--bg-subtle)] text-[var(--fg-secondary)] border-[var(--border-default)] hover:border-[var(--border-emphasis)] hover:bg-[var(--bg-subtle)]"}`,children:[(()=>{const ae=(_==null?void 0:_.icon)||Is;return e.jsx(ae,{size:K.sm,className:A?"":"text-[var(--fg-muted)]"})})(),e.jsx("span",{children:ys[q]?i(ys[q]):q}),y&&p&&e.jsx("span",{className:"text-[9px] text-amber-600 border border-amber-200 px-1 rounded",children:p}),e.jsx("span",{className:`text-[10px] font-normal rounded-full px-1.5 ${A?"bg-white/60":"bg-[var(--bg-subtle)] text-[var(--fg-muted)]"}`,children:G})]},q)})})}),e.jsxs("div",{className:"flex-1 overflow-y-auto pr-1 pb-6",children:[(!(t!=null&&t.candidates)||Object.keys(t.candidates).length===0)&&!g&&e.jsxs("div",{className:"h-72 flex flex-col items-center justify-center bg-[var(--bg-surface)] rounded-2xl border border-dashed border-[var(--border-default)] text-[var(--fg-muted)]",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-[var(--bg-subtle)] flex items-center justify-center mb-4",children:e.jsx(Us,{size:32,className:"text-[var(--fg-muted)]"})}),e.jsx("p",{className:"text-sm font-medium text-[var(--fg-secondary)]",children:i("candidates.noResults")}),e.jsx("p",{className:"mt-2 text-xs max-w-sm text-center leading-relaxed text-[var(--fg-muted)]",children:i("candidates.emptyHint")}),x&&e.jsxs("button",{onClick:x,disabled:v,className:`mt-4 flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${v?"text-[var(--fg-muted)] bg-[var(--bg-subtle)] 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:[v?e.jsx(Pe,{size:16,className:"animate-spin"}):e.jsx(ls,{size:16}),i(v?"common.loading":"candidates.sourceBootstrap")]}),e.jsxs("p",{className:"mt-3 text-[11px] text-[var(--fg-muted)]",children:["或 ",e.jsx("code",{className:"text-blue-600 bg-blue-50 px-1 rounded",children:"asd ais --all"})," ",i("candidates.fullScanBtn"),e.jsx("code",{className:"text-blue-600 bg-blue-50 px-1 rounded ml-1",children:"asd candidate"})," ",i("candidates.clipboardCreate")]})]}),(!(t!=null&&t.candidates)||Object.keys(t.candidates).length===0)&&g&&e.jsxs("div",{className:"h-72 flex flex-col items-center justify-center bg-[var(--bg-surface)] rounded-2xl border border-dashed border-violet-500/30 text-[var(--fg-muted)]",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-violet-500/10 flex items-center justify-center mb-4",children:e.jsx(Pe,{size:32,className:"text-violet-400 animate-spin"})}),e.jsx("p",{className:"text-sm font-medium text-violet-400",children:i("common.loading")}),e.jsx("p",{className:"mt-2 text-xs max-w-sm text-center leading-relaxed text-[var(--fg-muted)]",children:i("candidates.scanningHint")})]}),t&&S&&Be.filter(([q])=>q===S).map(([q,y])=>{const p=s(q),z=a(q),G=vs[q]?i(vs[q]):i("candidates.silent"),A=b[q]||{page:1,pageSize:12},_=A.page,J=A.pageSize,ae=y.items.filter(te=>{if(P.onlySimilar){const de=Y[te.id];if(!Array.isArray(de)||de.length===0)return!1}return!0}).sort((te,de)=>{var Ke,He,Ue,tt,bt,Ye;if(P.sort==="default")return 0;if(P.sort==="score-desc")return(((Ke=de.quality)==null?void 0:Ke.overall)??0)-(((He=te.quality)==null?void 0:He.overall)??0);if(P.sort==="score-asc")return(((Ue=te.quality)==null?void 0:Ue.overall)??0)-(((tt=de.quality)==null?void 0:tt.overall)??0);if(P.sort==="confidence-desc")return(((bt=de.reasoning)==null?void 0:bt.confidence)??0)-(((Ye=te.reasoning)==null?void 0:Ye.confidence)??0);if(P.sort==="date-desc"){const wt=typeof te.createdAt=="number"?te.createdAt:0;return(typeof de.createdAt=="number"?de.createdAt:0)-wt}return 0}),be=ae.length,X=Math.ceil(be/J),xe=(_-1)*J,he=ae.slice(xe,xe+J),Fe=te=>{h(de=>({...de,[q]:{...A,page:te}}))},Oe=te=>{h(de=>({...de,[q]:{page:1,pageSize:te}}))},qe=gt[q]||gt.All;return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 rounded-xl bg-[var(--bg-surface)] border border-[var(--border-default)] shadow-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[(()=>{const te=(qe==null?void 0:qe.icon)||Is;return e.jsx(te,{size:18,className:(qe==null?void 0:qe.color)||"text-blue-600"})})(),e.jsx("span",{className:"text-base font-bold text-[var(--fg-primary)] truncate",children:ys[q]?i(ys[q]):q}),z&&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:G}),p&&!z&&e.jsx("span",{className:"text-[10px] font-bold text-[var(--fg-muted)] border border-[var(--border-default)] bg-[var(--bg-subtle)] px-1.5 py-0.5 rounded",children:"SHELL"}),e.jsxs("span",{className:"text-[11px] text-[var(--fg-muted)] flex items-center gap-1",children:[e.jsx(it,{size:11}),i("candidates.scannedAt",{time:ts(y.scanTime,i)||new Date(y.scanTime).toLocaleString()})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 rounded-lg bg-[var(--bg-subtle)] border border-[var(--border-default)]",children:[e.jsx(Mn,{size:12,className:"text-[var(--fg-muted)]"}),e.jsx(lt,{value:P.sort,onChange:te=>U(de=>({...de,sort:te})),options:[{value:"default",label:i("candidates.sortNewest")},{value:"score-desc",label:`${i("candidates.sortConfidence")} ↓`},{value:"score-asc",label:`${i("candidates.sortConfidence")} ↑`},{value:"confidence-desc",label:`${i("candidates.confidence")} ↓`},{value:"date-desc",label:i("candidates.sortOldest")}],size:"xs",className:"border-none bg-transparent"})]}),e.jsxs("label",{className:"text-[11px] font-medium text-[var(--fg-secondary)] flex items-center gap-1.5 px-2 py-1 rounded-lg bg-[var(--bg-subtle)] border border-[var(--border-default)] cursor-pointer hover:bg-[var(--bg-subtle)] transition-colors select-none",children:[e.jsx("input",{type:"checkbox",checked:P.onlySimilar,onChange:te=>U(de=>({...de,onlySimilar:te.target.checked})),className:"rounded text-blue-600 w-3 h-3"}),i("candidates.similarOnly")]}),(P.sort!=="default"||P.onlySimilar)&&e.jsx("button",{onClick:()=>U({sort:"default",onlySimilar:!1}),className:"text-[11px] font-medium text-[var(--fg-secondary)] hover:text-[var(--fg-primary)] px-2 py-1 rounded-lg border border-[var(--border-default)] bg-[var(--bg-surface)] hover:bg-[var(--bg-subtle)] transition-colors",children:i("candidates.resetFilters")})]}),e.jsx("div",{className:"h-5 w-px bg-[var(--border-default)]"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[11px] text-[var(--fg-muted)] font-medium",children:i("candidates.totalCount",{count:be})}),e.jsx("button",{onClick:()=>u(he,q),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:i("candidates.approveCurrentPage")}),e.jsx("button",{onClick:async()=>{if(!window.confirm(i("candidates.batchDeleteConfirm",{count:he.length})))return;const de=(await Promise.allSettled(he.map(Ke=>o(q,Ke.id)))).filter(Ke=>Ke.status==="rejected").length;de>0&&re(`${de} ${i("common.deleteFailed")}`,{title:i("common.operationFailed"),type:"error"}),m==null||m()},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:i("candidates.removeCurrentPage")}),e.jsx("button",{onClick:()=>n(q),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:i("candidates.deleteAll")})]})]}),e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3",children:he.map(te=>{var wt,ze,dt,ut,nt;const de=f===te.id,Ke=((wt=te.reasoning)==null?void 0:wt.confidence)??null,He=(((ze=te.quality)==null?void 0:ze.overall)??0)>0?((dt=te.quality)==null?void 0:dt.overall)??null:null,Ue=Y[te.id]||[],tt=Ue[0]||null,bt=Ra[te.source||""]||{labelKey:te.source||"",color:"text-[var(--fg-secondary)] bg-[var(--bg-subtle)] border-[var(--border-default)]"},Ye=gt[te.category||""]||gt.All||{};return e.jsxs("div",{onClick:()=>j(de?null:te.id),className:`bg-[var(--bg-surface)] rounded-xl border overflow-hidden hover:shadow-lg transition-all duration-200 flex flex-col group cursor-pointer
83
+ ${p?"opacity-75":""}
84
+ ${de?"ring-2 ring-blue-300 border-blue-300 shadow-md":"border-[var(--border-default)] hover:border-[var(--border-emphasis)]"}`,children:[e.jsx("div",{className:"px-4 pt-3.5 pb-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mb-1.5",children:[e.jsxs("span",{className:`text-[10px] font-bold px-1.5 py-0.5 rounded uppercase flex items-center gap-1 border ${(Ye==null?void 0:Ye.bg)||"bg-[var(--bg-subtle)]"} ${(Ye==null?void 0:Ye.color)||"text-[var(--fg-muted)]"} ${(Ye==null?void 0:Ye.border)||"border-[var(--border-default)]"}`,children:[(()=>{const Ve=(Ye==null?void 0:Ye.icon)||ht;return e.jsx(Ve,{size:10})})(),te.category||"general"]}),te.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:te.knowledgeType}),te.source&&te.source!=="unknown"&&e.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border ${bt.color}`,children:bt.labelKey.startsWith("candidates.")?i(bt.labelKey):bt.labelKey}),te.complexity&&e.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border
85
+ ${te.complexity==="advanced"?"bg-red-50 text-red-600 border-red-100":te.complexity==="intermediate"?"bg-amber-50 text-amber-600 border-amber-100":"bg-emerald-50 text-emerald-600 border-emerald-100"}`,children:te.complexity==="advanced"?i("candidates.confidenceHigh"):te.complexity==="intermediate"?i("candidates.confidenceMedium"):i("candidates.confidenceLow")})]}),e.jsx("h3",{className:"font-bold text-sm text-[var(--fg-primary)] leading-snug mb-1 line-clamp-1",children:te.title}),e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] line-clamp-2 leading-relaxed",children:te.description||""})]}),e.jsxs("div",{className:"flex flex-col items-center gap-1 shrink-0",children:[e.jsx(ei,{value:Ke}),e.jsx("span",{className:"text-[9px] text-[var(--fg-muted)] font-medium",children:i("candidates.confidence")})]})]})}),((ut=te.reasoning)==null?void 0:ut.whyStandard)&&!/^Submitted via /i.test(te.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(us,{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:te.reasoning.whyStandard})]})}),(He!=null||tt)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 px-4 py-2 border-t border-[var(--border-default)]",children:[He!=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(ms,{size:10}),i("candidates.overallScore",{score:(He*100).toFixed(0)+"%"})]}),tt&&e.jsxs("button",{onClick:Ve=>{Ve.stopPropagation();const st=String(tt.recipeName||"").trim();st&&Le(te,q,st,Ue)},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:i("candidates.similarWith",{name:tt.recipeName,score:(tt.similarity*100).toFixed(0)}),children:[e.jsx(ks,{size:10}),i("candidates.similarPrefix")," ",tt.recipeName.replace(/\.md$/i,"")," ",(tt.similarity*100).toFixed(0),"%"]})]}),((nt=te.content)==null?void 0:nt.pattern)&&e.jsxs("div",{className:"overflow-hidden border-t border-[var(--border-default)]/60",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5",style:{background:"#282c34"},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yt,{size:11,className:"text-[var(--fg-secondary)]"}),e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] font-mono uppercase tracking-wide",children:te.language||"code"})]}),e.jsx("span",{className:"text-[10px] text-[var(--fg-secondary)] font-mono tabular-nums",children:i("candidates.linesCount",{count:te.content.pattern.split(`
86
+ `).length})})]}),e.jsxs("div",{className:"relative max-h-[80px] overflow-hidden",children:[e.jsx(St,{code:Xo(te.content.pattern,3),language:te.language==="objc"?"objectivec":te.language,className:"!rounded-none"}),te.content.pattern.split(`
87
+ `).length>3&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-6 bg-gradient-to-t from-[#282c34] to-transparent pointer-events-none"})]})]}),e.jsxs("div",{className:"flex justify-between items-center px-4 py-2.5 border-t border-[var(--border-default)] bg-[var(--bg-subtle)] mt-auto",onClick:Ve=>Ve.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap min-w-0",children:[te.trigger&&e.jsx("span",{className:"text-[10px] font-mono px-2 py-0.5 rounded-md bg-[var(--bg-surface)] border border-[var(--border-default)] text-[var(--fg-secondary)] font-bold",children:te.trigger}),e.jsx("span",{className:"text-[10px] uppercase font-bold text-[var(--fg-muted)] bg-[var(--bg-surface)] border border-[var(--border-default)] px-1.5 py-0.5 rounded-md",children:te.language}),te.tags&&te.tags.length>0&&te.tags.slice(0,3).map((Ve,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 Ve=="string"?Ve:String(Ve)},st)),te.tags&&te.tags.length>3&&e.jsxs("span",{className:"text-[9px] text-[var(--fg-muted)]",children:["+",te.tags.length-3]}),te.createdAt&&ts(te.createdAt,i)&&e.jsxs("span",{className:"text-[9px] text-[var(--fg-muted)] flex items-center gap-0.5",children:[e.jsx(it,{size:9}),ts(te.createdAt,i)]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[e.jsx("button",{onClick:()=>V(te.id),disabled:D.has(te.id),title:i("candidates.enrichTitleSingle"),className:`p-1.5 rounded-lg transition-colors flex items-center gap-1 text-[11px] font-medium ${D.has(te.id)?"text-[var(--fg-muted)] cursor-not-allowed":"text-amber-500 hover:text-amber-600 hover:bg-amber-50"}`,children:D.has(te.id)?e.jsx(Pe,{size:14,className:"animate-spin"}):e.jsx(Ns,{size:14})}),e.jsx("button",{onClick:()=>pe(te.id),disabled:O.has(te.id),title:i("candidates.refineTitleSingle"),className:`p-1.5 rounded-lg transition-colors flex items-center gap-1 text-[11px] font-medium ${O.has(te.id)?"text-[var(--fg-muted)] cursor-not-allowed":"text-emerald-500 hover:text-emerald-600 hover:bg-emerald-50"}`,children:O.has(te.id)?e.jsx(Pe,{size:14,className:"animate-spin"}):e.jsx(Je,{size:14})}),e.jsx("button",{onClick:()=>{o(q,te.id),f===te.id&&(j(null),ue(null))},title:i("common.delete"),className:"p-1.5 hover:bg-red-50 text-[var(--fg-muted)] hover:text-red-500 rounded-lg transition-colors",children:e.jsx(ot,{size:14})}),e.jsxs("button",{onClick:()=>d(te,q),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($t,{size:12})," ",i("candidates.approveAndSave")]}),te.lifecycle==="pending"&&e.jsxs("button",{onClick:async()=>{try{await ne.promoteCandidateToRecipe(te.id),re(i("candidates.approveSuccess"),{title:i("candidates.approveSuccess")}),m==null||m()}catch(Ve){re(Ve.message,{title:i("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:i("candidates.approve"),children:[e.jsx(ls,{size:12})," ",i("candidates.approve")]})]})]})]},te.id)})}),be>12&&e.jsx(pa,{currentPage:_,totalPages:X,totalItems:be,pageSize:J,onPageChange:Fe,onPageSizeChange:Oe})]},q)})]}),f&&S&&((_e=t==null?void 0:t.candidates)==null?void 0:_e[S])&&(()=>{var Fe,Oe,qe,te;const q=t.candidates[S].items,y=q.find(de=>de.id===f);if(!y)return null;const p=w[f]||y,z=q.findIndex(de=>de.id===f),G=z>0,A=z<q.length-1,_=()=>{G&&(j(q[z-1].id),ue(null))},J=()=>{A&&(j(q[z+1].id),ue(null))},ae=p.reasoning,be=Y[p.id]||[],X=Ne===p.id,xe=gt[p.category||""]||gt.All||{},he=Ra[p.source||""]||{labelKey:p.source||"",color:"text-[var(--fg-secondary)] bg-[var(--bg-subtle)] border-[var(--border-default)]"};return e.jsxs(Ze,{className:"z-30 flex justify-end",onClick:()=>{j(null),ue(null)},children:[e.jsx(Ze.Backdrop,{className:"bg-black/20 dark:bg-black/40 backdrop-blur-sm"}),Q&&(()=>{const de=Q.candidate,Ke=de.language==="objc"||de.language==="objective-c"?"objectivec":de.language||"text",He=()=>{var dt,ut;const ze=[];(dt=de.content)!=null&&dt.pattern&&ze.push("## Snippet / Code Reference\n\n```"+Ke+`
88
+ `+de.content.pattern+"\n```"),(ut=de.content)!=null&&ut.markdown?ze.push(`
89
+ ## `+i("candidates.projectProfile")+`
90
+
91
+ `+de.content.markdown):de.doClause&&ze.push(`
92
+ ## AI Context / Usage Guide
93
+
94
+ `+de.doClause),navigator.clipboard.writeText(ze.join(`
95
+ `)||"").then(()=>re(i("common.copied"),{title:i("common.copied")}))},Ue=()=>{const ze=ca(Q.recipeContent);navigator.clipboard.writeText(ze).then(()=>re(i("common.copied"),{title:i("common.copied")}))},tt=async ze=>{var ut;if(ze===Q.recipeName)return;const dt=Q.recipeContents[ze];if(dt)ue(nt=>nt?{...nt,recipeName:ze,recipeContent:dt}:null);else{let nt="";const Ve=(ut=t==null?void 0:t.recipes)==null?void 0:ut.find(st=>st.name===ze||st.name.endsWith("/"+ze));if(Ve!=null&&Ve.content)nt=[Ve.content.pattern,Ve.content.markdown].filter(Boolean).join(`
96
+
97
+ `)||"";else try{nt=(await ne.getRecipeContentByName(ze)).content}catch{return}ue(st=>st?{...st,recipeName:ze,recipeContent:nt,recipeContents:{...st.recipeContents,[ze]:nt}}:null)}},bt=async()=>{if(window.confirm(i("common.areYouSure")))try{await o(Q.targetName,de.id),ue(null)}catch(ze){re((ze==null?void 0:ze.message)||i("common.deleteFailed"),{title:i("common.deleteFailed"),type:"error"})}},Ye=()=>{d(de,Q.targetName),ue(null)},wt=()=>{var dt;const ze=(dt=t==null?void 0:t.recipes)==null?void 0:dt.find(ut=>ut.name===Q.recipeName||ut.name.endsWith("/"+Q.recipeName));ze?c==null||c(ze):c==null||c({name:Q.recipeName,content:{markdown:Q.recipeContent}}),ue(null)};return e.jsxs(Te.Panel,{width:C?"w-[800px] max-w-[55vw]":"w-[600px] max-w-[45vw]",animationDuration:"0.2s",children:[e.jsxs(Te.Header,{className:"bg-emerald-50/60 py-3.5",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(ks,{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:i("candidates.recipeCompare")}),e.jsx("span",{className:"text-[11px] text-emerald-600 truncate block",children:Q.recipeName.replace(/\.md$/i,"")})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 ml-2",children:[e.jsx(We,{variant:"ghost",size:"icon-sm",onClick:()=>Ue(),title:i("common.copy"),className:"text-emerald-600 hover:bg-emerald-100",children:e.jsx(Qt,{size:14})}),e.jsx("button",{onClick:wt,className:"text-[11px] font-medium text-emerald-600 hover:bg-emerald-100 px-2 py-1.5 rounded-lg transition-colors",children:i("candidates.approveAndSave")}),e.jsx(Te.CloseButton,{onClose:()=>ue(null)})]})]}),Q.similarList.length>1&&e.jsx("div",{className:"flex flex-wrap gap-1 px-5 py-2 border-b border-[var(--border-default)] bg-[var(--bg-surface)] shrink-0",children:Q.similarList.map(ze=>e.jsxs("button",{onClick:()=>tt(ze.recipeName),className:`text-[10px] font-bold px-2 py-1 rounded transition-colors ${Q.recipeName===ze.recipeName?"bg-emerald-200 text-emerald-800":"bg-[var(--bg-surface)] text-emerald-600 hover:bg-emerald-50 border border-emerald-100"}`,children:[ze.recipeName.replace(/\.md$/i,"")," ",(ze.similarity*100).toFixed(0),"%"]},ze.recipeName))}),e.jsxs("div",{className:"flex items-center gap-1.5 px-5 py-2 border-b border-[var(--border-default)] bg-[var(--bg-surface)] shrink-0",children:[e.jsxs("button",{onClick:bt,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})," ",i("common.delete")]}),e.jsxs("button",{onClick:Ye,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($t,{size:12})," ",i("candidates.approveAndSave")]}),e.jsxs("button",{onClick:()=>He(),className:"text-xs font-medium text-[var(--fg-secondary)] hover:bg-[var(--bg-subtle)] px-2.5 py-1.5 rounded-lg transition-colors flex items-center gap-1",children:[e.jsx(Qt,{size:12})," ",i("common.copy")]})]}),e.jsx(Te.Body,{padded:!0,children:e.jsx(Et,{content:Q.recipeContent,stripFrontmatter:!0})})]})})(),e.jsxs(Te.Panel,{size:C?"lg":"md",children:[e.jsxs(Te.Header,{title:p.title,children:[e.jsx(Te.Nav,{currentIndex:z,total:q.length,onPrev:_,onNext:J,hasPrev:G,hasNext:A}),e.jsxs(Te.HeaderActions,{children:[e.jsx(Te.WidthToggle,{isWide:C,onToggle:I,title:i(C?"common.collapse":"common.expand")}),e.jsx(We,{variant:"danger",size:"icon-sm",onClick:()=>{o(S,p.id),j(null),ue(null)},children:e.jsx(ot,{size:16})}),e.jsx(Te.CloseButton,{onClose:()=>{j(null),ue(null)}})]})]}),e.jsxs(Te.Body,{children:[e.jsx(ma,{badges:(()=>{const de=[];return de.push({label:p.category||"general",className:`font-bold uppercase ${(xe==null?void 0:xe.bg)||"bg-[var(--bg-subtle)]"} ${(xe==null?void 0:xe.color)||"text-[var(--fg-muted)]"} ${(xe==null?void 0:xe.border)||"border-[var(--border-default)]"}`}),p.knowledgeType&&de.push({label:p.knowledgeType,className:"bg-purple-50 text-purple-700 border-purple-200"}),p.language&&de.push({label:p.language,className:"uppercase font-bold text-[var(--fg-secondary)] bg-[var(--bg-subtle)] border-[var(--border-default)]"}),p.complexity&&de.push({label:p.complexity==="advanced"?i("candidates.confidenceHigh"):p.complexity==="intermediate"?i("candidates.confidenceMedium"):i("candidates.confidenceLow"),className:p.complexity==="advanced"?"bg-red-50 text-red-600 border-red-100":p.complexity==="intermediate"?"bg-amber-50 text-amber-600 border-amber-100":"bg-emerald-50 text-emerald-600 border-emerald-100"}),p.trigger&&de.push({label:p.trigger,className:"font-mono font-bold bg-amber-50 text-amber-700 border-amber-200"}),p.source&&p.source!=="unknown"&&de.push({label:he.labelKey.startsWith("candidates.")?i(he.labelKey):he.labelKey,className:he.color}),p.lifecycle&&p.lifecycle!=="pending"&&de.push({label:p.lifecycle,className:"bg-blue-50 text-blue-600 border-blue-200"}),de})(),metadata:(()=>{const de=[];return p.scope&&de.push({icon:qt,iconClass:"text-teal-400",label:i("candidates.path"),value:p.scope==="universal"?i("common.all"):p.scope==="project-specific"||p.scope==="module-level"?i("candidates.category"):p.scope}),p.source&&p.source!=="unknown"&&de.push({icon:qt,iconClass:"text-violet-400",label:i("candidates.source"),value:he.labelKey.startsWith("candidates.")?i(he.labelKey):he.labelKey}),p.createdAt&&ts(p.createdAt,i)&&de.push({icon:it,iconClass:"text-[var(--fg-muted)]",label:i("candidates.createdAt"),value:ts(p.createdAt,i)}),de})(),tags:p.tags,maxTags:10}),e.jsx($e.Description,{label:i("candidates.description"),text:p.description}),e.jsx($e.Reasoning,{reasoning:ae,labels:{section:i("knowledge.reasoning"),source:`${i("candidates.source")}:`,confidence:`${i("candidates.confidence")}:`,alternatives:`${i("candidates.viewDetail")}:`},filterSubmitted:!0}),e.jsx($e.Quality,{quality:p.quality,labels:{section:i("candidates.qualityDimensions"),completeness:i("recipes.qualityCompleteness"),adaptation:i("recipes.qualityAdaptation"),documentation:i("recipes.qualityDocumentation")}}),(()=>{const de=p.relations?Object.entries(p.relations).flatMap(([He,Ue])=>Array.isArray(Ue)?Ue.map(tt=>({...tt,type:He})):[]):[];return p.agentNotes||p.aiInsight||de.length>0?e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(Je,{size:11,className:"text-emerald-400"})," ",i("candidates.refineEnhanced")]}),e.jsxs("div",{className:"bg-emerald-50/30 border border-emerald-100 rounded-xl p-4 space-y-2.5 text-xs",children:[p.aiInsight&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)] font-bold",children:[i("candidates.viewDetail"),":"]}),e.jsx("p",{className:"text-sm text-[var(--fg-primary)] leading-relaxed mt-0.5",children:p.aiInsight})]}),p.agentNotes&&p.agentNotes.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] font-bold",children:i("candidates.agentNotes")}),e.jsx("ul",{className:"mt-1 space-y-0.5",children:p.agentNotes.map((He,Ue)=>e.jsxs("li",{className:"flex items-start gap-1.5 text-[var(--fg-secondary)]",children:[e.jsx("span",{className:"text-emerald-400 mt-0.5",children:"•"}),He]},Ue))})]}),de.length>0&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)] font-bold",children:[i("recipes.relations"),":"]}),e.jsx("div",{className:"mt-1 space-y-1",children:de.map((He,Ue)=>e.jsxs("div",{className:"flex items-start gap-1.5 text-[var(--fg-secondary)]",children:[e.jsx("span",{className:"text-[9px] font-bold px-1 py-0.5 rounded bg-emerald-100 text-emerald-700 shrink-0 uppercase",children:He.type}),e.jsx("span",{className:"font-medium text-[var(--fg-primary)]",children:we.get(He.target)||He.target}),He.description&&e.jsxs("span",{className:"text-[var(--fg-muted)]",children:["— ",He.description]})]},Ue))})]})]})]}):null})(),be.length>0&&e.jsxs("div",{className:"px-6 py-3 border-b border-[var(--border-default)]",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block flex items-center gap-1.5",children:[i("candidates.similarRecipe"),X&&e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] animate-pulse",children:i("common.loading")})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:be.slice(0,5).map(de=>e.jsxs("button",{onClick:()=>Le(p,S,de.recipeName,be),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:i("candidates.similarWith",{name:de.recipeName,score:(de.similarity*100).toFixed(0)}),children:[e.jsx(ks,{size:10}),de.recipeName.replace(/\.md$/i,"")," ",(de.similarity*100).toFixed(0),"%"]},de.recipeName))})]}),e.jsx($e.CodePattern,{label:i("knowledge.codePattern"),code:(Fe=p.content)==null?void 0:Fe.pattern,language:p.language}),e.jsx($e.MarkdownSection,{label:i("knowledge.markdownDoc"),content:(Oe=p.content)==null?void 0:Oe.markdown}),e.jsx($e.Delivery,{delivery:{topicHint:p.topicHint,whenClause:p.whenClause,doClause:p.doClause,dontClause:p.dontClause,coreCode:p.coreCode},language:p.language}),e.jsx($e.Rationale,{label:i("candidates.rationale"),text:(qe=p.content)==null?void 0:qe.rationale}),e.jsx($e.Headers,{label:i("candidates.headers"),headers:p.headers}),e.jsx($e.Steps,{label:i("recipes.steps"),steps:(te=p.content)==null?void 0:te.steps})]}),e.jsxs(Te.Footer,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:()=>V(p.id),disabled:D.has(p.id),title:i("candidates.enrichTitleBottom"),className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium transition-colors ${D.has(p.id)?"text-[var(--fg-muted)] cursor-not-allowed":"text-amber-600 hover:bg-amber-50 border border-amber-200"}`,children:[D.has(p.id)?e.jsx(Pe,{size:14,className:"animate-spin"}):e.jsx(Ns,{size:14}),i("candidates.enrichShort")]}),e.jsxs("button",{onClick:()=>pe(p.id),disabled:O.has(p.id),title:i("candidates.refineTitleBottom"),className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium transition-colors ${O.has(p.id)?"text-[var(--fg-muted)] cursor-not-allowed":"text-emerald-600 hover:bg-emerald-50 border border-emerald-200"}`,children:[O.has(p.id)?e.jsx(Pe,{size:14,className:"animate-spin"}):e.jsx(Je,{size:14}),i("candidates.refineShort")]}),e.jsxs("button",{onClick:()=>{o(S,p.id),j(null),ue(null)},title:i("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})," ",i("common.delete")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[p.lifecycle==="pending"&&e.jsxs("button",{onClick:async()=>{try{await ne.promoteCandidateToRecipe(p.id),re(i("candidates.approveSuccess"),{title:i("candidates.approveSuccess")}),m==null||m()}catch(de){re(de.message,{title:i("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(ls,{size:14})," ",i("candidates.approve")]}),e.jsxs("button",{onClick:()=>{d(p,S),j(null),ue(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($t,{size:14})," ",i("candidates.approveAndSave")]})]})]})]})]})})()]})},si=({isOpen:t,onClose:s,currentFile:a,targetName:r,language:o="",onSelectRecipe:n})=>{var W,M,F,k;const{t:d}=Me(),[u,c]=l.useState(""),[x,v]=l.useState([]),[g,m]=l.useState(null),[i,f]=l.useState(!1),[j,C]=l.useState(null),[I,D]=l.useState(!1),[$,O]=l.useState(null),T=async()=>{if(u.trim()){f(!0);try{const E=await ne.search(u,{context:{language:o},limit:10});v((E.items||[]).map(B=>{var b,h,L;return{name:(B.title||B.name||"")+".md",content:((b=B.content)==null?void 0:b.pattern)||((h=B.content)==null?void 0:h.markdown)||((L=B.content)==null?void 0:L.code)||"",similarity:B.score||0,authority:B.authorityScore||0,matchType:B.matchType||"ranked",qualityScore:B.qualityScore||0,usageCount:B.usageCount||0}})),m(null)}catch(E){console.error("Context-aware search failed:",E),alert(d("search.searchFailed"))}finally{f(!1)}}},Z=E=>{E.key==="Enter"&&T()};return t?e.jsxs(Ze,{className:"z-30 flex",children:[e.jsx(Ze.Backdrop,{className:"bg-black/20 dark:bg-black/40 backdrop-blur-sm"}),e.jsxs("div",{className:"relative w-full max-w-2xl ml-auto bg-white shadow-xl flex flex-col max-h-screen",children:[e.jsxs("div",{className:"border-b border-slate-200 p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{className:"text-xl font-bold text-slate-900",children:d("search.title")}),e.jsx("button",{onClick:s,className:"p-1 hover:bg-slate-100 rounded-lg transition-colors",children:e.jsx(Xe,{size:K.lg,className:"text-slate-500"})})]}),g&&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:K.md,className:"text-blue-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1",children:[((W=g.targetInfo)==null?void 0:W.targetName)&&e.jsxs("div",{className:"text-blue-900 font-medium flex items-center gap-2 mb-1",children:[e.jsx(ba,{size:K.sm}),"Target: ",g.targetInfo.targetName]}),((M=g.fileInfo)==null?void 0:M.imports)&&g.fileInfo.imports.length>0&&e.jsxs("div",{className:"text-blue-800 text-xs mt-2",children:[e.jsx("strong",{children:d("search.importedFrameworks")})," ",g.fileInfo.imports.slice(0,3).join(", "),g.fileInfo.imports.length>3&&` +${g.fileInfo.imports.length-3}`]}),((F=g.targetInfo)==null?void 0:F.suggestedApis)&&g.targetInfo.suggestedApis.length>0&&e.jsxs("div",{className:"text-blue-800 text-xs mt-1",children:[e.jsx("strong",{children:d("search.relatedApis")})," ",g.targetInfo.suggestedApis.slice(0,3).join(", ")]})]})]})}),e.jsxs("div",{className:"relative",children:[e.jsx(Ct,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-400",size:K.md}),e.jsx("input",{type:"text",placeholder:d("search.searchPlaceholder"),value:u,onChange:E=>c(E.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:T,disabled:!u.trim()||i,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:[i&&e.jsx(Pe,{size:K.sm,className:"animate-spin"}),d(i?"search.searching":"search.searchBtn")]})]}),e.jsxs("div",{className:"flex-1 overflow-auto",children:[x.length===0&&!i&&e.jsx("div",{className:"flex items-center justify-center h-full text-slate-500",children:e.jsxs("div",{className:"text-center",children:[e.jsx(hr,{size:K.xxl,className:"mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:d("search.emptyHint")})]})}),x.map((E,B)=>e.jsxs("div",{className:"border-b border-slate-200 p-4 hover:bg-slate-50 transition-colors cursor-pointer",onClick:()=>{C(j===B?null:B),E.name&&(n==null||n(E.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:E.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:K.xs}),Math.round(E.similarity*100),"%"]}),E.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(ba,{size:K.xs}),d("search.contextRelevant")]}),E.matchType&&e.jsx("span",{className:"text-xs text-slate-500",children:E.matchType==="semantic"?d("search.matchSemantic"):d("search.matchKeyword")})]})]}),e.jsx("button",{onClick:b=>{b.stopPropagation(),C(j===B?null:B)},className:"p-1 hover:bg-slate-200 rounded transition-colors",children:j===B?"▼":"▶"})]}),E.stats&&e.jsxs("div",{className:"text-xs text-slate-500 mb-2 flex gap-3",children:[E.stats.authorityScore!==void 0&&e.jsxs("span",{children:[d("search.authorityScore"),": ",E.stats.authorityScore]}),E.usageCount!==void 0&&e.jsxs("span",{children:[d("search.usage"),": ",d("search.usageCount",{count:E.usageCount})]})]}),j===B&&e.jsxs("div",{className:"mt-3 pt-3 border-t border-slate-200",children:[E.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:d("search.recommendReason")}),e.jsx("p",{children:E.recommendReason})]}),e.jsxs("div",{className:"text-xs text-slate-600 max-h-[200px] overflow-auto bg-slate-50 p-3 rounded",children:[E.content.substring(0,500),"..."]}),e.jsx("button",{onClick:b=>{b.stopPropagation(),O(E),D(!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:d("search.viewFullContent")})]})]},B)),i&&e.jsx("div",{className:"flex items-center justify-center h-32",children:e.jsx(Pe,{size:K.lg,className:"animate-spin text-blue-600"})}),x.length===0&&u&&!i&&e.jsx("div",{className:"flex items-center justify-center h-32",children:e.jsxs("div",{className:"text-center text-slate-500",children:[e.jsx(Xt,{size:K.xl,className:"mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:d("search.noResults")})]})})]})]}),I&&$&&e.jsxs(Ze,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx(Ze.Backdrop,{className:"bg-black/20 dark:bg-black/40 backdrop-blur-sm"}),e.jsxs("div",{className:"relative bg-white rounded-lg shadow-2xl w-full max-w-2xl max-h-[90vh] flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"border-b border-slate-200 p-6 flex items-start justify-between shrink-0",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-bold text-slate-900",children:$.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:[d("search.similarity"),": ",Math.round($.similarity*100),"%"]}),$.isContextRelevant&&e.jsxs("span",{className:"text-xs bg-green-100 text-green-700 px-2 py-1 rounded",children:["✓ ",d("search.contextRelevant")]}),$.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:["🤖 ",d("search.quality"),": ",($.qualityScore*100).toFixed(0),"%"]}),((k=$.stats)==null?void 0:k.authorityScore)!==void 0&&e.jsxs("span",{className:"text-xs bg-purple-100 text-purple-700 px-2 py-1 rounded",children:[d("search.authorityScore"),": ",Math.round($.stats.authorityScore*100)/100]})]})]}),e.jsx("button",{onClick:()=>D(!1),className:"p-1 hover:bg-slate-100 rounded transition-colors shrink-0",children:e.jsx(Xe,{size:K.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:$.content?e.jsx(St,{code:$.content,language:"markdown"}):e.jsx("p",{className:"text-slate-500 text-sm",children:d("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:()=>D(!1),className:"px-4 py-2 text-slate-700 hover:bg-slate-200 rounded transition-colors text-sm font-medium",children:d("common.close")}),n&&e.jsxs("button",{onClick:()=>{n($.name),D(!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:K.md}),d("search.useSnippet")]})]})]})]})]}):null},Ta=t=>la(t.language)||"text";function ai(t){const s=[],a=t.match(/#import\s+"([^"]+)"/);if(a){const d=a[1].replace(/\.h$/,"");s.push(d)}const r=t.match(/#import\s+<([^>]+)>/);if(r){const d=r[1].replace(/\.h$/,"").split("/");s.push(...d)}const o=t.match(/^import\s+(\w+)/);o&&s.push(o[1]);const n=t.match(/@import\s+(\w+)/);return n&&s.push(n[1]),[...new Set(s.filter(Boolean))]}function ss(t,s){if(!s||!s.trim())return"unknown";const a=ai(t);return a.length===0?"unknown":a.some(r=>s.includes(r))?"used":"unused"}function ri(t){return t.startsWith("#import ")||t.startsWith("import ")||t.startsWith("@import ")?t.trim():t.startsWith("<")||t.startsWith('"')?`#import ${t.trim()}`:t.trim()}const ni=[{value:"",label:"—"},{value:"networking",label:"Networking"},{value:"ui",label:"UI"},{value:"data",label:"Data"},{value:"architecture",label:"Architecture"},{value:"conventions",label:"Conventions"}],li=t=>{var o;const s=(((o=t.content)==null?void 0:o.pattern)||"").trim();if(!s)return!1;const a=s.split(`
98
+ `).filter(n=>n.trim());return!(a.filter(n=>/^\s*(#{1,6}\s|[-*>]\s|\d+\.\s)/.test(n)).length>a.length*.3)},oi=({res:t,index:s,editingCodeIndex:a,setEditingCodeIndex:r,expandedEditIndex:o,setExpandedEditIndex:n,similarityMap:d,handleUpdateScanResult:u,handleSaveExtracted:c,handlePromoteToCandidate:x,openCompare:v,isSavingRecipe:g=!1})=>{var W,M,F;const{t:m}=Me(),[i,f]=l.useState(!1),j=o===s,C=t.headers||[],I=((W=t.content)==null?void 0:W.pattern)||"",D=((M=t.content)==null?void 0:M.markdown)||"",$=t.description||"",O=t.tags||[],T=li(t),Z=(k,E)=>{u(s,{content:{...t.content||{},[k]:E}})};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:m("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(ht,{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"?m("scanResult.lifecyclePending"):t.lifecycle==="active"?m("scanResult.lifecycleActive"):t.lifecycle==="deprecated"?m("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"?m("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:k=>u(s,{title:k.target.value})})]}),e.jsxs("div",{className:"flex gap-2 shrink-0 pt-3",children:[x&&e.jsxs("button",{onClick:()=>x(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(Fn,{size:K.md}),"Candidate"]}),e.jsxs("button",{onClick:()=>c(t),disabled:g,className:`text-xs px-4 py-2 rounded-lg font-bold transition-all shadow-sm flex items-center gap-1.5 active:scale-95 disabled:opacity-60 disabled:cursor-not-allowed whitespace-nowrap ${T&&t.mode==="full"?"bg-blue-600 text-white hover:bg-blue-700 dark:bg-blue-500/20 dark:text-blue-300 dark:hover:bg-blue-500/30 dark:border dark:border-blue-500/30":"bg-amber-600 text-white hover:bg-amber-700 dark:bg-amber-500/20 dark:text-amber-300 dark:hover:bg-amber-500/30 dark:border dark:border-amber-500/30"}`,children:[g?e.jsx(Pe,{size:K.md,className:"animate-spin"}):e.jsx(fr,{size:K.md}),m(g?"scanResult.saving":T?"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:m("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:m("scanResult.triggerPlaceholder"),onChange:k=>u(s,{trigger:k.target.value})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:"Kind"}),e.jsx(lt,{value:t.kind||"pattern",onChange:k=>u(s,{kind:k}),options:[{value:"rule",label:"Rule"},{value:"pattern",label:"Pattern"},{value:"fact",label:"Fact"}],size:"xs"})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:"Topic"}),e.jsx(lt,{value:t.topicHint||"",onChange:k=>u(s,{topicHint:k}),options:ni.map(k=>({value:k.value,label:k.label})),size:"xs"})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:m("scanResult.category")}),e.jsx(lt,{value:t.category||"",onChange:k=>u(s,{category:k}),options:cl.filter(k=>k!=="All").map(k=>({value:k,label:k})),size:"xs"})]}),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-px h-6 bg-slate-200 self-end mb-0.5"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:m("scanResult.language")}),e.jsx(lt,{value:la(t.language),onChange:k=>u(s,{language:k}),options:Jt.map(k=>({value:k.id,label:k.label})),size:"xs"})]})]}),t.moduleName&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-px h-6 bg-slate-200 self-end mb-0.5"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:m("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"}),T&&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:m("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:()=>u(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:()=>u(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:m("scanResult.difficulty")}),e.jsx(lt,{value:t.difficulty||"intermediate",onChange:k=>u(s,{difficulty:k,complexity:k}),options:[{value:"beginner",label:m("scanResult.difficultyBeginner")},{value:"intermediate",label:m("scanResult.difficultyIntermediate")},{value:"advanced",label:m("scanResult.difficultyAdvanced")}],size:"xs"})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:m("scanResult.authorityScore")}),e.jsx(lt,{value:String(t.authority??((F=t.stats)==null?void 0:F.authority)??3),onChange:k=>u(s,{authority:parseInt(k)}),options:[{value:"1",label:"⭐ 1",icon:""},{value:"2",label:"⭐⭐ 2",icon:""},{value:"3",label:"⭐⭐⭐ 3",icon:""},{value:"4",label:"⭐⭐⭐⭐ 4",icon:""},{value:"5",label:"⭐⭐⭐⭐⭐ 5",icon:""}],size:"xs",className:"font-bold text-amber-600 bg-amber-50 border-amber-100"})]})]}),e.jsx("div",{className:"mt-2.5",children:e.jsxs("div",{className:"flex flex-wrap gap-1 items-center bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 rounded-md px-1.5 py-0.5 min-h-[28px] focus-within:ring-2 focus-within:ring-blue-500/20",children:[O.map((k,E)=>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:[k,e.jsx("button",{onClick:()=>{const B=[...O];B.splice(E,1),u(s,{tags:B})},className:"text-blue-400 hover:text-red-500 transition-colors leading-none text-[10px]",title:"{t('scanResult.removeTag')}",children:"×"})]},E)),e.jsx("input",{className:"flex-1 min-w-[80px] text-[11px] text-slate-600 outline-none bg-transparent py-0.5",placeholder:O.length===0?m("scanResult.tagsPlaceholder"):"",onKeyDown:k=>{const E=k.currentTarget,B=E.value.trim();if((k.key==="Enter"||k.key===","||k.key===",")&&B){k.preventDefault();const b=B.replace(/[,,]/g,"").trim();b&&!O.includes(b)&&u(s,{tags:[...O,b]}),E.value=""}else if(k.key==="Backspace"&&!E.value&&O.length>0){const b=[...O];b.pop(),u(s,{tags:b})}},onBlur:k=>{const E=k.currentTarget.value.trim().replace(/[,,]/g,"").trim();E&&!O.includes(E)&&u(s,{tags:[...O,E]}),k.currentTarget.value=""}})]})}),T&&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:m("scanResult.headers")}),e.jsxs("button",{onClick:()=>n(o===s?null:s),className:`text-[10px] font-bold px-2 py-0.5 rounded-md transition-colors border ${j?"text-blue-700 bg-blue-100 border-blue-300":"text-blue-600 bg-blue-50 border-blue-100 hover:bg-blue-100"}`,children:[m(j?"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:()=>u(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?m("scanResultCard.includeMarkOn"):m("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 k=C.filter(B=>ss(B,I)==="used").length,E=C.filter(B=>ss(B,I)==="unused").length;return e.jsxs("span",{className:"text-[9px] text-slate-400",children:[k>0&&e.jsxs("span",{className:"text-green-600 font-bold",children:[k," ",m("scanResult.referenced")]}),k>0&&E>0&&" · ",E>0&&e.jsxs("span",{className:"text-amber-600 font-bold",children:[E," ",m("scanResult.unreferenced")]})]})})()]}),j&&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 k=C.map(E=>ri(E));u(s,{headers:k})},className:"text-[9px] px-2 py-0.5 bg-slate-200 text-slate-600 rounded hover:bg-slate-300 font-bold",title:m("scanResultCard.formatHeaders"),children:m("scanResult.formatHeaders")}),C.some(k=>ss(k,I)==="unused")&&e.jsx("button",{onClick:()=>{const k=C.filter(E=>ss(E,I)!=="unused");u(s,{headers:k})},className:"text-[9px] px-2 py-0.5 bg-amber-100 text-amber-700 rounded hover:bg-amber-200 font-bold",title:m("scanResultCard.cleanUnused"),children:m("scanResult.cleanUnused")}),e.jsx("button",{onClick:()=>{const k=[...C,wa(t.language)];u(s,{headers:k})},className:"text-[9px] px-2 py-0.5 bg-green-500 text-white rounded hover:bg-green-600 font-bold",children:m("scanResult.addHeader")})]}),e.jsx("div",{className:"space-y-1",children:C.map((k,E)=>{const B=ss(k,I);return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${B==="used"?"bg-green-500":B==="unused"?"bg-amber-400":"bg-slate-300"}`,title:m(B==="used"?"scanResult.usedInCode":B==="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 ${B==="unused"?"border-amber-300 text-amber-700 dark:border-amber-700 dark:text-amber-400":"border-slate-200 dark:border-slate-600"}`,value:k,onChange:b=>{const h=[...C];h[E]=b.target.value,u(s,{headers:h})},placeholder:wa(t.language)}),B==="unused"&&e.jsx("span",{className:"text-[8px] text-amber-500 font-bold shrink-0",children:m("scanResult.unreferenced")}),e.jsx("button",{onClick:()=>{const b=C.filter((h,L)=>L!==E);u(s,{headers:b})},className:"px-2 py-1 bg-red-500 text-white rounded hover:bg-red-600 text-[9px] font-bold shrink-0",children:m("scanResult.deleteHeader")})]},E)})})]})]})]}),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}),m("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:k=>u(s,{doClause:k.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:k=>u(s,{dontClause:k.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:k=>u(s,{whenClause:k.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:[m("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:m("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:[m("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:m("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:$,onChange:k=>u(s,{description:k.target.value,summary:k.target.value}),placeholder:m("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:m("scanResult.markdown")}),e.jsx("button",{type:"button",onClick:()=>f(!i),className:`flex items-center gap-1 text-[10px] font-bold px-2 py-1 rounded transition-colors ${i?"text-blue-600 hover:text-blue-700 bg-blue-50":"text-slate-500 hover:text-slate-700 hover:bg-slate-100"}`,children:i?e.jsxs(e.Fragment,{children:[e.jsx(yt,{size:K.xs})," ",m("scanResult.done")]}):e.jsxs(e.Fragment,{children:[e.jsx(Ws,{size:K.xs})," ",m("common.edit")]})})]}),i?e.jsx("textarea",{rows:Math.max(6,(D||"").split(`
99
+ `).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:D,onChange:k=>Z("markdown",k.target.value)}):D?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:D}):e.jsx("p",{className:"text-xs text-slate-400 italic py-2",children:m("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:m("scanResult.code")}),a===s?e.jsxs("button",{type:"button",onClick:()=>r(null),className:"flex items-center gap-1 text-[10px] font-bold text-blue-600 hover:text-blue-700 px-2 py-1 rounded bg-blue-50",children:[e.jsx(yt,{size:K.xs})," ",m("scanResult.done")]}):e.jsxs("button",{type:"button",onClick:()=>r(s),className:"flex items-center gap-1 text-[10px] font-bold text-slate-500 hover:text-slate-700 px-2 py-1 rounded hover:bg-slate-100",title:m("common.edit"),children:[e.jsx(Ws,{size:K.xs})," ",m("common.edit")]})]}),a===s?e.jsx("div",{className:"rounded-xl overflow-hidden",children:e.jsx(Ls,{value:I,onChange:k=>Z("pattern",k),language:Ta(t),height:`${Math.min(12,I.split(`
100
+ `).length)*20+16}px`})}):I?e.jsx(St,{code:I,language:Ta(t),showLineNumbers:!0}):e.jsx("p",{className:"text-xs text-slate-400 italic py-4",children:m("scanResult.noCode")})]}),(()=>{const k=t.candidateId??t.id??`scan-${s}`,E=d[k],B=(E||[]).filter(L=>L.similarity>=.6);if(B.length===0)return null;const b=B.filter(L=>L.similarity>=.85),h=b.length>0;return e.jsxs("div",{className:"space-y-1.5",children:[h&&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:m("scanResult.highDuplicateRisk")}),b.map(L=>e.jsxs("button",{onClick:()=>v(t,L.recipeName,E||[]),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:[L.recipeName.replace(/\.md$/i,"")," ",(L.similarity*100).toFixed(0),"%"]},L.recipeName)),e.jsx("span",{className:"text-[10px] text-red-500",children:m("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:m("scanResult.similarRecipes")}),B.slice(0,5).map(L=>e.jsxs("button",{onClick:()=>v(t,L.recipeName,E||[]),className:`text-[10px] font-bold px-2 py-1 rounded border transition-colors flex items-center gap-1 ${L.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:m("scanResultCard.similarWithClick",{name:L.recipeName,score:(L.similarity*100).toFixed(0)}),children:[e.jsx(ks,{size:K.xs}),L.recipeName.replace(/\.md$/i,"")," ",(L.similarity*100).toFixed(0),"%"]},L.recipeName))]})]})})()]})]})},ii=t=>{const s=(t.language||"").toLowerCase();return["objectivec","objc","objective-c","obj-c"].includes(s)?"objectivec":t.language||"text"},ci=({data:t,onClose:s,onDataChange:a,recipes:r,handleSaveExtracted:o,handleDeleteCandidate:n,onEditRecipe:d,isSavingRecipe:u=!1})=>{var I,D,$,O;const{t:c}=Me(),x=t.candidate,v=ii(x),g=()=>{var M,F;const T=[],Z=((M=x.content)==null?void 0:M.pattern)||"",W=((F=x.content)==null?void 0:F.markdown)||x.doClause||"";Z&&T.push("## Snippet / Code Reference\n\n```"+v+`
101
+ `+Z+"\n```"),W&&T.push(`
102
+ ## AI Context / Usage Guide
103
+
104
+ `+W),navigator.clipboard.writeText(T.join(`
105
+ `)||"").then(()=>re(c("spmCompare.candidateCopied"),{title:c("spmCompare.copied")}))},m=()=>{const T=ca(t.recipeContent);navigator.clipboard.writeText(T).then(()=>re(c("spmCompare.recipeCopied"),{title:c("spmCompare.copied")}))},i=async T=>{if(T===t.recipeName)return;const Z=t.recipeContents[T];if(Z)a({...t,recipeName:T,recipeContent:Z});else{let W="";const M=r==null?void 0:r.find(F=>F.name===T||F.name.endsWith("/"+T));if(M!=null&&M.content)W=[M.content.pattern,M.content.markdown].filter(Boolean).join(`
106
+
107
+ `)||"";else try{W=(await ne.getRecipeContentByName(T)).content}catch{return}a({...t,recipeName:T,recipeContent:W,recipeContents:{...t.recipeContents,[T]:W}})}},f=async()=>{if(!(!x.candidateId||!t.targetName||!n)&&window.confirm(c("spmCompare.deleteConfirm")))try{await n(t.targetName,x.candidateId),s()}catch(T){re((T==null?void 0:T.message)||c("spmCompare.deleteFailed"),{title:c("spmCompare.deleteFailed"),type:"error"})}},j=()=>{o(x),s()},C=()=>{const T=r==null?void 0:r.find(Z=>Z.name===t.recipeName||Z.name.endsWith("/"+t.recipeName));T?d==null||d(T):d==null||d({name:t.recipeName,content:{markdown:t.recipeContent}}),s()};return e.jsxs(Te,{open:!0,onClose:s,size:"full",children:[e.jsxs(Te.Header,{title:c("spmCompare.compareTitle"),children:[e.jsxs(Te.HeaderActions,{children:[x.candidateId&&t.targetName&&e.jsx(We,{variant:"danger",size:"sm",onClick:f,children:c("spmCompare.deleteCandidate")}),e.jsxs(We,{variant:"ghost",size:"sm",onClick:j,disabled:u,children:[u?e.jsx(Pe,{size:K.xs,className:"animate-spin"}):null,c("spmCompare.auditCandidate")]}),e.jsx(We,{variant:"ghost",size:"sm",onClick:C,children:c("spmCompare.editRecipe")})]}),e.jsx(Te.CloseButton,{onClose:s})]}),e.jsxs(Te.Body,{children:[t.similarList.length>1&&e.jsxs("div",{className:"flex flex-wrap gap-1.5 px-5 py-2 border-b border-[var(--border-default)] bg-[var(--bg-subtle)] shrink-0",children:[e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] font-bold self-center",children:c("spmCompare.switchRecipe")}),t.similarList.map(T=>e.jsxs("button",{onClick:()=>i(T.recipeName),className:`text-[10px] font-bold px-2 py-1 rounded transition-colors ${t.recipeName===T.recipeName?"bg-emerald-200 text-emerald-800":"bg-[var(--bg-surface)] text-emerald-600 hover:bg-emerald-100 border border-emerald-200"}`,children:[T.recipeName.replace(/\.md$/i,"")," ",(T.similarity*100).toFixed(0),"%"]},T.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-[var(--border-default)]",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-[var(--border-default)] bg-blue-50/40 shrink-0",children:[e.jsx("span",{className:"text-xs font-bold text-blue-700 truncate",children:c("spmCompare.candidateTitle",{title:x.title||""})}),e.jsx("button",{onClick:g,className:"p-1 hover:bg-blue-100 rounded text-blue-500 shrink-0",title:c("spmCompare.copyCandidate"),children:e.jsx(Qt,{size:K.xs})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e.jsxs("div",{className:"markdown-body text-[var(--fg-secondary)] space-y-4",children:[e.jsx("h3",{className:"text-sm font-bold",children:"Snippet / Code Reference"}),(I=x.content)!=null&&I.pattern?e.jsx(St,{code:((D=x.content)==null?void 0:D.pattern)||"",language:v,className:"!overflow-visible"}):e.jsx("p",{className:"text-[var(--fg-muted)] italic text-xs",children:c("spmCompare.noCode")}),e.jsx("h3",{className:"text-sm font-bold mt-4",children:c("spmCompare.aiContextProfile")}),($=x.content)!=null&&$.markdown||x.doClause?e.jsx(Et,{content:((O=x.content)==null?void 0:O.markdown)||x.doClause||""}):e.jsx("p",{className:"text-[var(--fg-muted)] italic text-xs",children:c("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-[var(--border-default)] 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:m,className:"p-1 hover:bg-emerald-100 rounded text-emerald-500 shrink-0",title:c("spmCompare.copyRecipe"),children:e.jsx(Qt,{size:K.xs})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e.jsx(Et,{content:t.recipeContent,stripFrontmatter:!0})})]})]})]})]})},Ea={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"},Pa={swift:"Swift",objectivec:"ObjC",go:"Go",python:"Py",java:"Java",kotlin:"KT",javascript:"JS",typescript:"TS",rust:"RS",ruby:"RB",c:"C",cpp:"C++"},di=({targets:t,filteredTargets:s,selectedTargetName:a,isScanning:r,scanProgress:o,scanFileList:n,scanResults:d,guardAudit:u,handleScanTarget:c,handleScanProject:x,handleUpdateScanResult:v,handleSaveExtracted:g,handlePromoteToCandidate:m,handleDeleteCandidate:i,onEditRecipe:f,isShellTarget:j,recipes:C=[],isSavingRecipe:I=!1,handleRefreshProject:D,onAddCustomFolder:$,onRemoveCustomFolder:O})=>{var se,we;const{t:T}=Me(),[Z,W]=l.useState(null),[M,F]=l.useState(null),[k,E]=l.useState({}),[,B]=l.useState(null),[b,h]=l.useState(null),[L,ie]=l.useState(!1),[Y]=l.useState(),[ge]=l.useState(),Ne=l.useRef(new Set),fe=l.useRef([]),[w,N]=l.useState([]),[P,U]=l.useState(!1),Q=l.useRef(!1),ue=3,[ce,ke]=l.useState("modules"),Le=l.useRef(!1),Ie=l.useMemo(()=>s.filter(V=>!j(V.name)).length,[s,j]);l.useEffect(()=>{Le.current||t.length!==0&&(Le.current=!0,Ie<ue?ke("folders"):ke("modules"))},[t.length,Ie]),l.useEffect(()=>{ce!=="folders"||Q.current||(Q.current=!0,U(!0),ne.browseDirectories("",3).then(V=>{N(V)}).catch(()=>{N([])}).finally(()=>{U(!1)}))},[ce]);const Be=l.useCallback(V=>{const ye={name:V.name,packageName:V.name,packagePath:V.path,targetDir:V.path,path:V.path,type:"directory",language:V.language||"unknown",discovererId:"folder-scan",discovererName:T("moduleExplorer.discovererFolderScan"),info:{source:"manual-folder-scan",originalPath:V.path},isVirtual:!0};$==null||$(ye),c(ye),ke("modules")},[c,$,T]),H=l.useCallback(async(V,ye)=>{if(!Ne.current.has(V)){Ne.current.add(V),B(V);try{const Re=ye.candidateId&&ye.targetName?{targetName:ye.targetName,candidateId:ye.candidateId}:{candidate:ye.candidate||{}},je=await ne.getCandidateSimilarityEx(Re);E(pe=>({...pe,[V]:je.similar||[]}))}catch{E(je=>({...je,[V]:[]}))}finally{B(null)}}},[]),S=l.useCallback(async(V,ye,Re=[])=>{var p,z,G;const je=V.candidateTargetName||"",pe=ye.replace(/\.md$/i,"");let _e="";const q=C==null?void 0:C.find(A=>A.name===pe||A.name.endsWith("/"+pe));if(q!=null&&q.content)_e=[q.content.pattern,q.content.markdown].filter(Boolean).join(`
108
+
109
+ `)||"";else try{_e=(await ne.getRecipeContentByName(pe)).content}catch(A){const _=(p=A.response)==null?void 0:p.status,J=((G=(z=A.response)==null?void 0:z.data)==null?void 0:G.message)||A.message;_===404?re(T("moduleExplorer.recipeNotExist",{name:pe}),{title:T("moduleExplorer.recipeNotExistTitle"),type:"error"}):re(J,{title:T("moduleExplorer.loadRecipeFailed"),type:"error"});return}const y={[pe]:_e};h({candidate:V,targetName:je,recipeName:pe,recipeContent:_e,similarList:Re.slice(0,3),recipeContents:y})},[C]);return l.useEffect(()=>{const V=d.map((pe,_e)=>pe.candidateId??`scan-${_e}`),ye=fe.current;(V.length!==ye.length||V.some((pe,_e)=>pe!==ye[_e]))&&(Ne.current.clear(),fe.current=V);const je=setTimeout(()=>{d.forEach((pe,_e)=>{var y,p;const q=pe.candidateId??pe.id??`scan-${_e}`;pe.candidateId&&pe.candidateTargetName?H(q,{targetName:pe.candidateTargetName,candidateId:pe.candidateId}):H(q,{candidate:{title:pe.title,summary:pe.description||"",code:((y=pe.content)==null?void 0:y.pattern)||"",usageGuide:((p=pe.content)==null?void 0:p.markdown)||""}})})},800);return()=>clearTimeout(je)},[d,H]),e.jsxs("div",{className:"flex gap-4 xl:gap-6 2xl:gap-8 h-full",children:[e.jsxs("div",{className:"w-64 xl:w-72 2xl:w-80 bg-[var(--bg-surface)] rounded-xl border border-[var(--border-default)] flex flex-col overflow-hidden shrink-0",children:[e.jsx("div",{className:"p-3 bg-[var(--bg-subtle)] border-b border-[var(--border-default)]",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-0.5 bg-[var(--bg-subtle)] rounded-lg p-0.5",children:[e.jsx("button",{onClick:()=>ke("modules"),className:`text-[11px] px-2.5 py-1.5 rounded-md font-bold transition-all ${ce==="modules"?"bg-[var(--bg-surface)] text-blue-700 shadow-sm":"text-[var(--fg-secondary)] hover:text-[var(--fg-primary)]"}`,children:T("moduleExplorer.modulesTabLabel",{count:Ie})}),e.jsx("button",{onClick:()=>ke("folders"),className:`text-[11px] px-2.5 py-1.5 rounded-md font-bold transition-all ${ce==="folders"?"bg-[var(--bg-surface)] text-blue-700 shadow-sm":"text-[var(--fg-secondary)] hover:text-[var(--fg-primary)]"}`,children:T("moduleExplorer.foldersTabLabel")})]}),D&&e.jsx("button",{onClick:D,title:T("moduleExplorer.refreshProject"),className:"p-1.5 rounded-md hover:bg-blue-50 text-[var(--fg-secondary)] hover:text-blue-600 border border-transparent hover:border-blue-200 transition-all",children:e.jsx(jt,{size:K.md})})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto p-2 space-y-1",children:ce==="modules"?e.jsx(e.Fragment,{children:s.map(V=>{const ye=j(V.name),Re=a===V.name,je=V.isVirtual||V.discovererId==="folder-scan",pe=V.language||"",_e=Ea[pe]||"bg-[var(--bg-subtle)] text-[var(--fg-secondary)] border-[var(--border-default)]",q=V.packageName&&V.packageName!==V.name?V.packageName:V.discovererName||"";return e.jsxs("button",{onClick:()=>c(V),disabled:r,className:`w-full text-left p-3 rounded-lg flex items-center justify-between group transition-all border ${r?"opacity-50 cursor-not-allowed":"hover:bg-[var(--bg-subtle)]"} ${Re?"bg-blue-50 border-blue-200 ring-1 ring-blue-200":"bg-[var(--bg-surface)] border-transparent"} ${ye?"opacity-90":""}`,children:[e.jsxs("div",{className:`flex flex-col max-w-[85%] ${ye?"opacity-60":""}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[!ye&&e.jsx("div",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${je?"bg-emerald-500":"bg-blue-600"}`}),e.jsx("span",{className:`text-sm truncate ${ye?"font-medium":"font-bold"} ${Re?"text-blue-700":""}`,children:V.name}),pe&&!ye&&!je&&pe!=="unknown"&&e.jsx("span",{className:`text-[9px] font-bold px-1.5 py-0.5 rounded border shrink-0 ${_e}`,children:Pa[pe]||pe.toUpperCase()})]}),q&&e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] truncate pl-3",children:q})]}),ye?e.jsx("span",{className:"text-[9px] font-bold text-[var(--fg-muted)] border border-[var(--border-default)] px-1 rounded",children:"SHELL"}):je&&O?e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[e.jsx(et,{size:K.sm,className:`${Re?"text-blue-500 opacity-100":"text-blue-500 opacity-0 group-hover:opacity-100"} transition-opacity`}),e.jsx("button",{onClick:y=>{y.stopPropagation(),O(V.path||"")},title:T("moduleExplorer.removeFolder"),className:"p-0.5 rounded text-[var(--fg-muted)] hover:text-red-500 hover:bg-red-50 opacity-0 group-hover:opacity-100 transition-all",children:e.jsx(ot,{size:12})})]}):e.jsx(et,{size:K.sm,className:`shrink-0 ${Re?"text-blue-500 opacity-100":"text-blue-500 opacity-0 group-hover:opacity-100"} transition-opacity`})]},`${V.discovererId||"default"}::${V.name}`)})}):e.jsxs(e.Fragment,{children:[P?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-[var(--fg-muted)]",children:[e.jsx(Pe,{size:K.lg,className:"animate-spin mb-3 opacity-40"}),e.jsx("p",{className:"text-xs",children:T("moduleExplorer.scanningDirs")})]}):w.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-[var(--fg-muted)]",children:[e.jsx(Dt,{size:K.xl,className:"mb-3 opacity-20"}),e.jsx("p",{className:"text-xs text-center px-4 leading-relaxed",children:T("moduleExplorer.noDirs")})]}):w.map(V=>{const ye=Ea[V.language]||"bg-[var(--bg-subtle)] text-[var(--fg-secondary)] border-[var(--border-default)]";return e.jsxs("button",{onClick:()=>Be(V),disabled:r||!V.hasSourceFiles,className:`w-full text-left p-2.5 rounded-lg flex items-center gap-2.5 transition-all border border-transparent
110
+ ${V.hasSourceFiles?r?"opacity-50 cursor-not-allowed":"hover:bg-emerald-50 hover:border-emerald-200 cursor-pointer":"opacity-40 cursor-not-allowed"}
111
+ `,style:{paddingLeft:`${V.depth*14+10}px`},children:[e.jsx(Dt,{size:K.sm,className:V.hasSourceFiles?"text-emerald-500 shrink-0":"text-[var(--fg-muted)] shrink-0"}),e.jsx("span",{className:"text-sm font-medium flex-1 truncate",children:V.name}),V.hasSourceFiles&&V.language!=="unknown"&&e.jsx("span",{className:`text-[9px] font-bold px-1.5 py-0.5 rounded border shrink-0 ${ye}`,children:Pa[V.language]||V.language.toUpperCase()}),V.hasSourceFiles&&e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] shrink-0",children:T("moduleExplorer.sourceFileCount",{count:V.sourceFileCount})}),e.jsx(rt,{size:12,className:"text-[var(--fg-muted)] shrink-0"})]},V.path)}),e.jsx("div",{className:"px-3 py-2 text-[10px] text-[var(--fg-muted)] text-center",children:T("moduleExplorer.selectFolderHint")})]})})]}),e.jsxs("div",{className:"flex-1 bg-[var(--bg-surface)] rounded-xl border border-[var(--border-default)] flex flex-col overflow-hidden relative",children:[e.jsx("div",{className:"p-4 bg-[var(--bg-subtle)] border-b border-[var(--border-default)] font-bold text-sm flex justify-between items-center",children:e.jsxs("div",{className:"flex items-center gap-2",children:[a==="__project__"?e.jsxs(e.Fragment,{children:[e.jsx(ht,{size:K.md,className:"text-indigo-500"}),e.jsx("span",{children:T("moduleExplorer.fullProjectResults")}),d.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:K.md,className:"text-blue-500"}),e.jsx("span",{children:T("moduleExplorer.moduleLabel",{name:a})}),d.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($t,{size:K.md,className:"text-[var(--fg-muted)]"}),e.jsx("span",{children:T("moduleExplorer.reviewResults")})]}),d.length>0&&e.jsxs("span",{className:"text-[var(--fg-muted)] font-normal text-xs ml-1",children:["(",T("moduleExplorer.resultsCount",{count:d.length}),(se=d[0])!=null&&se.trigger?T("moduleExplorer.candidateSuffix"):"",")"]})]})}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-8 relative",children:[r&&e.jsxs("div",{className:"absolute inset-0 bg-[var(--bg-surface)] backdrop-blur-[2px] z-10 flex flex-col items-center justify-center text-blue-600 px-4 xl:px-8 overflow-y-auto",children:[e.jsxs("div",{className:"relative mb-6",children:[e.jsx("div",{className:"w-16 h-16 border-4 border-blue-100 border-t-blue-600 rounded-full animate-spin"}),e.jsx(ps,{size:K.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__"?T("moduleExplorer.fullProjectScanning"):T("moduleExplorer.moduleScanLabel",{name:a||"..."})}),e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] mb-4",children:o.status}),e.jsx("div",{className:"w-full max-w-md bg-[var(--bg-subtle)] rounded-full h-2.5 overflow-hidden",children:e.jsx("div",{className:"h-full bg-blue-600 rounded-full transition-all duration-500 ease-out",style:{width:`${Math.min(o.total?o.current/o.total*100:0,98)}%`}})}),e.jsx("p",{className:"text-xs text-[var(--fg-muted)] mt-3",children:o.total?`${Math.round(o.current/o.total*100)}%`:"0%"})]}),!r&&d.length===0&&e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-[var(--fg-muted)] text-center",children:[e.jsx(Is,{size:K.xxxl,className:"mb-4 opacity-20"}),e.jsx("p",{className:"font-medium text-[var(--fg-secondary)]",children:T("moduleExplorer.knowledgeExtract")}),e.jsx("p",{className:"text-xs mt-2 max-w-sm leading-relaxed",children:T("moduleExplorer.knowledgeExtractHint")})]}),!r&&a==="__project__"&&(u==null?void 0:u.summary)&&e.jsxs("div",{className:`rounded-xl border p-4 ${u.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(mt,{size:K.md,className:u.summary.totalViolations>0?"text-amber-600":"text-emerald-600"}),e.jsx("span",{className:"text-sm font-bold text-[var(--fg-primary)]",children:T("moduleExplorer.guardAuditSummary")}),e.jsx("span",{className:"text-[10px] font-bold px-2 py-0.5 rounded-full bg-indigo-100 text-indigo-700 border border-indigo-200",children:"PROJECT SCAN"})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 xl:gap-6 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[var(--fg-secondary)]",children:T("moduleExplorer.auditedFiles")}),e.jsx("span",{className:"font-bold text-[var(--fg-primary)]",children:u.summary.totalFiles})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[var(--fg-secondary)]",children:T("moduleExplorer.totalViolationsLabel")}),e.jsx("span",{className:`font-bold ${u.summary.totalViolations>0?"text-amber-700":"text-emerald-700"}`,children:u.summary.totalViolations})]}),u.summary.errors>0&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Bt,{size:K.sm,className:"text-red-500"}),e.jsx("span",{className:"font-bold text-red-700",children:T("moduleExplorer.errorsCount",{count:u.summary.errors})})]}),u.summary.warnings>0&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Bt,{size:K.sm,className:"text-amber-500"}),e.jsx("span",{className:"font-bold text-amber-700",children:T("moduleExplorer.warningsCount",{count:u.summary.warnings})})]})]})]}),d.map((V,ye)=>e.jsx(oi,{res:V,index:ye,editingCodeIndex:Z,setEditingCodeIndex:W,expandedEditIndex:M,setExpandedEditIndex:F,similarityMap:k,handleUpdateScanResult:v,handleSaveExtracted:g,handlePromoteToCandidate:m,openCompare:S,isSavingRecipe:I},ye))]})]}),b&&e.jsx(ci,{data:b,onClose:()=>h(null),onDataChange:h,recipes:C,handleSaveExtracted:g,handleDeleteCandidate:i,onEditRecipe:f,isSavingRecipe:I}),e.jsx(si,{isOpen:L,onClose:()=>ie(!1),targetName:ge,currentFile:Y,language:((we=s.find(V=>V.name===a))==null?void 0:we.language)||"unknown",onSelectRecipe:V=>{}})]})},ui=72,pi=52,Ds=24,is=40,Or=36,Gt=140,os=40,cs=8;function mi(t,s){const a=new Set(t.map(u=>u.id)),r=new Map;for(const u of s)!a.has(u.from)||!a.has(u.to)||(r.has(u.from)||r.set(u.from,[]),r.get(u.from).push(u.to));const o=new Map,n=new Set;function d(u){if(o.has(u))return o.get(u);if(n.has(u))return 0;n.add(u);const c=r.get(u);if(!c||c.length===0)return o.set(u,0),n.delete(u),0;const x=1+Math.max(...c.map(d));return o.set(u,x),n.delete(u),x}return t.forEach(u=>d(u.id)),o}function xi(t){return Math.ceil(t/cs)}function gi(t,s){const a=mi(t,s),r=new Map;for(const g of t){const m=a.get(g.id)??0;r.has(m)||r.set(m,[]),r.get(m).push(g.id)}const o=[...new Set(a.values())].sort((g,m)=>g-m),n=[...o].reverse(),d=new Map,u=new Map,c=Math.min(cs,Math.max(...o.map(g=>(r.get(g)??[]).length),1)),x=(c-1)*Ds+c*Gt;let v=is;return n.forEach(g=>{const m=r.get(g)??[],i=xi(m.length),f=v;for(let C=0;C<i;C++){const I=m.slice(C*cs,(C+1)*cs),D=(I.length-1)*Ds+I.length*Gt,$=(x-D)/2;I.forEach((O,T)=>{const Z=is+Or+$+T*(Gt+Ds)+Gt/2,W=v+os/2;d.set(O,{x:Z,y:W})}),v+=C<i-1?pi:ui}const j=v-f;u.set(g,{y:f,h:j})}),{positions:d,tiers:a,tierOrder:o,tierYRanges:u}}const hi=()=>{const{t}=Me(),{isDark:s}=Fs(),[a,r]=l.useState(null),[o,n]=l.useState(!0),[d,u]=l.useState(null),[c,x]=l.useState(null),[v,g]=l.useState("package"),[m,i]=l.useState("all"),f=async()=>{var w,N;n(!0),u(null);try{const P=await ne.getDepGraph(v);r({nodes:Array.isArray(P==null?void 0:P.nodes)?P.nodes:[],edges:Array.isArray(P==null?void 0:P.edges)?P.edges:[],projectRoot:(P==null?void 0:P.projectRoot)??null,generatedAt:P==null?void 0:P.generatedAt})}catch(P){u(((N=(w=P.response)==null?void 0:w.data)==null?void 0:N.error)||P.message||"Failed to load dependency graph")}finally{n(!1)}};l.useEffect(()=>{f()},[v]);const j=Array.isArray(a==null?void 0:a.nodes)?a.nodes:[],C=Array.isArray(a==null?void 0:a.edges)?a.edges:[],I=j.some(w=>w.type==="internal"||w.type==="external"),D=l.useMemo(()=>!I||m==="all"?j:m==="internal"?j.filter(w=>w.type!=="external"):j.filter(w=>w.type!=="internal"),[j,m,I]),$=l.useMemo(()=>new Set(D.map(w=>w.id)),[D]),O=l.useMemo(()=>C.filter(w=>$.has(w.from)||$.has(w.to)),[C,$]),{positions:T,tiers:Z,tierOrder:W,tierYRanges:M}=l.useMemo(()=>gi(D,O),[D,O]),F=l.useMemo(()=>{const w=new Map;return D.forEach(N=>{const P=Z.get(N.id)??0;w.has(P)||w.set(P,[]),w.get(P).push(N.id)}),w},[D,Z]),k=l.useMemo(()=>[...W].reverse(),[W]),{dependsOn:E,dependedBy:B}=l.useMemo(()=>{const w=new Map,N=new Map;return O.forEach(P=>{w.has(P.from)||w.set(P.from,[]),w.get(P.from).push(P.to),N.has(P.to)||N.set(P.to,[]),N.get(P.to).push(P.from)}),{dependsOn:w,dependedBy:N}},[O]),b=Math.min(cs,Math.max(...W.map(w=>(F.get(w)??[]).length),1)),L=(b-1)*Ds+b*Gt+Or*2,ie=Math.max(600,is*2+L),Y=Math.max(...[...T.values()].map(w=>w.y),0),ge=Math.max(420,Y+os/2+is+20),Ne=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)"}],fe=w=>Ne[Math.min(w,Ne.length-1)]??Ne[0];return o?e.jsx("div",{className:"flex items-center justify-center min-h-[320px]",children:e.jsx("div",{className:"animate-spin rounded-full h-10 w-10 border-2 border-blue-600 border-t-transparent"})}):d?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:d}),e.jsx("button",{type:"button",onClick:f,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||j.length===0?e.jsxs("div",{className:"rounded-xl border border-[var(--border-default)] bg-[var(--bg-subtle)] p-8 text-[var(--fg-secondary)] shadow-sm",children:[e.jsx("p",{className:"font-medium text-[var(--fg-primary)]",children:t("depGraph.noDataTitle")}),e.jsx("p",{className:"mt-2 text-sm",children:t("depGraph.noDataDesc")})]}):e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"mb-4 flex flex-wrap justify-between items-center gap-3 shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-50 border border-blue-100 flex items-center justify-center shrink-0",children:e.jsx(ht,{className:"text-blue-600",size:20})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-lg xl:text-xl font-bold text-[var(--fg-primary)]",children:t("depGraph.title")}),e.jsxs("p",{className:"text-xs text-[var(--fg-muted)] mt-0.5 truncate",children:[t("depGraph.visualization"),a.projectRoot&&e.jsxs("span",{className:"ml-1",children:["· ",a.projectRoot]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[I&&e.jsx("div",{className:"flex items-center border border-[var(--border-default)] rounded-lg overflow-hidden text-xs",children:["all","internal","external"].map(w=>e.jsx("button",{type:"button",onClick:()=>i(w),className:`px-3 py-1.5 font-medium transition-colors ${m===w?"bg-blue-600 text-white":"bg-[var(--bg-surface)] text-[var(--fg-secondary)] hover:bg-[var(--bg-subtle)]"}`,children:t(w==="all"?"depGraph.filterAll":w==="internal"?"depGraph.filterInternal":"depGraph.filterExternal")},w))}),e.jsxs("button",{type:"button",onClick:()=>{f()},className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-all text-[var(--fg-secondary)] bg-[var(--bg-subtle)] border border-[var(--border-default)] hover:bg-[var(--bg-subtle)]",children:[e.jsx(jt,{size:14})," ",t("depGraph.refresh")]}),e.jsxs("div",{className:"flex items-center gap-2 xl:gap-3 text-xs flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-[var(--bg-subtle)] border border-[var(--border-default)]",children:[e.jsx(ht,{size:14,className:"text-[var(--fg-muted)]"}),e.jsxs("span",{className:"text-[var(--fg-secondary)]",children:[t("depGraph.packages")," ",e.jsx("strong",{className:"text-[var(--fg-primary)]",children:D.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:O.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 pb-6 space-y-6",children:[I&&e.jsxs("div",{className:"flex items-center gap-4 text-xs text-[var(--fg-secondary)] 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-[var(--border-emphasis)] bg-[var(--bg-surface)]"})," ",t("depGraph.projectRoot")]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded border-2 border-green-400 bg-green-50"})," ",t("depGraph.filterInternal")]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded border-2 border-amber-400 bg-amber-50 border-dashed"})," ",t("depGraph.filterExternal")]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded border-2 border-amber-400 bg-amber-50 border-dashed opacity-50"})," ",t("depGraph.labelIndirect")]})]}),e.jsxs("div",{className:"rounded-xl border border-[var(--border-default)] bg-[var(--bg-subtle)] overflow-auto shadow-sm min-h-[480px] flex items-center justify-center relative",children:[e.jsxs("svg",{width:"100%",height:ge,viewBox:`0 0 ${ie} ${ge}`,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"})})}),k.map((w,N)=>{const P=fe(N),U=M.get(w);return U?e.jsx("rect",{x:is,y:U.y-os/2-4,width:L,height:U.h+8,rx:8,fill:P.bg,stroke:P.border,strokeWidth:s?1.5:1,opacity:s?1:.6},w):null}),D.map(w=>{const N=T.get(w.id);if(!N)return null;const P=Z.get(w.id)??0,U=fe(k.indexOf(P)),Q=w.label.length>14?w.label.slice(0,13)+"…":w.label,ue=c===w.id,ce=c?(E.get(c)??[]).includes(w.id):!1,ke=c?(B.get(c)??[]).includes(w.id):!1,Le=c&&!ue&&!ce&&!ke,Ie=w.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"}:w.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:U.border,text:U.text,badge:""}:{fill:"white",stroke:U.border,text:U.text,badge:""},Be=c?ue?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}:ke?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:Ie.fill,stroke:Ie.stroke,text:Ie.text,strokeWidth:2,opacity:w.indirect?.55:1};return e.jsxs("g",{style:{cursor:"pointer",opacity:Be.opacity},onClick:()=>x(ue?null:w.id),children:[e.jsx("rect",{x:N.x-Gt/2,y:N.y-os/2,width:Gt,height:os,rx:10,ry:10,fill:Be.fill,stroke:Be.stroke,strokeWidth:Be.strokeWidth,filter:Le?void 0:"url(#nodeShadow)",strokeDasharray:w.type==="external"?"4 2":void 0}),e.jsx("text",{x:N.x,y:N.y+(Ie.badge?-2:0),textAnchor:"middle",dominantBaseline:"middle",fontSize:"12",fontWeight:"600",fill:Be.text,pointerEvents:"none",children:Q}),Ie.badge&&e.jsx("text",{x:N.x,y:N.y+12,textAnchor:"middle",dominantBaseline:"middle",fontSize:"8",fontWeight:"500",fill:Ie.text,opacity:.6,pointerEvents:"none",children:Ie.badge})]},w.id)})]}),c&&e.jsxs("div",{className:"absolute top-4 right-4 w-72 rounded-xl border border-[var(--border-default)] bg-[var(--bg-surface)] shadow-lg z-10 p-4",role:"dialog","aria-label":t("depGraph.dependencies"),children:[e.jsxs("div",{className:"flex items-center justify-between mb-3 pb-2 border-b border-[var(--border-default)]",children:[e.jsx("span",{className:"font-bold text-[var(--fg-primary)]",children:c}),e.jsx("button",{type:"button",onClick:()=>x(null),className:"text-[var(--fg-muted)] hover:text-[var(--fg-secondary)] text-lg leading-none","aria-label":t("depGraph.close"),children:"×"})]}),e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-[var(--fg-secondary)] mb-1",children:t("depGraph.dependencies")}),e.jsx("ul",{className:"text-[var(--fg-primary)] space-y-0.5",children:(E.get(c)??[]).length===0?e.jsx("li",{className:"text-[var(--fg-muted)]",children:t("depGraph.none")}):(E.get(c)??[]).map(w=>e.jsxs("li",{children:["→ ",w]},w))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-[var(--fg-secondary)] mb-1",children:t("depGraph.dependents")}),e.jsx("ul",{className:"text-[var(--fg-primary)] space-y-0.5",children:(B.get(c)??[]).length===0?e.jsx("li",{className:"text-[var(--fg-muted)]",children:t("depGraph.none")}):(B.get(c)??[]).map(w=>e.jsxs("li",{children:["← ",w]},w))})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"rounded-xl border border-[var(--border-default)] bg-[var(--bg-surface)] p-5 shadow-sm",children:[e.jsxs("h3",{className:"text-sm font-bold text-[var(--fg-primary)] mb-3 pb-2 border-b border-[var(--border-default)]",children:[t("depGraph.packageList")," (",D.length,")"]}),e.jsx("ul",{className:"text-sm space-y-3 max-h-[280px] overflow-y-auto pr-1",children:D.map(w=>e.jsxs("li",{className:"pb-3 border-b border-[var(--border-default)] last:border-0 last:pb-0",children:[e.jsxs("div",{className:"flex items-baseline gap-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-[var(--fg-primary)]",children:w.label||w.id}),w.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")}),w.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")}),w.indirect&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-[var(--bg-subtle)] text-[var(--fg-secondary)] border border-[var(--border-default)] font-medium",children:t("depGraph.labelIndirect")}),w.packageDir&&e.jsxs("span",{className:"text-[var(--fg-secondary)] text-xs",children:["· ",w.packageDir]})]}),w.fullPath&&e.jsx("div",{className:"mt-1 text-[var(--fg-muted)] text-xs truncate",children:w.fullPath}),w.targets&&w.targets.length>0&&e.jsxs("div",{className:"mt-1.5 text-[var(--fg-secondary)] text-xs pl-0",children:["Targets: ",e.jsx("span",{className:"text-[var(--fg-secondary)]",children:w.targets.join(", ")})]})]},w.id))})]}),e.jsxs("div",{className:"rounded-xl border border-[var(--border-default)] bg-[var(--bg-surface)] p-5 shadow-sm",children:[e.jsxs("h3",{className:"text-sm font-bold text-[var(--fg-primary)] mb-3 pb-2 border-b border-[var(--border-default)]",children:[t("depGraph.depRelations")," (",O.length,")"]}),e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] mb-2",children:t("depGraph.depRelationsDesc")}),e.jsx("ul",{className:"text-sm space-y-2 max-h-[280px] overflow-y-auto pr-1",children:O.map((w,N)=>e.jsxs("li",{className:"flex items-center gap-2 text-[var(--fg-primary)]",children:[e.jsx("span",{className:"font-semibold text-[var(--fg-primary)]",children:w.from}),e.jsx("span",{className:"text-[var(--fg-muted)] shrink-0",children:"→"}),e.jsx("span",{className:"font-semibold text-[var(--fg-primary)]",children:w.to})]},`${w.from}-${w.to}-${N}`))})]}),v==="target"&&e.jsxs("p",{className:"text-xs text-[var(--fg-secondary)] mt-2",children:[t("depGraph.targetHint"),e.jsx("span",{className:"font-mono",children:"Package::Target"})]})]})]})]})},fi=({onRefresh:t})=>{const{t:s}=Me(),[a,r]=l.useState({}),[o,n]=l.useState([]),[d,u]=l.useState([]),[c,x]=l.useState(null),[v,g]=l.useState(!0),[m,i]=l.useState(!1),[f,j]=l.useState({ruleId:"",message:"",severity:"warning",pattern:"",languages:[],note:"",dimension:""}),[C,I]=l.useState(!1),[D,$]=l.useState(""),O=async()=>{try{const[N,P]=await Promise.all([ne.getGuardRules(),ne.getGuardViolations()]);r((N==null?void 0:N.rules)||{}),u((N==null?void 0:N.projectLanguages)||[]),n((P==null?void 0:P.runs)||[])}catch{r({}),n([])}finally{g(!1)}};l.useEffect(()=>{O()},[]);const T=async()=>{if(window.confirm(s("guard.clearConfirm")))try{await ne.clearViolations(),O(),t==null||t()}catch(N){re((N==null?void 0:N.message)||s("common.operationFailed"),{title:s("common.operationFailed"),type:"error"})}},Z=N=>{j(P=>({...P,languages:P.languages.includes(N)?P.languages.filter(U=>U!==N):[...P.languages,N]}))},W=async N=>{var P,U;if(N.preventDefault(),$(""),!f.ruleId.trim()||!f.message.trim()||!f.pattern.trim()||f.languages.length===0){$(s("guard.addRuleValidation"));return}I(!0);try{await ne.saveGuardRule({ruleId:f.ruleId.trim(),message:f.message.trim(),severity:f.severity,pattern:f.pattern.trim(),languages:f.languages,note:f.note.trim()||void 0,...f.dimension?{dimension:f.dimension}:{}}),j({ruleId:"",message:"",severity:"warning",pattern:"",languages:[],note:"",dimension:""}),i(!1),O(),t==null||t()}catch(Q){$(((U=(P=Q==null?void 0:Q.response)==null?void 0:P.data)==null?void 0:U.error)||(Q==null?void 0:Q.message)||s("common.saveFailed"))}finally{I(!1)}},F=l.useMemo(()=>{const N=Object.entries(a);return d.length===0?N:N.filter(([,P])=>!P.languages||P.languages.length===0?!0:P.languages.some(U=>d.includes(U)))},[a,d]),k=o.reduce((N,P)=>N+P.violations.length,0),[E,B]=l.useState("all"),[b,h]=l.useState("all"),L=l.useMemo(()=>{const N=new Set;for(const[,U]of F)(U.languages||[]).forEach(Q=>N.add(Q));const P=Jt.filter(U=>N.has(U.id)).map(U=>U.id);for(const U of N)P.includes(U)||P.push(U);return P},[F]),ie=N=>{var P;return((P=Jt.find(U=>U.id===N))==null?void 0:P.label)||N},Y=l.useMemo(()=>{const N={error:0,warning:0,info:0};for(const[,P]of F){const U=P.severity;N[U]!==void 0&&N[U]++}return N},[F]),ge=N=>{const P={safety:s("guard.categorySafety"),correctness:s("guard.categoryCorrectness"),performance:s("guard.categoryPerformance"),style:s("guard.categoryStyle")};return N?P[N]||N:"—"},Ne=(N,P)=>{const U=`guardRuleMessages.${N}`,Q=s(U);return Q!==U?Q:P},fe=(N,P)=>{if(!P)return P;const U=`guardRuleFixSuggestions.${N}`,Q=s(U);return Q!==U?Q:P},w=l.useMemo(()=>F.filter(([,N])=>!(E!=="all"&&!(N.languages||[]).includes(E)||b!=="all"&&N.severity!==b)),[F,E,b]);return v?e.jsx("div",{className:"p-6 text-[var(--fg-secondary)]",children:s("common.loading")}):e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"mb-4 flex flex-wrap justify-between items-center gap-3 shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-blue-50 border border-blue-100 flex items-center justify-center shrink-0",children:e.jsx(mt,{className:"text-blue-600",size:20})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-lg xl:text-xl font-bold text-[var(--fg-primary)]",children:s("guard.title")}),e.jsxs("p",{className:"text-xs text-[var(--fg-muted)] mt-0.5 truncate",children:[s("guard.summary"),d.length>0&&e.jsxs("span",{className:"ml-1.5",children:["· ",s("guard.currentProject"),":",d.map(N=>ie(N)).join(" / ")]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("a",{href:ul,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-all text-[var(--fg-secondary)] bg-[var(--bg-subtle)] border border-[var(--border-default)] hover:bg-[var(--bg-subtle)]",children:[e.jsx(zn,{size:14})," ",s("guard.reportIssue")]}),e.jsxs("button",{type:"button",onClick:()=>i(!m),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:[m?e.jsx(Rt,{size:14}):e.jsx(rt,{size:14}),s("guard.addRule")]}),o.length>0&&e.jsxs("button",{type:"button",onClick:T,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-[var(--bg-subtle)] border border-[var(--border-default)]",children:[e.jsx(mt,{size:14,className:"text-[var(--fg-muted)]"}),e.jsxs("span",{className:"text-[var(--fg-secondary)]",children:[s("guard.tableHeaders.rule")," ",e.jsx("strong",{className:"text-[var(--fg-primary)]",children:F.length})]})]}),k>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(Bt,{size:14,className:"text-amber-400"}),e.jsx("span",{className:"text-amber-600",children:s("guard.totalViolations",{count:k})})]})]})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto pr-1 pb-6",children:[m&&e.jsx("section",{className:"mb-6",children:e.jsxs("form",{onSubmit:W,className:"p-4 bg-[var(--bg-surface)] border border-[var(--border-default)] 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-[var(--fg-secondary)] mb-1",children:s("guard.ruleId")}),e.jsx("input",{id:"rule-id",name:"ruleId",type:"text",value:f.ruleId,onChange:N=>j(P=>({...P,ruleId:N.target.value})),className:"w-full px-3 py-2 border border-[var(--border-default)] 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-[var(--fg-secondary)] mb-1",children:s("guard.severity")}),e.jsx(lt,{id:"rule-severity",name:"severity",value:f.severity,onChange:N=>j(P=>({...P,severity:N})),options:[{value:"warning",label:"warning"},{value:"error",label:"error"}],size:"md",className:"w-full"})]})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"rule-message",className:"block text-xs font-medium text-[var(--fg-secondary)] mb-1",children:s("guard.message")}),e.jsx("input",{id:"rule-message",name:"message",type:"text",value:f.message,onChange:N=>j(P=>({...P,message:N.target.value})),className:"w-full px-3 py-2 border border-[var(--border-default)] 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-[var(--fg-secondary)] mb-1",children:s("guard.patternLabel")}),e.jsx("input",{id:"rule-pattern",name:"pattern",type:"text",value:f.pattern,onChange:N=>j(P=>({...P,pattern:N.target.value})),className:"w-full px-3 py-2 border border-[var(--border-default)] 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-[var(--fg-secondary)] mb-1",children:s("guard.languagesLabel")}),e.jsx("div",{className:"flex gap-3 flex-wrap",children:(d.length>0?Jt.filter(N=>d.includes(N.id)):Jt.slice(0,8)).map(N=>e.jsxs("label",{htmlFor:`lang-${N.id}`,className:"flex items-center gap-1.5 text-sm",children:[e.jsx("input",{id:`lang-${N.id}`,name:"languages",type:"checkbox",checked:f.languages.includes(N.id),onChange:()=>Z(N.id)}),N.label]},N.id))})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"rule-dimension",className:"block text-xs font-medium text-[var(--fg-secondary)] mb-1",children:s("guard.dimensionLabel")}),e.jsx(lt,{id:"rule-dimension",name:"dimension",value:f.dimension,onChange:N=>j(P=>({...P,dimension:N})),options:[{value:"",label:s("guard.dimNoLimit")},{value:"file",label:s("guard.dimFile")},{value:"target",label:s("guard.dimTarget")},{value:"project",label:s("guard.dimProject")}],size:"md",className:"w-full"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"rule-note",className:"block text-xs font-medium text-[var(--fg-secondary)] mb-1",children:s("guard.noteLabel")}),e.jsx("input",{id:"rule-note",name:"note",type:"text",value:f.note,onChange:N=>j(P=>({...P,note:N.target.value})),className:"w-full px-3 py-2 border border-[var(--border-default)] rounded-lg text-sm",placeholder:s("guard.notePlaceholder")})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{type:"submit",disabled:C,className:"px-4 py-2 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700 disabled:opacity-50",children:s(C?"common.saving":"common.confirm")}),e.jsx("button",{type:"button",onClick:()=>i(!1),className:"px-4 py-2 text-[var(--fg-secondary)] text-sm rounded-lg hover:bg-[var(--bg-subtle)]",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-[var(--fg-primary)] flex items-center gap-1.5",children:[e.jsx(br,{size:14,className:"text-[var(--fg-muted)]"}),s("guard.tableHeaders.rule"),e.jsxs("span",{className:"text-[var(--fg-muted)] font-normal",children:["(",w.length,"/",F.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:()=>h("all"),className:`px-2 py-1 rounded-md border transition-all ${b==="all"?"bg-slate-700 text-white border-slate-700":"bg-[var(--bg-surface)] text-[var(--fg-secondary)] border-[var(--border-default)] hover:bg-[var(--bg-subtle)]"}`,children:s("common.all")}),e.jsxs("button",{onClick:()=>h("error"),className:`px-2 py-1 rounded-md border transition-all flex items-center gap-1 ${b==="error"?"bg-red-600 text-white border-red-600":"bg-[var(--bg-surface)] text-red-600 border-red-200 hover:bg-red-50"}`,children:[e.jsx(Xt,{size:12})," error ",e.jsxs("span",{className:"opacity-70",children:["(",Y.error,")"]})]}),e.jsxs("button",{onClick:()=>h("warning"),className:`px-2 py-1 rounded-md border transition-all flex items-center gap-1 ${b==="warning"?"bg-amber-500 text-white border-amber-500":"bg-[var(--bg-surface)] text-amber-600 border-amber-200 hover:bg-amber-50"}`,children:[e.jsx(Bt,{size:12})," warning ",e.jsxs("span",{className:"opacity-70",children:["(",Y.warning,")"]})]}),e.jsxs("button",{onClick:()=>h("info"),className:`px-2 py-1 rounded-md border transition-all flex items-center gap-1 ${b==="info"?"bg-blue-500 text-white border-blue-500":"bg-[var(--bg-surface)] text-blue-600 border-blue-200 hover:bg-blue-50"}`,children:[e.jsx(Vs,{size:12})," info ",e.jsxs("span",{className:"opacity-70",children:["(",Y.info,")"]})]})]})})]}),e.jsxs("div",{className:"flex items-center gap-1.5 mb-3 flex-wrap",children:[e.jsx("button",{onClick:()=>B("all"),className:`px-2.5 py-1 rounded-full text-xs font-medium border transition-all ${E==="all"?"bg-slate-700 text-white border-slate-700":"bg-[var(--bg-surface)] text-[var(--fg-secondary)] border-[var(--border-default)] hover:bg-[var(--bg-subtle)]"}`,children:s("guard.allLanguages")}),L.map(N=>{const P=F.filter(([,U])=>(U.languages||[]).includes(N)).length;return e.jsxs("button",{onClick:()=>B(E===N?"all":N),className:`px-2.5 py-1 rounded-full text-xs font-medium border transition-all ${E===N?"bg-indigo-600 text-white border-indigo-600":"bg-[var(--bg-surface)] text-[var(--fg-secondary)] border-[var(--border-default)] hover:bg-[var(--bg-subtle)]"}`,children:[ie(N)," ",e.jsxs("span",{className:"opacity-60",children:["(",P,")"]})]},N)})]}),e.jsxs("div",{className:"mb-3 flex items-start gap-2 px-3 py-2 rounded-lg bg-indigo-50 border border-indigo-100 text-xs text-indigo-700",children:[e.jsx(Vs,{size:14,className:"shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("span",{children:s("guard.codeLevelConfigTip")}),e.jsx("span",{className:"ml-1 font-mono text-[11px] text-indigo-500",children:s("guard.codeLevelConfigPath")})]})]}),e.jsx("div",{className:"bg-[var(--bg-surface)] border border-[var(--border-default)] rounded-xl overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-[var(--bg-subtle)] border-b border-[var(--border-default)]",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left py-2 px-4 font-medium text-[var(--fg-secondary)]",children:s("guard.ruleId")}),e.jsx("th",{className:"text-left py-2 px-4 font-medium text-[var(--fg-secondary)] w-20",children:s("guard.severity")}),e.jsx("th",{className:"text-left py-2 px-4 font-medium text-[var(--fg-secondary)]",children:s("guard.message")}),e.jsx("th",{className:"text-left py-2 px-4 font-medium text-[var(--fg-secondary)] w-28",children:s("guard.languagesLabel")}),e.jsx("th",{className:"text-left py-2 px-4 font-medium text-[var(--fg-secondary)] w-20",children:s("guard.category")})]})}),e.jsx("tbody",{children:w.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:5,className:"py-4 px-4 text-[var(--fg-secondary)] text-center",children:F.length===0?s("common.noData"):s("guard.noMatchingRules")})}):w.map(([N,P])=>e.jsxs("tr",{className:"border-b border-[var(--border-default)] last:border-0 hover:bg-[var(--bg-subtle)]",children:[e.jsx("td",{className:"py-2 px-4 font-mono text-xs text-[var(--fg-primary)]",children:N}),e.jsx("td",{className:"py-2 px-4",children:e.jsx("span",{className:`text-xs font-medium px-1.5 py-0.5 rounded ${P.severity==="error"?"bg-red-100 text-red-700":P.severity==="info"?"bg-blue-100 text-blue-700":"bg-amber-100 text-amber-700"}`,children:P.severity})}),e.jsxs("td",{className:"py-2 px-4 text-[var(--fg-primary)]",children:[Ne(N,P.message),P.fixSuggestion&&e.jsx("span",{className:"ml-1.5 text-xs text-emerald-600",title:fe(N,P.fixSuggestion),children:"💡"})]}),e.jsx("td",{className:"py-2 px-4",children:e.jsx("div",{className:"flex flex-wrap gap-1",children:(P.languages||[]).map(U=>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:ie(U)},U))})}),e.jsx("td",{className:"py-2 px-4 text-xs text-[var(--fg-secondary)]",children:ge(P.category)})]},N))})]})})]}),e.jsxs("section",{children:[e.jsx("h3",{className:"text-sm font-semibold text-[var(--fg-primary)] mb-3",children:s("guard.violationRecords",{runs:o.length,count:k})}),o.length===0?e.jsx("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-xl py-12 text-center text-[var(--fg-secondary)]",children:s("guard.noViolations")}):e.jsx("div",{className:"space-y-2",children:o.map(N=>{const P=c===N.id,U=N.violations.length>0;return e.jsxs("div",{className:"bg-[var(--bg-surface)] border border-[var(--border-default)] rounded-xl overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>x(P?null:N.id),className:"w-full flex items-center gap-2 py-3 px-4 text-left hover:bg-[var(--bg-subtle)] transition-colors",children:[P?e.jsx(Rt,{size:K.md}):e.jsx(rt,{size:K.md}),e.jsx("span",{className:"font-mono text-sm text-[var(--fg-primary)]",children:N.filePath}),e.jsx("span",{className:"text-xs text-[var(--fg-muted)]",children:new Date(N.triggeredAt).toLocaleString()}),U?e.jsxs("span",{className:"ml-auto flex items-center gap-1 text-amber-600 text-xs font-medium",children:[e.jsx(Bt,{size:K.sm})," ",s("guard.totalViolations",{count:N.violations.length})]}):e.jsx("span",{className:"ml-auto text-[var(--fg-muted)] text-xs",children:s("guard.noViolations")})]}),P&&e.jsx("div",{className:"border-t border-[var(--border-default)] bg-[var(--bg-subtle)] p-4",children:N.violations.length===0?e.jsx("p",{className:"text-sm text-[var(--fg-secondary)]",children:s("guard.noViolations")}):e.jsx("ul",{className:"space-y-2",children:N.violations.map((Q,ue)=>{var ke;const ce=a[Q.ruleId];return e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[Q.severity==="error"?e.jsx(Xt,{size:K.md,className:"text-red-500 shrink-0 mt-0.5"}):e.jsx(Bt,{size:K.md,className:"text-amber-500 shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsxs("div",{children:[e.jsxs("span",{className:"font-mono text-xs text-[var(--fg-secondary)]",children:["[",Q.ruleId,"] ",Q.filePath?`${Q.filePath}:${Q.line}`:`L${Q.line}`]}),Q.dimension&&e.jsx("span",{className:"ml-1.5 text-xs px-1.5 py-0.5 rounded bg-[var(--bg-subtle)] text-[var(--fg-secondary)]",children:Q.dimension==="file"?s("guard.dimFile"):Q.dimension==="target"?s("guard.dimTarget"):s("guard.dimProject")}),e.jsx("span",{className:"text-[var(--fg-primary)] ml-2",children:Ne(Q.ruleId,Q.message)})]}),Q.snippet&&e.jsx("pre",{className:"text-xs text-[var(--fg-secondary)] bg-[var(--bg-subtle)] p-2 rounded overflow-x-auto",children:Q.snippet}),ce&&(ce.rationale||((ke=ce.fixSuggestions)==null?void 0:ke.length)||ce.sourceRecipe||ce.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:[ce.rationale&&e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx(Qe,{size:12,className:"text-blue-500 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsxs("span",{className:"font-bold text-blue-700",children:[s("guard.rationale"),":"]}),e.jsx("span",{className:"text-[var(--fg-secondary)]",children:ce.rationale})]})]}),ce.fixSuggestions&&ce.fixSuggestions.length>0&&e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx(vr,{size:12,className:"text-emerald-500 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsxs("span",{className:"font-bold text-emerald-700",children:[s("guard.fixSuggestion"),":"]}),e.jsx("ul",{className:"mt-0.5 space-y-0.5 text-[var(--fg-secondary)]",children:ce.fixSuggestions.map((Le,Ie)=>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:Le}),e.jsx("button",{className:"ml-1 text-blue-500 hover:text-blue-700",title:s("guard.copyFixSuggestion"),onClick:()=>navigator.clipboard.writeText(Le),children:"⎘"})]},Ie))})]})]}),ce.sourceRecipe&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ra,{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:ce.sourceRecipe})]}),!ce.rationale&&ce.note&&e.jsxs("div",{className:"text-[var(--fg-secondary)] italic",children:[s("guard.noteLabel"),":",ce.note]})]})]})]},ue)})})})]},N.id)})})]})]})]})},La=()=>Math.random().toString(36).substring(2,10),bi=({d:t})=>{const{t:s}=Me();return e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-2.5 py-1 bg-[var(--bg-subtle)] border-b border-[var(--border-default)] flex items-center gap-1.5",children:[e.jsx(pr,{size:10,className:"text-emerald-500"}),e.jsx("span",{className:"text-[10px] font-bold text-[var(--fg-secondary)]",children:t.label})]}),e.jsxs("div",{className:"p-2.5 bg-red-50/30 border-b border-[var(--border-default)]",children:[e.jsx("div",{className:"text-[9px] font-bold text-red-400 mb-0.5 uppercase",children:s("aiChat.diffBefore")}),e.jsx("pre",{className:"text-[11px] text-[var(--fg-secondary)] whitespace-pre-wrap break-words max-h-48 overflow-auto font-mono leading-relaxed scrollbar-light",children:t.before||e.jsx("span",{className:"italic text-[var(--fg-muted)]",children:s("aiChat.diffEmpty")})})]}),e.jsxs("div",{className:"p-2.5 bg-emerald-50/30",children:[e.jsx("div",{className:"text-[9px] font-bold text-emerald-500 mb-0.5 uppercase",children:s("aiChat.diffAfter")}),e.jsx("pre",{className:"text-[11px] text-[var(--fg-primary)] whitespace-pre-wrap break-words max-h-48 overflow-auto font-mono leading-relaxed scrollbar-light",children:t.after})]})]})};function vi(t,s){const a=new Date(t),o=new Date().getTime()-a.getTime(),n=Math.floor(o/6e4);if(n<1)return s("aiChat.timeJustNow");if(n<60)return s("aiChat.timeMinutesAgo",{n});const d=Math.floor(n/60);if(d<24)return s("aiChat.timeHoursAgo",{n:d});const u=Math.floor(d/24);return u<7?s("aiChat.timeDaysAgo",{n:u}):a.toLocaleDateString("zh-CN",{month:"short",day:"numeric"})}const yi=()=>{const{t,lang:s}=Me(),{close:a,isOpen:r}=xs(),[o,n]=l.useState([]),[d,u]=l.useState(!1),c=l.useRef([]),x=l.useRef(null),v=Ar(),{topics:g,activeTopicId:m,activeTopic:i,createTopic:f,deleteTopic:j,saveTopic:C,switchTopic:I}=v,D=l.useRef(null),$=l.useRef(null),[O,T]=l.useState(""),[Z,W]=l.useState(!1),M=l.useRef(!1);l.useEffect(()=>{r&&a()},[]),l.useEffect(()=>{var h;(h=D.current)==null||h.scrollIntoView({behavior:"smooth"})},[o,d]),l.useEffect(()=>{setTimeout(()=>{var h;return(h=$.current)==null?void 0:h.focus()},200)},[]),l.useEffect(()=>{M.current||m&&o.length>0&&C(m,o)},[o,m,C]);const F=l.useCallback(()=>{M.current=!0,f(),n([]),c.current=[],setTimeout(()=>{M.current=!1},50)},[f,n,c]),k=l.useCallback(h=>{if(h===m)return;M.current=!0,I(h);const L=v.getTopic(h);L?(n(L.messages),c.current=L.messages.filter(ie=>ie.role==="user"||ie.role==="assistant").map(ie=>({role:ie.role==="assistant"?"model":ie.role,content:ie.content}))):(n([]),c.current=[]),setTimeout(()=>{M.current=!1},50)},[m,I,v,n,c]),E=l.useCallback((h,L)=>{h.stopPropagation(),j(L),L===m&&(M.current=!0,n([]),c.current=[],setTimeout(()=>{M.current=!1},50))},[j,m,n,c]),B=l.useCallback(async()=>{const h=O.trim();if(!h||d)return;let L=m;L||(M.current=!0,L=f(),setTimeout(()=>{M.current=!1},50)),T(""),n(ge=>[...ge,{id:La(),role:"user",content:h,timestamp:Date.now()}]),u(!0);const ie=La();n(ge=>[...ge,{id:ie,role:"assistant",content:`🔄 ${t("aiChat.thinking")}`,timestamp:Date.now()}]),c.current.push({role:"user",content:h});const Y=new AbortController;x.current=Y;try{const{onEvent:ge,getState:Ne}=Dr(ie,n,t),w=(await ne.chatStream(h,c.current,N=>{ge(N)},Y.signal,s)).text||Ne().answerText;c.current.push({role:"model",content:w}),n(N=>N.map(P=>P.id===ie?{...P,content:w}:P))}catch(ge){if(ge.name==="AbortError"){const Ne=t("aiChat.cancelled");n(fe=>fe.map(w=>w.id===ie?{...w,content:Ne}:w))}else n(Ne=>Ne.map(fe=>fe.id===ie?{...fe,content:t("aiChat.requestFailed",{error:ge.message})}:fe))}finally{x.current=null}u(!1)},[O,d,m,f,t,s]),b=l.useCallback(h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),B())},[B]);return e.jsxs("div",{className:"flex-1 flex h-full bg-[var(--bg-subtle)]",children:[e.jsx("div",{className:`${Z?"w-10":"w-64"} shrink-0 bg-[var(--bg-surface)] border-r border-[var(--border-default)] flex flex-col transition-all duration-200`,children:Z?e.jsxs("div",{className:"flex flex-col items-center py-3 gap-2",children:[e.jsx("button",{onClick:()=>W(!1),className:"p-1.5 hover:bg-[var(--bg-subtle)] rounded-lg transition-colors text-[var(--fg-muted)] hover:text-[var(--fg-secondary)]",title:t("aiChat.expandTopics"),children:e.jsx(rt,{size:16})}),e.jsx("button",{onClick:F,className:"p-1.5 hover:bg-[var(--accent-subtle)] rounded-lg transition-colors text-blue-500",title:t("aiChat.newTopic"),children:e.jsx(kt,{size:16})})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"px-3 py-2.5 border-b border-[var(--border-default)] flex items-center justify-between shrink-0",children:[e.jsx("span",{className:"text-xs font-bold text-[var(--fg-secondary)] uppercase tracking-wider",children:t("aiChat.topicRecords")}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx("button",{onClick:F,className:"p-1.5 hover:bg-[var(--accent-subtle)] rounded-lg transition-colors text-[var(--fg-muted)] hover:text-blue-600",title:t("aiChat.newTopic"),children:e.jsx(kt,{size:14})}),e.jsx("button",{onClick:()=>W(!0),className:"p-1.5 hover:bg-[var(--bg-subtle)] rounded-lg transition-colors text-[var(--fg-muted)] hover:text-[var(--fg-secondary)]",title:t("common.collapse"),children:e.jsx(aa,{size:14})})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto scrollbar-light",children:g.length===0?e.jsxs("div",{className:"px-4 py-8 text-center",children:[e.jsx(It,{size:24,className:"text-[var(--fg-muted)] mx-auto mb-2"}),e.jsx("p",{className:"text-xs text-[var(--fg-muted)]",children:t("aiChat.noHistory")}),e.jsx("p",{className:"text-[10px] text-[var(--fg-muted)] mt-1",children:t("aiChat.autoSaveHint")})]}):e.jsx("div",{className:"py-1",children:g.map(h=>{const L=h.id===m,ie=h.messages.filter(Y=>Y.role==="user").length;return e.jsx("div",{onClick:()=>k(h.id),className:`group mx-1.5 mb-0.5 px-3 py-2 rounded-lg cursor-pointer transition-colors ${L?"bg-[var(--accent-subtle)] border border-blue-200":"hover:bg-[var(--bg-subtle)] border border-transparent"}`,children:e.jsxs("div",{className:"flex items-start justify-between gap-1.5",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`text-xs font-medium truncate leading-snug ${L?"text-blue-700":"text-[var(--fg-primary)]"}`,children:h.title}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)] flex items-center gap-0.5",children:[e.jsx(it,{size:9}),vi(h.updatedAt,t)]}),ie>0&&e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)]",children:t("aiChat.messageCount",{n:ie})})]})]}),e.jsx("button",{onClick:Y=>E(Y,h.id),className:`p-1 rounded transition-colors shrink-0 ${L?"text-blue-400 hover:text-red-500 hover:bg-red-50":"text-transparent group-hover:text-[var(--fg-muted)] hover:!text-red-500 hover:!bg-red-50"}`,title:t("aiChat.deleteTopic"),children:e.jsx(ot,{size:12})})]})},h.id)})})}),g.length>0&&e.jsx("div",{className:"px-3 py-2 border-t border-[var(--border-default)] shrink-0",children:e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)]",children:t("aiChat.topicCount",{count:g.length})})})]})}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsxs("div",{className:"px-6 py-3 border-b border-[var(--border-default)] bg-[var(--bg-surface)] flex items-center justify-between shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-9 h-9 rounded-xl bg-gradient-to-br from-blue-50 to-indigo-50 border border-blue-100 flex items-center justify-center",children:e.jsx(It,{className:"text-blue-600",size:18})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm font-bold text-[var(--fg-primary)]",children:i?i.title:"AI Chat"}),e.jsx("p",{className:"text-[11px] text-[var(--fg-muted)]",children:t("aiChat.askAnything")})]})]}),o.length>0&&e.jsxs("button",{onClick:F,className:"flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-[var(--fg-secondary)] hover:text-blue-600 hover:bg-[var(--accent-subtle)] rounded-lg transition-colors border border-[var(--border-default)] hover:border-blue-200",children:[e.jsx(kt,{size:14}),t("aiChat.newTopic")]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto min-h-0 scrollbar-light",children:e.jsxs("div",{className:"max-w-3xl mx-auto p-6 space-y-4",children:[o.length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-50 border border-blue-100 flex items-center justify-center mb-4",children:e.jsx(Je,{className:"text-blue-500",size:28})}),e.jsx("h3",{className:"text-base font-bold text-[var(--fg-primary)] mb-2",children:t("aiChat.startChat")}),e.jsx("p",{className:"text-sm text-[var(--fg-muted)] max-w-md leading-relaxed mb-5",children:t("aiChat.emptyDescLong")}),e.jsx("div",{className:"flex flex-wrap gap-2 justify-center",children:[{key:"analyzeArch",label:t("aiChat.quickPrompts.analyzeArch")},{key:"findDuplicates",label:t("aiChat.quickPrompts.findDuplicates")},{key:"suggestOptimize",label:t("aiChat.quickPrompts.suggestOptimize")},{key:"summarize",label:t("aiChat.quickPromptSummarize")}].map(h=>e.jsx("button",{onClick:()=>{var L;T(h.label),(L=$.current)==null||L.focus()},className:"text-xs px-3.5 py-2 rounded-lg bg-[var(--bg-surface)] border border-[var(--border-default)] text-[var(--fg-secondary)] hover:bg-[var(--accent-subtle)] hover:text-blue-700 hover:border-blue-200 transition-colors shadow-sm",children:h.label},h.key))})]}),o.map(h=>e.jsx("div",{className:`flex ${h.role==="user"?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[80%] ${h.role==="user"?"bg-[var(--accent-subtle)] text-[var(--fg-primary)] rounded-2xl rounded-tr-md px-4 py-2.5":h.role==="system"?"bg-[var(--bg-subtle)] border border-[var(--border-default)] text-[var(--fg-secondary)] rounded-2xl px-4 py-2.5 w-full":"bg-[var(--bg-surface)] border border-[var(--border-default)] rounded-2xl rounded-tl-md px-4 py-3 shadow-sm w-full"}`,children:[h.role==="assistant"&&e.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[e.jsx(us,{size:13,className:"text-blue-500"}),e.jsx("span",{className:"text-[11px] font-bold text-blue-600",children:t("aiChat.aiAssistant")})]}),h.role==="assistant"&&!h.diff?e.jsx(Et,{content:h.content,className:"text-sm text-[var(--fg-primary)]"}):e.jsx("p",{className:`text-sm leading-relaxed whitespace-pre-wrap ${h.role==="user"?"":"text-[var(--fg-secondary)]"}`,children:h.content}),h.diff&&h.diff.length>0&&e.jsx("div",{className:"space-y-2 mt-2",children:h.diff.map(L=>e.jsx(bi,{d:L},L.field))})]})},h.id)),d&&e.jsx("div",{className:"flex justify-start",children:e.jsx("div",{className:"bg-[var(--bg-surface)] border border-[var(--border-default)] rounded-2xl rounded-tl-md px-4 py-3 shadow-sm",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pe,{size:14,className:"animate-spin text-blue-500"}),e.jsx("span",{className:"text-sm text-[var(--fg-secondary)]",children:t("aiChat.thinking")}),x.current&&e.jsx("button",{onClick:()=>{var h;return(h=x.current)==null?void 0:h.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:D})]})}),e.jsx("div",{className:"border-t border-[var(--border-default)] bg-[var(--bg-surface)] shrink-0",children:e.jsxs("div",{className:"max-w-3xl mx-auto px-6 py-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx("textarea",{ref:$,value:O,onChange:h=>T(h.target.value),onKeyDown:b,placeholder:t("aiChat.inputPlaceholder"),rows:2,className:"flex-1 px-4 py-2.5 text-sm border border-[var(--border-default)] rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-200 focus:border-blue-400 resize-none placeholder:text-[var(--fg-muted)]",disabled:d}),e.jsx("button",{onClick:B,disabled:!O.trim()||d,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(sa,{size:16})})]}),e.jsx("p",{className:"text-[10px] text-[var(--fg-muted)] mt-1.5",children:t("aiChat.inputHint")})]})})]})]})},ji=28,wi=22,Ni=50,ki=11,Ci=10,Nt={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"},Si={depends_on:"依赖",requires:"需要",extends:"扩展",implements:"实现",inherits:"继承",enforces:"约束",related:"关联",conflicts:"冲突",calls:"调用",prerequisite:"前置",data_flow_to:"数据流",references:"引用",alternative:"替代",deprecated_by:"废弃",solves:"解决"},Ks=[{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"}],Ai=[{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 _t(t){return Math.min(Ni,Math.max(wi,ji+t*2))}function Ma(t,s){return t.length<=s?t:t.substring(0,s-1)+"…"}function Di(t,s,a,r){const o=new Map;for(const v of t)o.set(v.fromId,(o.get(v.fromId)||0)+1),o.set(v.toId,(o.get(v.toId)||0)+1);const n=[...o.keys()],d=[...new Set(n.map(v=>r[v]||"general"))].sort(),u=new Map,c=Math.ceil(Math.sqrt(d.length)),x=400;return d.forEach((v,g)=>{const m=g%c,i=Math.floor(g/c);u.set(v,{x:450+(m-(c-1)/2)*x,y:350+(i-(Math.ceil(d.length/c)-1)/2)*x})}),n.map(v=>{const g=r[v]||"general",m=u.get(g)||{x:450,y:350},i=Math.random()*2*Math.PI,f=40+Math.random()*80;return{id:v,label:s[v]||v,type:a[v]||"recipe",group:g,x:m.x+f*Math.cos(i),y:m.y+f*Math.sin(i),vx:0,vy:0,degree:o.get(v)||1}})}function Ii(t,s,a=200){const r=t.map(d=>({...d})),o=new Map(r.map(d=>[d.id,d]));function n(){const d=new Map;for(const u of r){const c=d.get(u.group);c?(c.x+=u.x,c.y+=u.y,c.count++):d.set(u.group,{x:u.x,y:u.y,count:1})}for(const[,u]of d)u.x/=u.count,u.y/=u.count;return d}for(let d=0;d<a;d++){const u=1-d/a,c=18e3*u,x=.015,v=.8,g=n();for(let i=0;i<r.length;i++)for(let f=i+1;f<r.length;f++){const j=r[i],C=r[f];let I=C.x-j.x,D=C.y-j.y,$=Math.sqrt(I*I+D*D)||1;const O=_t(j.degree)+_t(C.degree)+60,T=Math.max($,1),Z=j.group===C.group?.6:1.4,W=c*Z/(T*T),M=$<O?(O-$)*.5:0,F=W+M,k=I/T*F,E=D/T*F;j.vx-=k,j.vy-=E,C.vx+=k,C.vy+=E}for(const i of s){const f=o.get(i.fromId),j=o.get(i.toId);if(!f||!j)continue;let C=j.x-f.x,I=j.y-f.y,D=Math.sqrt(C*C+I*I)||1;const $=f.group===j.group?140:280,O=x*(D-$),T=C/D*O,Z=I/D*O;f.vx+=T,f.vy+=Z,j.vx-=T,j.vy-=Z}const m=.008*u;for(const i of r){const f=g.get(i.group);f&&(i.vx+=(f.x-i.x)*m,i.vy+=(f.y-i.y)*m)}for(const i of r)i.vx*=v,i.vy*=v,i.x+=i.vx,i.y+=i.vy}return r}function Ri(t,s,a,r,o,n,d=0){const u=a-t,c=r-s,x=Math.sqrt(u*u+c*c)||1,v=u/x,g=c/x,m=t+v*o,i=s+g*o,f=a-v*n,j=r-g*n;if(d===0)return`M${m},${i}L${f},${j}`;const C=(m+f)/2+-g*d,I=(i+j)/2+v*d;return`M${m},${i}Q${C},${I},${f},${j}`}const Ti=()=>{const{t}=Me(),{isDark:s}=Fs(),a=s?Ai:Ks,r=p=>{const z={depends_on:"knowledgeGraph.relationDependsOn",requires:"knowledgeGraph.relationRequires",extends:"knowledgeGraph.relationExtends",implements:"knowledgeGraph.relationImplements",inherits:"knowledgeGraph.relationInherits",enforces:"knowledgeGraph.relationEnforces",related:"knowledgeGraph.relationAssociates",conflicts:"knowledgeGraph.relationConflicts",calls:"knowledgeGraph.relationCalls",prerequisite:"knowledgeGraph.relationPrerequisite",data_flow_to:"knowledgeGraph.relationDataFlow",references:"knowledgeGraph.relationReferences",alternative:"knowledgeGraph.relationAlternative",deprecated_by:"knowledgeGraph.relationDeprecatedBy",solves:"knowledgeGraph.relationSolves"};return z[p]?t(z[p]):Si[p]||p},[o,n]=l.useState([]),[d,u]=l.useState({}),[c,x]=l.useState({}),[v,g]=l.useState({}),[m,i]=l.useState(null),[f,j]=l.useState(!0),[C,I]=l.useState(null),[D,$]=l.useState(null),[O,T]=l.useState(null),[Z,W]=l.useState(null),[M,F]=l.useState(!1),[k,E]=l.useState(null),[B,b]=l.useState(!1),[h,L]=l.useState(1),[ie,Y]=l.useState({x:0,y:0}),ge=l.useRef(null),Ne=l.useRef(null),fe=l.useRef(!1),w=l.useRef({x:0,y:0}),N=async()=>{var p,z;j(!0),I(null);try{const[G,A]=await Promise.all([ne.getKnowledgeGraph(),ne.getGraphStats()]);n(G.edges||[]),u(G.nodeLabels||{}),x(G.nodeTypes||{}),g(G.nodeCategories||{}),i(A)}catch(G){I(((z=(p=G.response)==null?void 0:p.data)==null?void 0:z.error)||G.message||t("knowledgeGraph.loadFailed"))}finally{j(!1)}};l.useEffect(()=>{N()},[]),l.useEffect(()=>{ne.getDiscoverRelationsStatus().then(p=>{p.status==="running"&&(F(!0),E(t("knowledgeGraph.discoverAnalyzing",{elapsed:p.elapsed??0})))}).catch(()=>{})},[]),l.useEffect(()=>{if(!M)return;let p=0;const z=240,G=setInterval(async()=>{if(p++,p>z){clearInterval(G),F(!1),b(!0),E(t("knowledgeGraph.discoverPollTimeout"));return}try{const A=await ne.getDiscoverRelationsStatus();if(A.status==="done"){F(!1);const _=A.discovered??0,J=A.totalPairs??0,ae=A.batchErrors??0;if(_===0&&ae===0)b(!1),E(t("knowledgeGraph.discoverNoResults",{pairs:J}));else if(_===0&&ae>0)b(!0),E(t("knowledgeGraph.discoverBatchErrors",{errors:ae}));else{b(!1);const be=ae>0?t("knowledgeGraph.discoverBatchFailed",{count:ae}):"";E(t("knowledgeGraph.discoverSuccess",{count:_,pairs:J,failMsg:be}))}N()}else if(A.status==="error"){F(!1),b(!0);const _=A.error||t("knowledgeGraph.unknownError");_.includes("AI Provider")||_.includes("API Key")?E(t("knowledgeGraph.discoverAiNotConfigured",{error:_})):_.includes("超时")||_.includes("timeout")?E(t("knowledgeGraph.discoverTimeout",{error:_})):E(t("knowledgeGraph.discoverFailed",{error:_}))}else A.status==="running"&&E(t("knowledgeGraph.discoverAnalyzing",{elapsed:A.elapsed??0}))}catch{}},3e3);return()=>clearInterval(G)},[M]);const P=l.useCallback(async()=>{var p,z,G;E(null),b(!1);try{const A=await ne.discoverRelations();if(A.status==="empty"){E(A.message||t("knowledgeGraph.discoverInsufficientRecipes"));return}if(A.status==="timeout"){b(!0),E(A.error||t("knowledgeGraph.discoverPreviousTimeout"));return}if(A.status==="running"){F(!0),E(t("knowledgeGraph.discoverRunning"));return}F(!0),E(t("knowledgeGraph.discoverStarted"))}catch(A){b(!0);const _=((G=(z=(p=A==null?void 0:A.response)==null?void 0:p.data)==null?void 0:z.error)==null?void 0:G.message)||A.message||t("knowledgeGraph.unknownError");_.includes("ChatAgent")||_.includes("AI Provider")?E(t("knowledgeGraph.discoverAiUnavailable",{error:_})):E(t("knowledgeGraph.discoverStartFailed",{error:_}))}},[t]),U=l.useMemo(()=>{if(o.length===0)return[];const p=Di(o,d,c,v);return Ii(p,o)},[o,d,c,v]),Q=l.useMemo(()=>{const p=new Map;for(const A of U){const _=p.get(A.group)||[];_.push(A),p.set(A.group,_)}const z=[],G=[...p.keys()].sort();for(const A of G){const _=p.get(A);if(_.length===0)continue;let J=0,ae=0;for(const xe of _)J+=xe.x,ae+=xe.y;J/=_.length,ae/=_.length;let be=0,X=0;for(const xe of _){const he=_t(xe.degree);be=Math.max(be,Math.abs(xe.x-J)+he+35),X=Math.max(X,Math.abs(xe.y-ae)+he+35)}z.push({group:A,cx:J,cy:ae,rx:Math.max(be,60),ry:Math.max(X,60),count:_.length})}return z},[U]),ue=l.useMemo(()=>{const p=[...new Set(U.map(G=>G.group))].sort(),z={};return p.forEach((G,A)=>{z[G]=a[A%a.length]}),z},[U,a]),ce=l.useMemo(()=>{if(U.length===0)return{x:0,y:0,w:900,h:700};let p=1/0,z=1/0,G=-1/0,A=-1/0;for(const _ of U){const J=_t(_.degree);p=Math.min(p,_.x-J-80),z=Math.min(z,_.y-J-40),G=Math.max(G,_.x+J+80),A=Math.max(A,_.y+J+40)}return{x:p,y:z,w:G-p,h:A-z}},[U]),ke=l.useMemo(()=>new Map(U.map(p=>[p.id,p])),[U]),{connectedEdgeIds:Le,connectedNodeIds:Ie}=l.useMemo(()=>{const p=D||O;if(!p)return{connectedEdgeIds:new Set,connectedNodeIds:new Set};const z=new Set,G=new Set([p]);for(const A of o)(A.fromId===p||A.toId===p)&&(z.add(A.id),G.add(A.fromId),G.add(A.toId));return{connectedEdgeIds:z,connectedNodeIds:G}},[D,O,o]),Be=l.useMemo(()=>{const p=new Map,z=new Map;for(const A of o){const _=[A.fromId,A.toId].sort().join("|"),J=p.get(_)||0;z.set(A.id,J),p.set(_,J+1)}const G=new Map;for(const A of o){const _=[A.fromId,A.toId].sort().join("|"),J=p.get(_)||1;if(J<=1){G.set(A.id,0);continue}const ae=z.get(A.id)||0;G.set(A.id,(ae-(J-1)/2)*40)}return G},[o]),[H,S]=l.useState(new Set);l.useEffect(()=>{S(new Set(o.map(p=>p.relation)))},[o]);const se=l.useMemo(()=>o.filter(p=>H.has(p.relation)),[o,H]),we=p=>{S(z=>{const G=new Set(z);return G.has(p)?G.delete(p):G.add(p),G})},V=l.useCallback(p=>{p.button===0&&(fe.current=!0,w.current={x:p.clientX,y:p.clientY})},[]),ye=l.useCallback(p=>{if(!fe.current)return;const z=p.clientX-w.current.x,G=p.clientY-w.current.y;w.current={x:p.clientX,y:p.clientY},Y(A=>({x:A.x+z,y:A.y+G}))},[]),Re=l.useCallback(()=>{fe.current=!1},[]),je=l.useCallback(p=>{p.preventDefault();const z=p.deltaY>0?-.1:.1;L(G=>Math.min(3,Math.max(.2,G+z)))},[]),pe=p=>`kg-arrow-${p.replace(/[^a-z_]/g,"")}`;if(f)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:N,className:"px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors",children:t("knowledgeGraph.retry")})]});if(o.length===0)return e.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-[var(--fg-secondary)]",children:[e.jsx(Rs,{size:48,className:"text-[var(--fg-muted)]"}),e.jsx("p",{className:"text-lg font-medium",children:t("knowledgeGraph.empty")}),e.jsx("p",{className:"text-sm text-center max-w-md",children:t("knowledgeGraph.emptyDesc")}),k&&e.jsx("p",{className:`text-sm ${B?"text-red-500":"text-green-600"}`,children:k}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:P,disabled:M,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:M?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(Je,{size:K.sm})," ",t("knowledgeGraph.discoverRelations")]})}),e.jsxs("button",{onClick:N,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(jt,{size:K.sm})," ",t("knowledgeGraph.refresh")]})]})]});const _e=[...new Set(o.map(p=>p.relation))].sort(),y=!!(D||O);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(Rs,{size:K.lg,className:"text-blue-600"}),e.jsx("h2",{className:"text-lg xl:text-xl font-bold text-[var(--fg-primary)]",children:t("knowledgeGraph.title")}),m&&e.jsx("span",{className:"text-xs px-2 py-1 rounded-full text-[var(--fg-secondary)] bg-[var(--bg-subtle)]",children:t("knowledgeGraph.statsLabel",{nodes:U.length,edges:m.totalEdges})})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{onClick:()=>L(p=>Math.min(p+.2,3)),className:"p-1.5 rounded-lg transition-colors bg-[var(--bg-subtle)] hover:bg-[var(--border-default)] text-[var(--fg-secondary)]",title:t("knowledgeGraph.zoomIn"),children:e.jsx(_n,{size:K.sm})}),e.jsx("button",{onClick:()=>L(p=>Math.max(p-.2,.2)),className:"p-1.5 rounded-lg transition-colors bg-[var(--bg-subtle)] hover:bg-[var(--border-default)] text-[var(--fg-secondary)]",title:t("knowledgeGraph.zoomOut"),children:e.jsx(Bn,{size:K.sm})}),e.jsx("button",{onClick:()=>{L(1),Y({x:0,y:0})},className:"p-1.5 rounded-lg transition-colors bg-[var(--bg-subtle)] hover:bg-[var(--border-default)] text-[var(--fg-secondary)]",title:t("knowledgeGraph.resetView"),children:e.jsx(xr,{size:K.sm})}),e.jsx("button",{onClick:N,className:"p-1.5 rounded-lg transition-colors bg-[var(--bg-subtle)] hover:bg-[var(--border-default)] text-[var(--fg-secondary)]",title:t("knowledgeGraph.refresh"),children:e.jsx(jt,{size:K.sm})}),e.jsx("button",{onClick:P,disabled:M,className:"flex items-center gap-1 px-2.5 py-1 rounded-lg text-xs font-medium transition-colors disabled:opacity-50 bg-violet-50 hover:bg-violet-100 text-violet-700",title:t("knowledgeGraph.discoverTooltip"),children:M?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(Je,{size:K.sm})," ",t("knowledgeGraph.discoverRelations")]})})]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-3 flex-shrink-0",children:_e.map(p=>{var z;return e.jsxs("button",{onClick:()=>we(p),className:`flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-medium transition-all border ${H.has(p)?"border-transparent shadow-sm":"border-[var(--border-default)] bg-[var(--bg-surface)] text-[var(--fg-muted)] opacity-40"}`,style:H.has(p)?{backgroundColor:(Nt[p]||"#6b7280")+"18",color:Nt[p]||"#6b7280"}:{},children:[e.jsx("span",{className:"w-2 h-2 rounded-full",style:{backgroundColor:Nt[p]||"#6b7280"}}),r(p),((z=m==null?void 0:m.byRelation)==null?void 0:z[p])!=null&&e.jsxs("span",{className:"opacity-60",children:["(",m.byRelation[p],")"]})]},p)})}),e.jsxs("div",{ref:Ne,className:"flex-1 rounded-xl border overflow-hidden relative min-h-0 border-[var(--border-default)] bg-[var(--bg-subtle)]",style:{cursor:fe.current?"grabbing":"grab"},onWheel:je,children:[e.jsxs("svg",{ref:ge,width:"100%",height:"100%",viewBox:`${ce.x} ${ce.y} ${ce.w} ${ce.h}`,onMouseDown:V,onMouseMove:ye,onMouseUp:Re,onMouseLeave:Re,style:{transform:`scale(${h}) translate(${ie.x/h}px, ${ie.y/h}px)`},children:[e.jsxs("defs",{children:[_e.map(p=>e.jsx("marker",{id:pe(p),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:Nt[p]||"#6b7280"})},p)),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:Q.map(p=>{const z=ue[p.group]||Ks[0];return e.jsxs("g",{children:[e.jsx("ellipse",{cx:p.cx,cy:p.cy,rx:p.rx,ry:p.ry,fill:z.bg,stroke:z.border,strokeWidth:1.5,strokeDasharray:"6,4",opacity:.6}),e.jsxs("text",{x:p.cx,y:p.cy-p.ry+14,textAnchor:"middle",fontSize:11,fontWeight:600,fill:z.text,opacity:.8,style:{pointerEvents:"none",userSelect:"none"},children:[p.group||"general"," (",p.count,")"]})]},p.group)})}),e.jsx("g",{children:se.map(p=>{const z=ke.get(p.fromId),G=ke.get(p.toId);if(!z||!G)return null;const A=y?Le.has(p.id):!1,_=Z===p.id,J=y?A?.85:.06:_?.9:.35,ae=_t(z.degree),be=_t(G.degree),X=Be.get(p.id)||0,xe=Ri(z.x,z.y,G.x,G.y,ae,be,X);return e.jsxs("g",{children:[e.jsx("path",{d:xe,fill:"none",stroke:"transparent",strokeWidth:12,onMouseEnter:()=>W(p.id),onMouseLeave:()=>W(null),style:{cursor:"pointer"}}),e.jsx("path",{d:xe,fill:"none",stroke:Nt[p.relation]||"#6b7280",strokeWidth:_||A?2:1.2,opacity:J,markerEnd:`url(#${pe(p.relation)})`,strokeDasharray:p.relation==="related"?"6,3":void 0,style:{transition:"opacity 0.25s, stroke-width 0.15s",pointerEvents:"none"}}),_&&(()=>{const he=(z.x+G.x)/2,Fe=(z.y+G.y)/2;return e.jsxs("g",{children:[e.jsx("rect",{x:he-24,y:Fe-16,width:48,height:18,rx:4,fill:"var(--bg-surface)",stroke:Nt[p.relation]||"#6b7280",strokeWidth:.8,opacity:.95}),e.jsx("text",{x:he,y:Fe-4,textAnchor:"middle",fontSize:9,fontWeight:600,fill:Nt[p.relation]||"#6b7280",children:r(p.relation)})]})})()]},p.id)})}),e.jsx("g",{children:U.map(p=>{const z=_t(p.degree),G=D===p.id,A=y&&Ie.has(p.id),_=G||p.id===O,J=y&&!A,ae=J?.12:1,be=ue[p.group]||Ks[0],X=_?be.border:be.bg,xe=_?be.text:be.border,he=_?"#ffffff":be.text,Fe=_?be.text:"var(--fg-muted)";return e.jsxs("g",{onClick:Oe=>{Oe.stopPropagation(),$(G?null:p.id)},onMouseEnter:()=>T(p.id),onMouseLeave:()=>T(null),style:{cursor:"pointer",transition:"opacity 0.25s"},opacity:ae,filter:_?"url(#kg-glow)":void 0,children:[e.jsx("circle",{cx:p.x,cy:p.y,r:z,fill:X,stroke:xe,strokeWidth:_?2.5:1.5}),e.jsx("text",{x:p.x,y:p.y+4,textAnchor:"middle",fontSize:Math.min(ki,z*.7),fill:he,fontWeight:700,style:{pointerEvents:"none",userSelect:"none"},children:Ma(p.label,4).toUpperCase()}),e.jsx("text",{x:p.x,y:p.y+z+14,textAnchor:"middle",fontSize:Ci,fill:Fe,fontWeight:_?600:400,style:{pointerEvents:"none",userSelect:"none"},children:Ma(p.label,18)}),p.degree>=3&&!J&&e.jsxs("g",{children:[e.jsx("circle",{cx:p.x+z*.7,cy:p.y-z*.7,r:8,fill:"#3b82f6",stroke:"var(--bg-surface)",strokeWidth:1.5}),e.jsx("text",{x:p.x+z*.7,y:p.y-z*.7+3.5,textAnchor:"middle",fontSize:8,fill:"white",fontWeight:700,style:{pointerEvents:"none"},children:p.degree})]})]},p.id)})})]}),D&&e.jsx("button",{className:"absolute top-2 right-2 text-xs px-2 py-1 rounded-md shadow-sm border text-[var(--fg-muted)] hover:text-[var(--fg-secondary)] bg-[var(--bg-surface)] border-[var(--border-default)]",onClick:()=>$(null),children:t("knowledgeGraph.cancelSelection")})]}),D&&e.jsxs("div",{className:"mt-3 p-4 rounded-xl border shadow-sm flex-shrink-0 max-h-48 overflow-y-auto scrollbar-light bg-[var(--bg-surface)] border-[var(--border-default)]",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3 pb-2 border-b border-[var(--border-default)]",children:[e.jsx(Vs,{size:14,className:"text-blue-500"}),e.jsx("h3",{className:"font-semibold text-sm text-[var(--fg-primary)]",children:d[D]||D}),e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)] ml-auto",children:["ID: ",D]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-xs",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-[var(--fg-secondary)] font-medium",children:t("knowledgeGraph.outEdges")}),e.jsxs("ul",{className:"mt-1.5 space-y-1",children:[o.filter(p=>p.fromId===D&&H.has(p.relation)).map(p=>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:Nt[p.relation]||"#6b7280"}}),e.jsx("span",{className:"text-[var(--fg-secondary)]",children:r(p.relation)}),e.jsx("span",{className:"text-[var(--fg-muted)]",children:"→"}),e.jsx("button",{className:"text-blue-600 hover:underline truncate",onClick:()=>$(p.toId),children:d[p.toId]||p.toId.substring(0,16)})]},p.id)),o.filter(p=>p.fromId===D&&H.has(p.relation)).length===0&&e.jsx("li",{className:"text-[var(--fg-muted)]",children:t("knowledgeGraph.none")})]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[var(--fg-secondary)] font-medium",children:t("knowledgeGraph.inEdges")}),e.jsxs("ul",{className:"mt-1.5 space-y-1",children:[o.filter(p=>p.toId===D&&H.has(p.relation)).map(p=>e.jsxs("li",{className:"flex items-center gap-1.5",children:[e.jsx("button",{className:"text-blue-600 hover:underline truncate",onClick:()=>$(p.fromId),children:d[p.fromId]||p.fromId.substring(0,16)}),e.jsx("span",{className:"text-[var(--fg-muted)]",children:"→"}),e.jsx("span",{className:"text-[var(--fg-secondary)]",children:r(p.relation)}),e.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:Nt[p.relation]||"#6b7280"}})]},p.id)),o.filter(p=>p.toId===D&&H.has(p.relation)).length===0&&e.jsx("li",{className:"text-[var(--fg-muted)]",children:t("knowledgeGraph.none")})]})]})]})]})]})};function Ei(){return e.jsxs("div",{className:"space-y-0",children:[e.jsxs("div",{className:"flex items-center gap-4 px-4 py-3 border-b border-[var(--border-default)]",children:[e.jsx(xt,{className:"h-4 w-4 rounded-sm"}),e.jsx(xt,{className:"h-3.5 w-[30%]"}),e.jsx(xt,{className:"h-3.5 w-[12%]"}),e.jsx(xt,{className:"h-3.5 w-[12%]"}),e.jsx(xt,{className:"h-3.5 w-[15%]"}),e.jsx(xt,{className:"h-3.5 w-6"})]}),Array.from({length:8}).map((t,s)=>e.jsxs("div",{className:"flex items-center gap-4 px-4 py-3 border-b border-[var(--border-default)]",children:[e.jsx(xt,{className:"h-4 w-4 rounded-sm"}),e.jsx(xt,{className:"h-3.5 w-[28%]",style:{width:`${24+s%3*8}%`}}),e.jsx(xt,{className:"h-5 w-14 rounded-full"}),e.jsx(xt,{className:"h-5 w-16 rounded-full"}),e.jsx(xt,{className:"h-3.5 w-[12%]"}),e.jsx(xt,{className:"h-5 w-5 rounded"})]},s))]})}const vt={pending:{labelKey:"lifecycle.pending",color:"text-amber-700",bg:"bg-amber-50",border:"border-amber-200",icon:it},active:{labelKey:"lifecycle.active",color:"text-green-700",bg:"bg-green-50",border:"border-green-200",icon:ms},deprecated:{labelKey:"lifecycle.deprecated",color:"text-orange-600",bg:"bg-orange-50",border:"border-orange-200",icon:Js}},as={rule:{labelKey:"kind.rule",color:"text-red-700",bg:"bg-red-50",border:"border-red-200",icon:mt},pattern:{labelKey:"kind.pattern",color:"text-violet-700",bg:"bg-violet-50",border:"border-violet-200",icon:Ut},fact:{labelKey:"kind.fact",color:"text-cyan-700",bg:"bg-cyan-50",border:"border-cyan-200",icon:Qe}},Pi={pending:[{action:"publish",labelKey:"knowledge.actionPublish",color:"text-green-700",bg:"bg-green-50 hover:bg-green-100",icon:ms},{action:"deprecate",labelKey:"knowledge.actionDeprecate",color:"text-orange-700",bg:"bg-orange-50 hover:bg-orange-100",icon:Js,needsReason:!0}],active:[{action:"deprecate",labelKey:"knowledge.actionDeprecate",color:"text-orange-700",bg:"bg-orange-50 hover:bg-orange-100",icon:Js,needsReason:!0}],deprecated:[{action:"reactivate",labelKey:"knowledge.actionReactivate",color:"text-green-700",bg:"bg-green-50 hover:bg-green-100",icon:ur}]};function rs(t,s){if(!t)return"";const a=t<1e12?t*1e3:t,r=new Date(a);if(isNaN(r.getTime())||r.getFullYear()<2e3)return"";const n=Date.now()-a;if(n<0)return r.toLocaleDateString();const d=Math.floor(n/6e4);if(d<1)return s("candidates.timeJustNow");if(d<60)return s("candidates.timeMinutesAgo",{n:d});const u=Math.floor(d/60);if(u<24)return s("candidates.timeHoursAgo",{n:u});const c=Math.floor(u/24);return c<7?s("candidates.timeDaysAgo",{n:c}):r.toLocaleDateString()}function Li(t){return t==null?{ring:"stroke-[var(--border-default)]",text:"text-[var(--fg-muted)]",bg:"bg-[var(--bg-subtle)]",labelKey:""}:t>=.8?{ring:"stroke-emerald-500",text:"text-emerald-700",bg:"bg-emerald-50",labelKey:"candidates.confidenceHighLabel"}:t>=.6?{ring:"stroke-blue-500",text:"text-blue-700",bg:"bg-blue-50",labelKey:"candidates.confidenceMediumLabel"}:t>=.4?{ring:"stroke-amber-500",text:"text-amber-700",bg:"bg-amber-50",labelKey:"candidates.confidenceMediumLowLabel"}:{ring:"stroke-red-500",text:"text-red-700",bg:"bg-red-50",labelKey:"candidates.confidenceLowLabel"}}function Mi(t,s=4){return t?ia(t).split(`
112
+ `).slice(0,s).join(`
113
+ `):""}const Fa={"bootstrap-scan":{labelKey:"knowledge.sourceBootstrap",color:"text-violet-600 bg-violet-50 border-violet-200"},mcp:{labelKey:"knowledge.sourceMcp",color:"text-blue-600 bg-blue-50 border-blue-200"},manual:{labelKey:"knowledge.sourceManual",color:"text-emerald-600 bg-emerald-50 border-emerald-200"},"file-watcher":{labelKey:"knowledge.sourceFileWatcher",color:"text-orange-600 bg-orange-50 border-orange-200"},clipboard:{labelKey:"knowledge.sourceClipboard",color:"text-pink-600 bg-pink-50 border-pink-200"},cli:{labelKey:"knowledge.sourceCli",color:"text-[var(--fg-secondary)] bg-[var(--bg-subtle)] border-[var(--border-default)]"},agent:{labelKey:"knowledge.sourceAgent",color:"text-violet-600 bg-violet-50 border-violet-200"},submit_with_check:{labelKey:"knowledge.sourceSubmitCheck",color:"text-teal-600 bg-teal-50 border-teal-200"}},Fi=({onRefresh:t,idTitleMap:s})=>{const{t:a}=Me(),r=S=>({pending:a("knowledge.lifecyclePending"),active:a("knowledge.lifecycleActive"),deprecated:a("knowledge.lifecycleDeprecated")})[S]||S,o=S=>({publish:a("knowledge.actionPublish"),deprecate:a("knowledge.actionDeprecate"),reactivate:a("knowledge.actionReactivate")})[S]||S,[n,d]=l.useState([]),[u,c]=l.useState(null),[x,v]=l.useState(!0),[g,m]=l.useState(1),[i,f]=l.useState(12),[j,C]=l.useState(0),[I,D]=l.useState(""),[$,O]=l.useState(""),[T,Z]=l.useState(""),[W,M]=l.useState(""),[F,k]=l.useState(""),{isWide:E,toggle:B}=ua(),[b,h]=l.useState(null),[L,ie]=l.useState(!1),[Y,ge]=l.useState(new Set),[Ne,fe]=l.useState(!1),w=l.useRef(!0);l.useEffect(()=>(w.current=!0,()=>{w.current=!1}),[]);const N=l.useCallback(async()=>{var S;v(!0);try{const se=await ne.knowledgeList({page:g,limit:i,lifecycle:I||void 0,kind:$||void 0,category:T||void 0,keyword:W||void 0});w.current&&(d(se.data||[]),C(((S=se.pagination)==null?void 0:S.total)||0))}catch(se){re((se==null?void 0:se.message)||a("knowledge.loadFailed"),{title:a("common.loadFailed"),type:"error"})}finally{w.current&&v(!1)}},[g,i,I,$,T,W]),P=l.useCallback(async()=>{try{const S=await ne.knowledgeStats();w.current&&c(S)}catch{}},[]);l.useEffect(()=>{N()},[N]),l.useEffect(()=>{P()},[P]),l.useEffect(()=>{const S=setTimeout(()=>{M(F),m(1)},300);return()=>clearTimeout(S)},[F]),l.useEffect(()=>{m(1)},[I,$,T]);const U=l.useCallback(()=>{N(),P(),t==null||t()},[N,P,t]),Q=l.useMemo(()=>{const S=new Map;if(s)for(const[se,we]of Object.entries(s))S.set(se,we);for(const se of n)se.id&&se.title&&S.set(se.id,se.title);return S},[n,s]),ue=async(S,se,we)=>{var V,ye,Re,je;ie(!0);try{const pe=await ne.knowledgeLifecycle(S.id,se,we);re(`${S.title} → ${a(((V=vt[pe.lifecycle])==null?void 0:V.labelKey)||"")||pe.lifecycle}`,{title:a("knowledge.operationSuccess")}),d(_e=>_e.map(q=>q.id===S.id?pe:q)),(b==null?void 0:b.id)===S.id&&h(pe),P()}catch(pe){re(((je=(Re=(ye=pe==null?void 0:pe.response)==null?void 0:ye.data)==null?void 0:Re.error)==null?void 0:je.message)||(pe==null?void 0:pe.message)||a("common.operationFailed"),{title:a("common.operationFailed"),type:"error"})}finally{w.current&&ie(!1)}},ce=async S=>{if(confirm(a("knowledge.deleteConfirmMsg",{title:S.title})))try{await ne.knowledgeDelete(S.id),re(a("knowledge.deleteSuccess",{title:S.title}),{title:a("common.delete")}),d(se=>se.filter(we=>we.id!==S.id)),(b==null?void 0:b.id)===S.id&&h(null),P()}catch(se){re((se==null?void 0:se.message)||a("knowledge.deleteFailed"),{title:a("knowledge.deleteFailed"),type:"error"})}},ke=async()=>{if(Y.size!==0){fe(!0);try{const S=await ne.knowledgeBatchPublish([...Y]);re(a("knowledge.batchPublishResult",{success:S.successCount,fail:S.failureCount}),{title:a("knowledge.batchPublish")}),ge(new Set),U()}catch(S){re((S==null?void 0:S.message)||a("knowledge.batchPublishFailed"),{title:a("common.operationFailed"),type:"error"})}finally{fe(!1)}}},Le=async()=>{fe(!0);try{const se=((await ne.knowledgeList({lifecycle:"pending",limit:500})).data||[]).filter(V=>V.autoApprovable).map(V=>V.id);if(se.length===0){re(a("knowledge.noAutoApprovable"),{title:a("knowledge.noPublishable")});return}const we=await ne.knowledgeBatchPublish(se);re(a("knowledge.autoPublishResult",{count:we.successCount}),{title:a("knowledge.batchPublishComplete")}),U()}catch(S){re((S==null?void 0:S.message)||a("knowledge.batchPublishFailed"),{title:a("common.operationFailed"),type:"error"})}finally{fe(!1)}},Ie=S=>{ge(se=>{const we=new Set(se);return we.has(S)?we.delete(S):we.add(S),we})},Be=()=>{Y.size===n.length?ge(new Set):ge(new Set(n.map(S=>S.id)))},H=(S,se)=>{const we=prompt(a("knowledge.deprecateReasonPrompt"));we&&ue(S,se,we)};return e.jsxs("div",{className:"space-y-4 pb-6",children:[u&&e.jsx("div",{className:"grid grid-cols-3 gap-3",children:Object.entries(vt).map(([S,se])=>{const we=u[S]||0,V=se.icon;return e.jsxs("button",{onClick:()=>{D(I===S?"":S)},className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-all text-left ${I===S?`${se.bg} ${se.border} ${se.color} ring-1 ring-current`:"bg-[var(--bg-surface)] border-[var(--border-default)] text-[var(--fg-secondary)] hover:bg-[var(--bg-subtle)]"}`,children:[e.jsx(V,{size:14}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium",children:r(S)}),e.jsx("div",{className:"text-lg font-bold",children:we})]})]},S)})}),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(Ct,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-[var(--fg-muted)]",size:16}),e.jsx("input",{type:"text",placeholder:a("knowledge.searchPlaceholder"),value:F,onChange:S=>k(S.target.value),className:"w-full pl-9 pr-3 py-2 rounded-lg border border-[var(--border-default)] text-sm focus:outline-none focus:ring-2 focus:ring-blue-300"})]}),e.jsx("div",{className:"flex gap-1",children:Object.entries(as).map(([S,se])=>{const we=se.icon;return e.jsxs("button",{onClick:()=>O($===S?"":S),className:`flex items-center gap-1 px-2.5 py-1.5 rounded-md text-xs font-medium border transition-all ${$===S?`${se.bg} ${se.border} ${se.color}`:"bg-[var(--bg-surface)] border-[var(--border-default)] text-[var(--fg-secondary)] hover:bg-[var(--bg-subtle)]"}`,children:[e.jsx(we,{size:12}),a(se.labelKey)]},S)})}),e.jsx(lt,{value:T,onChange:S=>Z(S),options:[{value:"",label:a("knowledge.allCategories")},...["View","Service","Tool","Model","Network","Storage","UI","Utility"].map(S=>({value:S,label:S}))],size:"sm",className:"text-xs"}),e.jsx("button",{onClick:U,className:"p-2 rounded-md text-[var(--fg-muted)] hover:bg-[var(--bg-subtle)]",title:a("common.refresh"),children:e.jsx(jt,{size:16})}),Y.size>0&&e.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[e.jsx("span",{className:"text-xs text-[var(--fg-secondary)]",children:a("knowledge.selectedCount",{count:Y.size})}),e.jsx("button",{onClick:ke,disabled:Ne,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:Ne?e.jsx(Pe,{size:12,className:"animate-spin"}):a("knowledge.batchPublish")}),e.jsx("button",{onClick:()=>ge(new Set),className:"p-1 text-[var(--fg-muted)] hover:text-[var(--fg-primary)]",children:e.jsx(Xe,{size:14})})]}),Y.size===0&&e.jsxs("button",{onClick:Le,disabled:Ne,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:[Ne?e.jsx(Pe,{size:12,className:"animate-spin"}):e.jsx(et,{size:12}),a("knowledge.quickBatchPublish")]})]}),x?e.jsx(Ei,{}):n.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-[var(--fg-muted)]",children:[e.jsx(Qe,{size:48,className:"mb-4 opacity-30"}),e.jsx("p",{className:"text-sm",children:a("knowledge.noResults")}),(W||I||$||T)&&e.jsx("button",{onClick:()=>{k(""),D(""),O(""),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:Y.size===n.length&&n.length>0,onChange:Be,className:"rounded border-[var(--border-default)]"}),e.jsx("span",{className:"text-xs text-[var(--fg-muted)]",children:a("knowledge.selectAll")}),e.jsx("span",{className:"text-xs text-[var(--fg-muted)] ml-auto",children:a("knowledge.totalCount",{count:j})})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:n.map(S=>{var je,pe,_e,q,y,p;const se=vt[S.lifecycle]||vt.pending,we=as[S.kind]||as.pattern,V=se.icon,ye=we.icon,Re=Li((je=S.reasoning)==null?void 0:je.confidence);return e.jsxs("div",{onClick:()=>h(S),className:`group bg-[var(--bg-surface)] rounded-xl border shadow-sm hover:shadow-md cursor-pointer transition-all overflow-hidden ${(b==null?void 0:b.id)===S.id?"ring-2 ring-blue-300 border-blue-200":"border-[var(--border-default)]"}`,children:[e.jsxs("div",{className:"px-4 pt-3 pb-2",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[e.jsx("input",{type:"checkbox",checked:Y.has(S.id),onChange:z=>{z.stopPropagation(),Ie(S.id)},onClick:z=>z.stopPropagation(),className:"rounded border-[var(--border-default)]"}),e.jsxs("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium ${se.bg} ${se.color} ${se.border} border`,children:[e.jsx(V,{size:10}),r(S.lifecycle)]}),e.jsxs("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium ${we.bg} ${we.color} ${we.border} border`,children:[e.jsx(ye,{size:10}),a(we.labelKey)]}),S.category&&e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)]",children:S.category}),e.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded ${Re.bg} ${Re.text}`,children:((pe=S.reasoning)==null?void 0:pe.confidence)!=null?`${Math.round(S.reasoning.confidence*100)}%`:"—"}),S.autoApprovable&&S.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-[var(--fg-primary)] mb-1 break-words leading-snug",children:S.title}),(S.description||((_e=S.content)==null?void 0:_e.rationale))&&e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] line-clamp-2 leading-relaxed",children:S.description||((q=S.content)==null?void 0:q.rationale)||""}),((y=S.content)==null?void 0:y.pattern)&&e.jsx("pre",{className:"mt-1.5 text-[10px] text-[var(--fg-secondary)] bg-[var(--bg-subtle)] rounded p-1.5 line-clamp-3 font-mono overflow-hidden",children:Mi(S.content.pattern,3)})]}),e.jsxs("div",{className:"px-4 py-2 bg-[var(--bg-subtle)] border-t border-[var(--border-default)] flex items-center gap-2",children:[(p=S.tags)==null?void 0:p.slice(0,3).map(z=>e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100",children:z},z)),S.tags&&S.tags.length>3&&e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)]",children:["+",S.tags.length-3]}),e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)] ml-auto",children:[S.trigger&&e.jsx("span",{className:"text-blue-400 mr-2",children:S.trigger}),S.source&&e.jsx("span",{className:"mr-2",children:S.source}),rs(S.updatedAt,a)]})]})]},S.id)})}),e.jsx(pa,{currentPage:g,totalPages:Math.ceil(j/i),onPageChange:m,pageSize:i,onPageSizeChange:S=>{f(S),m(1)},totalItems:j})]}),b&&(()=>{var q,y,p,z,G,A,_,J;const S=vt[b.lifecycle]||vt.pending,se=as[b.kind]||as.pattern,we=gt[b.category||""]||gt.All||{},V=b.reasoning,ye=n.findIndex(ae=>ae.id===b.id),Re=ye>0,je=ye<n.length-1,pe=()=>{Re&&h(n[ye-1])},_e=()=>{je&&h(n[ye+1])};return e.jsxs(Te,{open:!!b,onClose:()=>h(null),size:E?"lg":"md",children:[e.jsxs(Te.Header,{title:b.title,children:[e.jsx(Te.Nav,{currentIndex:ye,total:n.length,onPrev:pe,onNext:_e,hasPrev:Re,hasNext:je}),e.jsxs(Te.HeaderActions,{children:[e.jsx(Te.WidthToggle,{isWide:E,onToggle:B,title:a(E?"knowledge.narrow":"knowledge.widen")}),e.jsx(We,{variant:"danger",size:"icon-sm",onClick:()=>{ce(b),h(null)},children:e.jsx(ot,{size:16})}),e.jsx(Te.CloseButton,{onClose:()=>h(null)})]})]}),e.jsxs(Te.Body,{children:[b.rejectionReason&&e.jsxs("div",{className:"px-6 py-3 border-b border-red-200 bg-red-50/80",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:b.rejectionReason})]}),e.jsx(ma,{badges:(()=>{const ae=[];return ae.push({label:r(b.lifecycle),className:`${S.bg} ${S.color} ${S.border}`,icon:S.icon}),ae.push({label:a(se.labelKey),className:`${se.bg} ${se.color} ${se.border}`,icon:se.icon}),ae.push({label:b.category||"general",className:`font-bold uppercase ${(we==null?void 0:we.bg)||"bg-[var(--bg-subtle)]"} ${(we==null?void 0:we.color)||"text-[var(--fg-muted)]"} ${(we==null?void 0:we.border)||"border-[var(--border-default)]"}`}),b.knowledgeType&&ae.push({label:b.knowledgeType,className:"bg-purple-50 text-purple-700 border-purple-200"}),b.language&&ae.push({label:b.language,className:"uppercase font-bold text-[var(--fg-secondary)] bg-[var(--bg-subtle)] border-[var(--border-default)]"}),b.trigger&&ae.push({label:b.trigger,className:"font-mono font-bold bg-amber-50 text-amber-700 border-amber-200"}),ae})(),metadata:(()=>{const ae=[];return b.scope&&ae.push({icon:qt,iconClass:"text-teal-400",label:a("knowledge.scope"),value:b.scope==="universal"?a("knowledge.scopeUniversal"):b.scope==="project-specific"?a("knowledge.scopeProject"):b.scope==="module-level"?a("knowledge.scopeModule"):b.scope}),b.complexity&&ae.push({icon:ht,iconClass:"text-orange-400",label:a("knowledge.complexity"),value:b.complexity==="advanced"?a("knowledge.complexityAdvanced"):b.complexity==="intermediate"?a("knowledge.complexityIntermediate"):b.complexity==="beginner"?a("knowledge.complexityBeginner"):b.complexity}),b.source&&b.source!=="unknown"&&ae.push({icon:qt,iconClass:"text-violet-400",label:a("knowledge.source"),value:Fa[b.source||""]?a(Fa[b.source||""].labelKey):b.source||"-"}),b.createdAt&&ae.push({icon:it,iconClass:"text-[var(--fg-muted)]",label:a("knowledge.createdAt"),value:rs(b.createdAt,a)}),b.updatedAt&&ae.push({icon:it,iconClass:"text-[var(--fg-muted)]",label:a("knowledge.updatedAt"),value:rs(b.updatedAt,a)}),b.publishedAt&&ae.push({icon:ms,iconClass:"text-emerald-400",label:a("knowledge.published"),value:rs(b.publishedAt,a)}),ae})(),tags:b.tags,id:b.id,sourceFile:b.sourceFile??void 0,sourceFileLabel:a("knowledge.sourceFile")}),b.relations&&Object.entries(b.relations).some(([,ae])=>Array.isArray(ae)&&ae.length>0)&&e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[e.jsx(ra,{size:12,className:"text-purple-400"}),e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase",children:a("knowledge.relatedKnowledge")}),(()=>{const ae=Object.values(b.relations).flat().length;return ae>0?e.jsx("span",{className:"text-[9px] bg-purple-100 text-purple-600 px-1.5 py-0.5 rounded-full font-bold",children:ae}):null})()]}),e.jsx("div",{className:"space-y-1.5",children:Object.entries(b.relations).map(([ae,be])=>!Array.isArray(be)||be.length===0?null:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-[10px] font-mono text-[var(--fg-secondary)] shrink-0 whitespace-nowrap pt-0.5 uppercase",children:ae}),e.jsx("div",{className:"flex flex-wrap gap-1",children:be.map((X,xe)=>{const he=X.target||(typeof X=="string"?X:JSON.stringify(X)),Fe=Q.get(he)||he;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:he,children:Fe},xe)})})]},ae))})]}),b.stats&&Object.values(b.stats).some(ae=>ae>0)&&e.jsxs("div",{className:"px-6 py-3 border-b border-[var(--border-default)]",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"bg-amber-50/60 rounded-xl p-3 text-center border border-amber-100",children:[e.jsx("div",{className:"text-lg font-bold text-amber-700",children:((q=b.stats)==null?void 0:q.authority)??"—"}),e.jsx("div",{className:"text-[10px] text-amber-500 font-medium",children:a("knowledge.authorityScore")})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-xl p-3 text-center border border-[var(--border-default)]",children:[e.jsx("div",{className:"text-lg font-bold text-[var(--fg-primary)]",children:((y=b.stats)==null?void 0:y.guardHits)??0}),e.jsx("div",{className:"text-[10px] text-[var(--fg-muted)] font-medium",children:a("knowledge.guardHits")})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-xl p-3 text-center border border-[var(--border-default)]",children:[e.jsx("div",{className:"text-lg font-bold text-[var(--fg-primary)]",children:((p=b.stats)==null?void 0:p.adoptions)??0}),e.jsx("div",{className:"text-[10px] text-[var(--fg-muted)] font-medium",children:a("knowledge.adoptions")})]}),e.jsxs("div",{className:"bg-blue-50/60 rounded-xl p-3 text-center border border-blue-100",children:[e.jsx("div",{className:"text-lg font-bold text-blue-700",children:((z=b.stats)==null?void 0:z.searchHits)??0}),e.jsx("div",{className:"text-[10px] text-blue-500 font-medium",children:a("knowledge.searchHits")})]})]}),(b.stats.views>0||b.stats.applications>0)&&e.jsxs("div",{className:"flex items-center gap-4 mt-2 text-[10px] text-[var(--fg-muted)]",children:[e.jsxs("span",{children:[a("knowledge.statViews"),": ",b.stats.views]}),e.jsxs("span",{children:[a("knowledge.statApplications"),": ",b.stats.applications]})]})]}),e.jsx($e.Reasoning,{reasoning:V,labels:{section:a("knowledge.reasoning"),source:`${a("knowledge.source")}:`,confidence:`${a("knowledge.confidence")}:`,alternatives:`${a("knowledge.alternatives")}:`},filterSubmitted:!0}),e.jsx($e.Quality,{quality:b.quality,labels:{section:a("knowledge.qualityGrade"),completeness:a("knowledge.qualityCompletionLabel"),adaptation:a("knowledge.qualityAdaptation"),documentation:a("knowledge.qualityDocumentation")},formatFixed:!0}),e.jsx($e.Description,{label:a("knowledge.summary"),text:b.description}),e.jsx($e.MarkdownSection,{label:a("knowledge.markdownDoc"),content:(G=b.content)==null?void 0:G.markdown}),e.jsx($e.Headers,{label:a("knowledge.importHeaders"),headers:b.headers}),e.jsx($e.CodePattern,{label:a("knowledge.codePattern"),code:(A=b.content)==null?void 0:A.pattern,language:b.language}),e.jsx($e.Delivery,{delivery:{topicHint:b.topicHint,whenClause:b.whenClause,doClause:b.doClause,dontClause:b.dontClause,coreCode:b.coreCode},language:b.language}),e.jsx($e.Rationale,{label:a("knowledge.designRationale"),text:(_=b.content)==null?void 0:_.rationale}),e.jsx($e.Steps,{label:a("knowledge.implementSteps"),steps:(J=b.content)==null?void 0:J.steps}),e.jsx($e.Constraints,{label:a("knowledge.constraintsLabel"),constraints:b.constraints}),b.aiInsight&&e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(Ut,{size:11,className:"text-cyan-400"})," ",a("knowledge.aiInsight")]}),e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] leading-relaxed",children:b.aiInsight})]}),(()=>{const ae=Array.isArray(b.lifecycleHistory)?b.lifecycleHistory:(()=>{try{const be=typeof b.lifecycleHistory=="string"?JSON.parse(b.lifecycleHistory):null;return Array.isArray(be)?be:[]}catch{return[]}})();return ae.length>0?e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(it,{size:11,className:"text-[var(--fg-muted)]"})," ",a("knowledge.lifecycleHistoryLabel")]}),e.jsx("div",{className:"space-y-1",children:ae.map((be,X)=>{const xe=vt[be.from]||vt.pending,he=vt[be.to]||vt.pending;return e.jsxs("div",{className:"flex items-center gap-2 text-[10px]",children:[e.jsx("span",{className:"text-[var(--fg-muted)] w-20 shrink-0",children:rs(be.at,a)}),e.jsx("span",{className:`${xe.color}`,children:r(be.from)}),e.jsx("span",{className:"text-[var(--fg-muted)]",children:"→"}),e.jsx("span",{className:`${he.color} font-medium`,children:r(be.to)}),e.jsxs("span",{className:"text-[var(--fg-muted)] ml-auto",children:["by ",be.by]})]},X)})})]}):null})()]}),e.jsxs(Te.Footer,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("button",{onClick:()=>{ce(b),h(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:(Pi[b.lifecycle]||[]).map(ae=>{const be=ae.icon;return e.jsxs("button",{onClick:()=>ae.needsReason?H(b,ae.action):ue(b,ae.action),disabled:L,className:`flex items-center gap-1.5 px-4 py-2 rounded-lg text-xs font-bold border transition-colors disabled:opacity-50 ${ae.bg} ${ae.color} border-current/20`,children:[L?e.jsx(Pe,{size:14,className:"animate-spin"}):e.jsx(be,{size:14}),o(ae.action)]},ae.action)})})]})]})})()]})},js={manual:{label:"manual",color:"bg-[var(--bg-subtle)] text-[var(--fg-secondary)]",icon:dr},"user-ai":{label:"user-ai",color:"bg-violet-100 text-violet-600",icon:Je},"system-ai":{label:"system-ai",color:"bg-amber-100 text-amber-600",icon:ps},"external-ai":{label:"external-ai",color:"bg-cyan-100 text-cyan-600",icon:na}},zi=({onRefresh:t,signalSuggestionCount:s=0,onSuggestionCountChange:a})=>{const{t:r}=Me(),[o,n]=l.useState([]),[d,u]=l.useState(!0),[c,x]=l.useState(null),[v,g]=l.useState(!1),[m,i]=l.useState(!1),[f,j]=l.useState("all"),[C,I]=l.useState(!1),[D,$]=l.useState([]),[O,T]=l.useState(!1),[Z,W]=l.useState(!1),[M,F]=l.useState(null),[k,E]=l.useState(!1),[B,b]=l.useState(""),[h,L]=l.useState(!1),[ie,Y]=l.useState(!1),[ge,Ne]=l.useState(!1),fe=l.useCallback(async()=>{var H;u(!0);try{const S=await ne.listSkills();n(S.skills||[])}catch(S){((H=S.response)==null?void 0:H.status)!==404&&re(S.message||"",{title:r("skills.fetchFailed"),type:"error"}),n([])}finally{u(!1)}},[]);l.useEffect(()=>{fe()},[fe]);const w=async H=>{if((c==null?void 0:c.skillName)===H){x(null);return}E(!1),Y(!1),g(!0);try{const S=await ne.loadSkill(H);x(S)}catch{re(`"${H}" ${r("skills.loadError")}`,{title:r("skills.loadSkillFailed"),type:"error"})}finally{g(!1)}},N=()=>{c!=null&&c.content&&(navigator.clipboard.writeText(c.content),I(!0),setTimeout(()=>I(!1),2e3))},P=()=>{c&&(b(c.content),E(!0))},U=()=>{E(!1),b("")},Q=async()=>{if(!(!c||!B.trim())){L(!0);try{await ne.updateSkill(c.skillName,{content:B}),re(r("skills.saveSuccess"),{title:`Skill "${c.skillName}" ${r("skills.updateSuccess")}`}),E(!1);const H=await ne.loadSkill(c.skillName);x(H)}catch(H){re(H.message||"",{title:r("skills.updateFailed"),type:"error"})}finally{L(!1)}}},ue=async()=>{if(c){Ne(!0);try{await ne.deleteSkill(c.skillName),re(r("skills.deleteSuccess"),{title:`Skill "${c.skillName}" ${r("skills.deleteSuccess")}`}),x(null),Y(!1),E(!1),fe(),t==null||t()}catch(H){re(H.message||"",{title:r("skills.deleteFailed"),type:"error"})}finally{Ne(!1)}}},ce=async()=>{T(!0),W(!0);try{const[H,S]=await Promise.allSettled([ne.suggestSkills(),ne.getSignalStatus()]),se=H.status==="fulfilled"?H.value.suggestions||[]:[],we=S.status==="fulfilled"?S.value.suggestions||[]:[],V=new Map;for(const Re of se)V.set(Re.name,Re);for(const Re of we)V.set(Re.name,{...V.get(Re.name),...Re});const ye=[...V.values()];$(ye),a==null||a(ye.length)}catch(H){re(H.message||"",{title:r("skills.aiRecommendFailed"),type:"error"}),$([]),a==null||a(0)}finally{T(!1)}};l.useEffect(()=>{s>0&&D.length===0&&!Z&&ce()},[]);const ke=async H=>{F(H.name);try{const S=H.description||H.rationale||H.name,se=`${r("skillsView.aiPromptPrefix")}
114
+
115
+ 名称:${H.name}
116
+ 描述:${S}
117
+ 推荐原因:${H.rationale}
118
+
119
+ 请直接生成 Skill 正文内容(Markdown 格式),不需要 frontmatter,不需要输出 JSON 元数据。内容应该详细、实用,包含具体的操作指南和示例。`;let V=(await ne.aiGenerateSkill(se)).reply||H.body||`# ${S}
120
+
121
+ ${H.rationale||""}`;V=V.replace(/^\s*\{["']name["']\s*:.*\}\s*\n?/,"").trim(),await ne.createSkill({name:H.name,description:S,content:V,createdBy:"user-ai"}),re(r("skills.createAddedToKB"),{title:`Skill "${H.name}" ${r("skills.createSuccess")}`}),$(ye=>{const Re=ye.filter(je=>je.name!==H.name);return a==null||a(Re.length),Re}),fe()}catch(S){re(S.message||"",{title:r("skills.createFailed"),type:"error"})}finally{F(null)}},Le=o.filter(H=>f==="all"?!0:H.source===f).sort((H,S)=>H.source===S.source?H.name.localeCompare(S.name):H.source==="project"?-1:1),Ie=o.filter(H=>H.source==="builtin").length,Be=o.filter(H=>H.source==="project").length;return e.jsxs("div",{className:"h-full flex flex-col",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx("div",{className:"w-10 h-10 bg-violet-100 rounded-xl flex items-center justify-center shrink-0",children:e.jsx(Qe,{size:20,className:"text-violet-600"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-lg xl:text-xl font-bold text-[var(--fg-primary)]",children:r("skills.title")}),e.jsx("p",{className:"text-sm text-[var(--fg-secondary)]",children:r("skills.subtitle")})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:ce,disabled:O,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:r("skills.aiRecommendTooltip"),children:[O?e.jsx(Pe,{size:14,className:"animate-spin"}):e.jsx(Ut,{size:14}),r("skills.aiRecommend")]}),e.jsx("button",{onClick:fe,className:"p-2 rounded-lg text-[var(--fg-muted)] hover:text-[var(--fg-secondary)] hover:bg-[var(--bg-subtle)] transition-colors",title:r("common.refresh"),children:e.jsx(jt,{size:16})}),e.jsxs("button",{onClick:()=>i(!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(Je,{size:14}),r("skills.addSkill")]})]})]}),e.jsx("div",{className:"flex items-center gap-1 mb-4 p-1 bg-[var(--bg-subtle)] rounded-lg w-fit",children:[{key:"all",label:r("common.all"),count:o.length},{key:"project",label:r("skills.filterProject"),count:Be,icon:Dt},{key:"builtin",label:r("skills.filterBuiltin"),count:Ie,icon:Gn}].map(H=>e.jsxs("button",{onClick:()=>j(H.key),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${f===H.key?"bg-[var(--bg-surface)] text-violet-700 shadow-sm":"text-[var(--fg-secondary)] hover:text-[var(--fg-primary)]"}`,children:[H.icon&&e.jsx(H.icon,{size:12}),H.label,e.jsx("span",{className:`ml-0.5 px-1.5 py-0.5 rounded-full text-[10px] ${f===H.key?"bg-violet-100 text-violet-600":"bg-[var(--bg-subtle)] text-[var(--fg-secondary)]"}`,children:H.count})]},H.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(Ut,{size:16,className:"text-amber-600"}),e.jsx("span",{className:"text-sm font-semibold text-amber-800",children:r("skills.aiRecommendDesc")}),D.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:D.length})]}),e.jsx("button",{onClick:()=>W(!1),className:"p-1 text-amber-400 hover:text-amber-600",children:e.jsx(Xe,{size:14})})]}),O?e.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-xs py-2",children:[e.jsx(Pe,{size:14,className:"animate-spin"}),r("skills.aiRecommending")]}):D.length===0?e.jsx("p",{className:"text-xs text-amber-600/70",children:r("skills.noRecommendations")}):e.jsx("div",{className:"space-y-2",children:D.map(H=>e.jsxs("div",{className:"flex items-start gap-3 p-3 bg-[var(--bg-surface)] rounded-lg border border-amber-100",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-mono text-xs font-semibold text-[var(--fg-primary)]",children:H.name}),e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[9px] font-bold uppercase ${H.priority==="high"?"bg-red-100 text-red-600":H.priority==="medium"?"bg-amber-100 text-amber-600":"bg-[var(--bg-subtle)] text-[var(--fg-secondary)]"}`,children:H.priority}),e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)]",children:H.source})]}),e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] mb-1",children:H.description}),e.jsx("p",{className:"text-[11px] text-[var(--fg-muted)] line-clamp-2",children:H.rationale})]}),e.jsx("button",{onClick:()=>ke(H),disabled:M===H.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:M===H.name?e.jsxs(e.Fragment,{children:[e.jsx(Pe,{size:12,className:"animate-spin"})," ",r("skills.creating")]}):e.jsxs(e.Fragment,{children:[e.jsx(et,{size:12})," ",r("skills.acceptRecommend")]})})]},H.name))})]}),e.jsxs("div",{className:"flex-1 flex gap-4 xl:gap-6 min-h-0 overflow-hidden",children:[e.jsx("div",{className:"w-1/2 overflow-y-auto pr-2 space-y-2",children:d?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx(Pe,{size:24,className:"animate-spin text-violet-400"})}):Le.length===0?e.jsxs("div",{className:"text-center py-20 text-[var(--fg-muted)]",children:[e.jsx(Qe,{size:40,className:"mx-auto mb-3 opacity-40"}),e.jsx("p",{children:r("skills.noResults")})]}):Le.map(H=>e.jsx("button",{onClick:()=>w(H.name),className:`w-full text-left p-4 rounded-xl border transition-all ${(c==null?void 0:c.skillName)===H.name?"border-violet-300 bg-violet-50 shadow-sm":"border-[var(--border-default)] bg-[var(--bg-surface)] hover:border-[var(--border-emphasis)] hover:shadow-sm"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`mt-0.5 shrink-0 ${(c==null?void 0:c.skillName)===H.name?"text-violet-500":"text-[var(--fg-muted)]"}`,children:(c==null?void 0:c.skillName)===H.name?e.jsx(Rt,{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-[var(--fg-primary)]",children:H.name}),e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider ${H.source==="builtin"?"bg-blue-100 text-blue-600":"bg-emerald-100 text-emerald-600"}`,children:H.source==="builtin"?r("skills.filterBuiltin"):r("skills.filterProject")}),H.createdBy&&js[H.createdBy]&&(()=>{const S=js[H.createdBy],se=S.icon;return e.jsxs("span",{className:`flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[10px] font-medium ${S.color}`,children:[e.jsx(se,{size:10}),S.label]})})()]}),e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] line-clamp-2",children:H.summary}),H.useCase&&e.jsxs("p",{className:"text-[11px] text-violet-500 mt-1 italic",children:[r("skills.useCase"),":",H.useCase]})]})]})},H.name))}),e.jsx("div",{className:"w-1/2 overflow-y-auto border border-[var(--border-default)] rounded-xl bg-[var(--bg-surface)]",children:v?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(Pe,{size:24,className:"animate-spin text-violet-400"})}):c?e.jsxs("div",{className:"h-full flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-[var(--border-default)]",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ft,{size:16,className:"text-violet-500"}),e.jsx("span",{className:"font-mono font-semibold text-sm",children:c.skillName}),e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-bold uppercase ${c.source==="builtin"?"bg-blue-100 text-blue-600":"bg-emerald-100 text-emerald-600"}`,children:c.source==="builtin"?r("skills.filterBuiltin"):r("skills.filterProject")}),c.createdBy&&js[c.createdBy]&&(()=>{const H=js[c.createdBy],S=H.icon;return e.jsxs("span",{className:`flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[10px] font-medium ${H.color}`,children:[e.jsx(S,{size:10}),r(`skills.createdBy.${c.createdBy}`)]})})()]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)]",children:[c.charCount," ",r("skills.chars")]}),e.jsx("button",{onClick:N,className:"p-1.5 rounded-md hover:bg-[var(--bg-subtle)] transition-colors text-[var(--fg-muted)] hover:text-[var(--fg-secondary)]",title:r("common.copy"),children:C?e.jsx(yt,{size:14,className:"text-emerald-500"}):e.jsx(Qt,{size:14})}),c.source==="project"&&!k&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:P,className:"p-1.5 rounded-md hover:bg-blue-50 transition-colors text-[var(--fg-muted)] hover:text-blue-600",title:r("common.edit"),children:e.jsx(Ws,{size:14})}),e.jsx("button",{onClick:()=>Y(!0),className:"p-1.5 rounded-md hover:bg-red-50 transition-colors text-[var(--fg-muted)] hover:text-red-500",title:r("common.delete"),children:e.jsx(ot,{size:14})})]}),k&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:Q,disabled:h,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:[h?e.jsx(Pe,{size:12,className:"animate-spin"}):e.jsx(Ms,{size:12}),r("common.save")]}),e.jsx("button",{onClick:U,className:"px-2.5 py-1 border border-[var(--border-default)] text-[var(--fg-secondary)] rounded-md hover:bg-[var(--bg-subtle)] transition-colors text-xs",children:r("common.cancel")})]})]})]}),c.relatedSkills.length>0&&e.jsxs("div",{className:"px-4 py-2 border-b border-[var(--border-default)] flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)] uppercase font-bold",children:[r("skills.related"),":"]}),c.relatedSkills.map(H=>e.jsx("button",{onClick:()=>w(H),className:"text-[11px] text-violet-600 hover:text-violet-800 bg-violet-50 px-2 py-0.5 rounded-full transition-colors",children:H},H))]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 relative",children:[k?e.jsx("textarea",{value:B,onChange:H=>b(H.target.value),className:"w-full h-full min-h-[300px] text-xs text-[var(--fg-primary)] font-mono leading-relaxed border border-blue-200 rounded-lg p-3 focus:outline-none focus:ring-2 focus:ring-blue-300 resize-none bg-blue-50/30",spellCheck:!1}):e.jsx("pre",{className:"whitespace-pre-wrap text-xs text-[var(--fg-primary)] font-mono leading-relaxed",children:c.content}),ie&&e.jsx("div",{className:"absolute inset-0 bg-white/90 backdrop-blur-sm flex items-center justify-center z-10",children:e.jsxs("div",{className:"bg-[var(--bg-surface)] border border-red-200 rounded-xl shadow-lg p-6 max-w-sm text-center",children:[e.jsx(ot,{size:32,className:"mx-auto mb-3 text-red-400"}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:r("skills.deleteConfirm")}),e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] mb-4",children:r("skills.deleteSkillConfirmMsg",{name:c.skillName})}),e.jsxs("div",{className:"flex gap-3 justify-center",children:[e.jsx("button",{onClick:()=>Y(!1),className:"px-4 py-2 border border-[var(--border-default)] text-[var(--fg-secondary)] rounded-lg hover:bg-[var(--bg-subtle)] text-sm",children:r("common.cancel")}),e.jsxs("button",{onClick:ue,disabled:ge,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:[ge?e.jsx(Pe,{size:14,className:"animate-spin"}):e.jsx(ot,{size:14}),r("skills.confirmDelete")]})]})]})})]})]}):e.jsx("div",{className:"flex items-center justify-center h-full text-[var(--fg-muted)]",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Qe,{size:40,className:"mx-auto mb-3 opacity-30"}),e.jsx("p",{className:"text-sm",children:r("skills.selectToView")})]})})})]}),m&&e.jsx(_i,{onClose:()=>i(!1),onCreated:()=>{i(!1),fe(),t==null||t()}})]})},_i=({onClose:t,onCreated:s})=>{const{t:a}=Me(),[r,o]=l.useState("ai"),[n,d]=l.useState(""),[u,c]=l.useState(!1),[x,v]=l.useState(""),[g,m]=l.useState(""),[i,f]=l.useState(""),[j,C]=l.useState(!1),[I,D]=l.useState(""),[$,O]=l.useState(!1),T=async()=>{if(n.trim()){c(!0),D("");try{const M=(await ne.aiGenerateSkill(n)).reply||"";let F="",k="",E=M;const B=/```(?:json)?\s*\n?\s*(\{[^}]*"name"[^}]*\})\s*\n?\s*```/i,b=M.match(B);if(b)try{const h=JSON.parse(b[1]);F=h.name||"",k=h.description||"",E=M.replace(b[0],"").trim()}catch{}if(!F){const h=M.split(`
122
+ `);for(let L=0;L<Math.min(h.length,5);L++){const ie=h[L].trim();if(!(!ie||ie.startsWith("```"))&&ie.startsWith("{")&&ie.endsWith("}"))try{const Y=JSON.parse(ie);if(Y.name){F=Y.name,k=Y.description||"";let ge=L+1;for(;ge<h.length&&!h[ge].trim();)ge++;E=h.slice(ge).join(`
123
+ `).trim();break}}catch{}}}if(!F){const h=/"name"\s*:\s*"([a-z][a-z0-9-]{1,62}[a-z0-9])"/,L=/"description"\s*:\s*"([^"]+)"/,ie=M.match(h),Y=M.match(L);ie&&(F=ie[1]),Y&&(k=Y[1])}E=E.replace(/```(?:json)?\s*\n?\s*\{[^}]*"name"[^}]*\}\s*\n?\s*```/gi,"").replace(/^\s*\{[^}]*"name"[^}]*\}\s*$/gm,"").trim(),F&&v(F),k&&m(k),f(E||M.trim()),O(!0),o("manual"),re(a("skills.checkGenerated"),{title:a("skills.aiGenerated")})}catch(W){D(a("skills.aiGenFailed")+": "+(W.message||""))}finally{c(!1)}}},Z=async()=>{var W,M,F;if(!x.trim()||!g.trim()||!i.trim()){D(a("skills.fillRequired"));return}C(!0),D("");try{await ne.createSkill({name:x.trim(),description:g.trim(),content:i.trim(),createdBy:$?"user-ai":"manual"}),re(a("skills.savedToKB"),{title:`Skill "${x}" ${a("skills.createSuccess")}`}),s()}catch(k){const E=((F=(M=(W=k.response)==null?void 0:W.data)==null?void 0:M.error)==null?void 0:F.message)||k.message||"";D(a("skills.createFailed")+": "+E)}finally{C(!1)}};return e.jsxs(Ze,{className:"z-40 flex items-center justify-center",children:[e.jsx(Ze.Backdrop,{className:"bg-black/20 dark:bg-black/40 backdrop-blur-sm"}),e.jsxs("div",{className:"relative bg-[var(--bg-surface)] rounded-2xl shadow-2xl w-[720px] max-h-[85vh] flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 bg-violet-100 rounded-lg flex items-center justify-center",children:e.jsx(Je,{size:16,className:"text-violet-600"})}),e.jsx("h3",{className:"font-bold text-lg",children:a("skills.addSkill")})]}),e.jsx("button",{onClick:t,className:"p-1.5 rounded-lg hover:bg-[var(--bg-subtle)] transition-colors",children:e.jsx(Xe,{size:18,className:"text-[var(--fg-muted)]"})})]}),e.jsx("div",{className:"px-6 pt-4",children:e.jsxs("div",{className:"inline-flex items-center gap-1 p-1 bg-[var(--bg-subtle)] rounded-lg",children:[e.jsxs("button",{onClick:()=>o("ai"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${r==="ai"?"bg-[var(--bg-surface)] text-violet-700 shadow-sm":"text-[var(--fg-secondary)] hover:text-[var(--fg-primary)]"}`,children:[e.jsx(Je,{size:12}),a("skills.aiGenMode")]}),e.jsxs("button",{onClick:()=>o("manual"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${r==="manual"?"bg-[var(--bg-surface)] text-violet-700 shadow-sm":"text-[var(--fg-secondary)] hover:text-[var(--fg-primary)]"}`,children:[e.jsx(ft,{size:12}),a("skills.manualMode")]})]})}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-4 space-y-4",children:[r==="ai"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[var(--fg-primary)] mb-1.5",children:a("skills.describeSkill")}),e.jsx("div",{className:"relative",children:e.jsx("textarea",{value:n,onChange:W=>d(W.target.value),placeholder:a("skillsView.placeholderDesc"),className:"w-full h-32 px-4 py-3 border border-[var(--border-default)] rounded-xl text-sm resize-none focus:outline-none focus:ring-2 focus:ring-violet-300 focus:border-violet-400",disabled:u})})]}),e.jsx("button",{onClick:T,disabled:u||!n.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:u?e.jsxs(e.Fragment,{children:[e.jsx(Pe,{size:16,className:"animate-spin"}),a("skills.aiGeneratingContent")]}):e.jsxs(e.Fragment,{children:[e.jsx(sa,{size:16}),a("skills.generateSkill")]})})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-[var(--fg-primary)] mb-1.5",children:[a("skills.skillName")," ",e.jsx("span",{className:"text-[var(--fg-muted)] text-xs",children:"(kebab-case)"})]}),e.jsx("input",{type:"text",value:x,onChange:W=>v(W.target.value),placeholder:"my-custom-skill",className:"w-full px-3 py-2 border border-[var(--border-default)] rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-violet-300 focus:border-violet-400"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-[var(--fg-primary)] mb-1.5",children:a("skills.skillDescription")}),e.jsx("input",{type:"text",value:g,onChange:W=>m(W.target.value),placeholder:a("skillsView.placeholderName"),className:"w-full px-3 py-2 border border-[var(--border-default)] rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-violet-300 focus:border-violet-400"})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-[var(--fg-primary)] mb-1.5",children:[a("skills.skillContent")," ",e.jsx("span",{className:"text-[var(--fg-muted)] text-xs",children:"(Markdown)"})]}),e.jsx("textarea",{value:i,onChange:W=>f(W.target.value),placeholder:a("skillsView.placeholderContent"),className:"w-full h-64 px-4 py-3 border border-[var(--border-default)] rounded-xl text-sm font-mono resize-none focus:outline-none focus:ring-2 focus:ring-violet-300 focus:border-violet-400 leading-relaxed"})]})]}),I&&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(Xt,{size:16,className:"shrink-0 mt-0.5"}),e.jsx("span",{children:I})]})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-[var(--border-default)] flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:t,className:"px-4 py-2 text-sm text-[var(--fg-secondary)] hover:text-[var(--fg-primary)] transition-colors",children:a("common.cancel")}),r==="manual"&&e.jsx("button",{onClick:Z,disabled:j||!x.trim()||!g.trim()||!i.trim(),className:"flex items-center gap-2 px-5 py-2 bg-violet-600 text-white rounded-lg hover:bg-violet-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors text-sm font-medium",children:j?e.jsxs(e.Fragment,{children:[e.jsx(Pe,{size:14,className:"animate-spin"}),a("common.saving")]}):e.jsxs(e.Fragment,{children:[e.jsx(kt,{size:14}),a("skills.addSkill")]})})]})]})]})},za=["objc-deep-scan","category-scan","project-profile","code-standard","architecture","code-pattern","event-and-data-flow","best-practice","agent-guidelines"],Bi={"code-standard":e.jsx(Qe,{className:"w-5 h-5"}),"code-pattern":e.jsx(Yt,{className:"w-5 h-5"}),architecture:e.jsx(ht,{className:"w-5 h-5"}),"best-practice":e.jsx(Je,{className:"w-5 h-5"}),"event-and-data-flow":e.jsx(et,{className:"w-5 h-5"}),"project-profile":e.jsx(Ts,{className:"w-5 h-5"}),"agent-guidelines":e.jsx(na,{className:"w-5 h-5"})};function Gi(t){return Bi[t]||e.jsx(Yt,{className:"w-5 h-5"})}const $i=({task:t})=>{const{t:s}=Me(),{status:a,meta:r}=t,o={skeleton:"bg-[var(--bg-subtle)] border-[var(--border-default)]",filling:"bg-blue-50 border-blue-300",completed:"bg-emerald-50 border-emerald-300",failed:"bg-red-50 border-red-300"},n={skeleton:e.jsxs("span",{className:"flex items-center gap-1 text-xs text-[var(--fg-muted)]",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-[var(--border-emphasis)]"}),s("bootstrap.statusLabels.skeleton")]}),filling:e.jsxs("span",{className:"flex items-center gap-1 text-xs text-blue-600",children:[e.jsx(Pe,{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(yt,{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 ${o[a]||o.skeleton}`,children:[a==="skeleton"&&e.jsx("div",{className:"absolute inset-0 rounded-xl overflow-hidden",children:e.jsx("div",{className:"animate-pulse bg-gradient-to-r from-transparent via-[var(--border-default)]/40 to-transparent h-full w-full"})}),a==="filling"&&e.jsx("div",{className:"absolute inset-0 rounded-xl overflow-hidden",children:e.jsx("div",{className:"animate-pulse bg-gradient-to-r from-transparent via-blue-200/30 to-transparent h-full w-full"})}),e.jsxs("div",{className:"relative z-10 flex items-start justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`flex-shrink-0 p-2 rounded-lg ${a==="completed"?"bg-emerald-100 text-emerald-600":a==="filling"?"bg-blue-100 text-blue-600":a==="failed"?"bg-red-100 text-red-600":"bg-[var(--bg-subtle)] text-[var(--fg-muted)]"}`,children:Gi(t.id)}),e.jsxs("div",{children:[e.jsx("h3",{className:`font-medium text-sm ${a==="skeleton"?"text-[var(--fg-muted)]":"text-[var(--fg-primary)]"}`,children:(()=>{const d=`bootstrap.pipelineLabels.${r.dimId}`,u=s(d);return u!==d?u:r.label})()}),a==="completed"&&t.result&&e.jsx("p",{className:"text-xs text-emerald-600 mt-0.5",children:(()=>{const d=t.result,u=d.sourceCount??0,c=d.extracted??0;return d.type==="empty"?s("bootstrap.noMatch"):d.type==="skill"?d.empty?s("bootstrap.noMatch"):c>0?s("bootstrap.featuresAndCandidates",{sourceCount:u,extracted:c}):s("bootstrap.featuresOnly",{sourceCount:u}):c>0?s("bootstrap.candidatesOnly",{extracted:c}):d.skillPending?s("bootstrap.skillPending"):s("bootstrap.noMatch")})()}),a==="failed"&&t.error&&e.jsx("p",{className:"text-xs text-red-500 mt-0.5 truncate max-w-[240px]",children:t.error})]})]}),e.jsx("div",{className:"flex-shrink-0",children:n[a]})]})]})},Hi=[{key:"round1",labelKey:"bootstrap.reviewRounds.round1Label",descKey:"bootstrap.reviewRounds.round1Desc",icon:e.jsx(br,{className:"w-4 h-4"})},{key:"round2",labelKey:"bootstrap.reviewRounds.round2Label",descKey:"bootstrap.reviewRounds.round2Desc",icon:e.jsx(Ns,{className:"w-4 h-4"})},{key:"round3",labelKey:"bootstrap.reviewRounds.round3Label",descKey:"bootstrap.reviewRounds.round3Desc",icon:e.jsx($n,{className:"w-4 h-4"})}],Oi=({review:t})=>{const{t:s}=Me();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(us,{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:Hi.map(({key:a,labelKey:r,descKey:o,icon:n})=>{const d=t[a],u=d.status==="running",c=d.status==="completed",x=d.status==="idle";return e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg border transition-all duration-300 ${u?"border-purple-300 bg-purple-100/60":c?"border-emerald-300 bg-emerald-50/60":"border-[var(--border-default)] bg-[var(--bg-surface)]"}`,children:[e.jsx("div",{className:`flex-shrink-0 p-1.5 rounded-md ${u?"bg-purple-200 text-purple-700":c?"bg-emerald-100 text-emerald-600":"bg-[var(--bg-subtle)] text-[var(--fg-muted)]"}`,children:n}),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 ${x?"text-[var(--fg-muted)]":"text-[var(--fg-primary)]"}`,children:s(r)}),e.jsx("span",{className:"text-xs text-[var(--fg-muted)]",children:s(o)})]}),a==="round1"&&c&&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"&&u&&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"&&c&&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"&&c&&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:[u&&e.jsx(Pe,{className:"w-4 h-4 text-purple-500 animate-spin"}),c&&e.jsx(yt,{className:"w-4 h-4 text-emerald-500"})]})]},a)})})]})};function _a(t){if(t<0)return"--";const s=Math.floor(t/1e3),a=Math.floor(s/60),r=s%60;return a===0?`${r}s`:`${a}m ${r.toString().padStart(2,"0")}s`}const Ki=({session:t,isAllDone:s,reviewState:a,onDismiss:r})=>{const{t:o}=Me(),[n,d]=l.useState(Date.now());if(l.useEffect(()=>{if(!t||t.status!=="running")return;const f=setInterval(()=>d(Date.now()),1e3);return()=>clearInterval(f)},[t==null?void 0:t.status]),!t)return null;const u=t.startedAt?n-t.startedAt:t.elapsedMs??0,c=t.completed+t.failed,x=t.total-c,v=t.elapsedMs??0,g=c>0&&v>0?Math.round(v/c*x):-1,m=t.totalToolCalls??0,i=t.status==="completed"?o("bootstrap.allCompleted"):t.status==="completed_with_errors"?o("bootstrap.completedWithErrors"):null;return e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-[var(--border-default)] shadow-sm p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-5",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold text-[var(--fg-primary)]",children:o("bootstrap.title")}),i&&e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] mt-0.5",children:i})]}),s&&r&&e.jsx("button",{onClick:r,className:"text-sm px-3 py-1.5 rounded-lg bg-[var(--bg-subtle)] hover:bg-[var(--bg-subtle)] text-[var(--fg-secondary)] transition-colors",children:o("bootstrap.close")})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-5 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[var(--fg-secondary)]",children:[e.jsx(it,{size:14,className:"text-[var(--fg-muted)]"}),e.jsxs("span",{children:[o("bootstrap.elapsed")," ",e.jsx("span",{className:"font-medium text-[var(--fg-primary)]",children:_a(u)})]})]}),t.status==="running"&&x>0&&g>0&&e.jsxs("div",{className:"flex items-center gap-1.5 text-[var(--fg-secondary)]",children:[e.jsx(it,{size:14,className:"text-blue-400"}),e.jsxs("span",{children:[o("bootstrap.estimatedRemaining")," ",e.jsx("span",{className:"font-medium text-blue-600",children:_a(g)})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-[var(--fg-secondary)]",children:[e.jsx(vr,{size:14,className:"text-[var(--fg-muted)]"}),e.jsxs("span",{children:[o("bootstrap.toolCalls")," ",e.jsx("span",{className:"font-medium text-[var(--fg-primary)]",children:m})]})]}),e.jsx("div",{className:"text-[var(--fg-muted)] text-xs",children:o("bootstrap.dimensions",{done:c,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((f,j)=>{var D,$;const C=za.indexOf(((D=f.meta)==null?void 0:D.dimId)??f.id),I=za.indexOf((($=j.meta)==null?void 0:$.dimId)??j.id);return(C===-1?999:C)-(I===-1?999:I)}).map(f=>e.jsx($i,{task:f},f.id))}),a&&a.activeRound>0&&e.jsx(Oi,{review:a})]})},ws={index:{icon:Qe,color:"text-blue-600",label:"overview"},architecture:{icon:ht,color:"text-violet-600",label:"architecture"},"getting-started":{icon:Tt,color:"text-emerald-600",label:"getting-started"},protocols:{icon:Je,color:"text-amber-600",label:"protocols"},components:{icon:Tt,color:"text-emerald-600",label:"components"},patterns:{icon:Je,color:"text-amber-600",label:"patterns"},module:{icon:Dt,color:"text-cyan-600",label:"module"},document:{icon:ft,color:"text-orange-600",label:"document"},_index:{icon:ea,color:"text-[var(--fg-secondary)]",label:"index"}};function qi(t){var a;const s=((a=t.split("/").pop())==null?void 0:a.replace(".md",""))||"";return s==="_index"?ws._index:t.startsWith("modules/")?ws.module:t.startsWith("documents/")?ws.document:ws[s]||{icon:ft,color:"text-[var(--fg-secondary)]",label:"doc"}}const Ui={"cursor-devdocs":{label:"Cursor Docs",color:"text-orange-700",bg:"bg-orange-50 border-orange-200"}},Wi={modules:"modules",documents:"documents"};function Kr(t){return t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`}function Vi(t){if(!t)return"";const s=new Date(t);if(isNaN(s.getTime()))return"";const r=Date.now()-s.getTime();return r<6e4?"just now":r<36e5?`${Math.floor(r/6e4)} min ago`:r<864e5?`${Math.floor(r/36e5)} hr ago`:r<6048e5?`${Math.floor(r/864e5)} d ago`:s.toLocaleDateString("zh-CN")}const Ji=({task:t,wiki:s})=>{const{t:a}=Me();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(Xt,{size:K.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(Xt,{size:K.md,className:"text-amber-600"})}),e.jsx("span",{className:"text-sm text-amber-700",children:a("wiki.outOfDateHint")})]}):null};function Yi(t,s){const a=[],r=new Map((s==null?void 0:s.map(x=>[x.path,x]))||[]),o=[],n=new Map;for(const x of t){const v=x.path.split("/"),g=r.get(x.path);if(v.length===1)o.push({name:v[0],path:x.path,isDir:!1,file:x,metaInfo:g});else{const m=v[0];n.has(m)||n.set(m,[]),n.get(m).push({name:v.slice(1).join("/"),path:x.path,isDir:!1,file:x,metaInfo:g})}}const d=["index.md","architecture.md","getting-started.md","patterns.md","protocols.md","components.md"];o.sort((x,v)=>{const g=d.indexOf(x.name),m=d.indexOf(v.name);return g!==-1&&m!==-1?g-m:g!==-1?-1:m!==-1?1:x.name.localeCompare(v.name)}),a.push(...o);const u=["modules","patterns","documents"],c=[...n.entries()].sort(([x],[v])=>{const g=u.indexOf(x),m=u.indexOf(v);return g!==-1&&m!==-1?g-m:g!==-1?-1:m!==-1?1:x.localeCompare(v)});for(const[x,v]of c){const g=v.filter(m=>!m.name.startsWith("_index")).sort((m,i)=>m.name.localeCompare(i.name));a.push({name:x,path:x,isDir:!0,children:g})}return a}const Qi=({tree:t,selectedFile:s,onSelect:a,searchQuery:r})=>{const[o,n]=l.useState(new Set(["modules","documents"])),d=x=>{n(v=>{const g=new Set(v);return g.has(x)?g.delete(x):g.add(x),g})},c=(x=>{if(!r)return x;const v=r.toLowerCase();return x.filter(g=>{var m;return g.isDir?(m=g.children)==null?void 0:m.some(i=>i.name.toLowerCase().includes(v)||i.path.toLowerCase().includes(v)):g.name.toLowerCase().includes(v)||g.path.toLowerCase().includes(v)})})(t);return e.jsx("div",{className:"space-y-0.5",children:c.map(x=>{var v;if(x.isDir){const g=o.has(x.path),m=r.toLowerCase(),i=r?(v=x.children)==null?void 0:v.filter(f=>f.name.toLowerCase().includes(m)||f.path.toLowerCase().includes(m)):x.children;return e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>d(x.path),className:"w-full flex items-center gap-2 px-3 py-2 text-sm text-[var(--fg-secondary)] hover:bg-[var(--bg-subtle)] rounded-lg transition-colors",children:[g?e.jsx(Rt,{size:14,className:"text-[var(--fg-muted)] flex-shrink-0"}):e.jsx(rt,{size:14,className:"text-[var(--fg-muted)] flex-shrink-0"}),e.jsx(Dt,{size:14,className:"text-amber-500 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:Wi[x.name]||x.name}),e.jsx("span",{className:"ml-auto text-xs text-[var(--fg-muted)]",children:(i==null?void 0:i.length)||0})]}),g&&i&&e.jsx("div",{className:"ml-3",children:i.map(f=>e.jsx(Ba,{node:f,isActive:s===f.path,onSelect:a},f.path))})]},x.path)}return e.jsx(Ba,{node:x,isActive:s===x.path,onSelect:a},x.path)})})},Ba=({node:t,isActive:s,onSelect:a})=>{var u,c;const r=qi(t.path),o=r.icon,n=(u=t.metaInfo)==null?void 0:u.polished,d=(c=t.metaInfo)==null?void 0:c.source;return e.jsxs("button",{onClick:()=>a(t.path),className:`w-full flex items-center gap-2 px-3 py-2 text-sm rounded-lg transition-all ${s?"bg-blue-50 text-blue-700 border border-blue-200 shadow-sm":"text-[var(--fg-secondary)] hover:bg-[var(--bg-subtle)]"}`,children:[e.jsx(o,{size:14,className:`flex-shrink-0 ${s?"text-blue-500":r.color}`}),e.jsx("span",{className:"truncate text-left",children:t.name.replace(".md","")}),e.jsxs("span",{className:"ml-auto flex items-center gap-1 flex-shrink-0",children:[n&&e.jsx("span",{title:"AI Enhanced",children:e.jsx(Je,{size:10,className:"text-violet-400"})}),d&&e.jsx("span",{title:`Source: ${d}`,children:e.jsx(On,{size:10,className:"text-orange-400"})})]})]})},Xi=({filePath:t,content:s,loading:a,meta:r,onBack:o})=>{var m;const{t:n}=Me(),[d,u]=l.useState(!1),c=(m=r==null?void 0:r.files)==null?void 0:m.find(i=>i.path===t),x=()=>{navigator.clipboard.writeText(s),u(!0),setTimeout(()=>u(!1),2e3)},v=t.split("/"),g=v.map((i,f)=>({label:f===v.length-1?i.replace(".md",""):i,isLast:f===v.length-1}));return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3 bg-[var(--bg-subtle)] border-b border-[var(--border-default)] flex-shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:o,className:"p-1.5 hover:bg-[var(--bg-subtle)] rounded-lg transition-colors lg:hidden",title:n("wiki.backToList"),children:e.jsx(Hn,{size:K.md})}),e.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[e.jsx(Qe,{size:14,className:"text-[var(--fg-muted)]"}),e.jsx("span",{className:"text-[var(--fg-muted)]",children:"wiki"}),g.map((i,f)=>e.jsxs(Pt.Fragment,{children:[e.jsx(rt,{size:12,className:"text-[var(--fg-muted)]"}),e.jsx("span",{className:i.isLast?"font-medium text-[var(--fg-primary)]":"text-[var(--fg-muted)]",children:i.label})]},f))]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[(c==null?void 0:c.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(Je,{size:10}),n("wiki.aiBadge")]}),(c==null?void 0:c.source)&&(()=>{const i=Ui[c.source];return e.jsx("span",{className:`flex items-center gap-1 text-xs border px-2 py-0.5 rounded-full ${(i==null?void 0:i.bg)||"bg-[var(--bg-subtle)] border-[var(--border-default)]"} ${(i==null?void 0:i.color)||"text-[var(--fg-secondary)]"}`,children:(i==null?void 0:i.label)||c.source})})(),e.jsxs("button",{onClick:x,className:"flex items-center gap-1 px-2.5 py-1 text-xs text-[var(--fg-secondary)] hover:text-[var(--fg-primary)] hover:bg-[var(--bg-subtle)] rounded-md transition-colors",children:[d?e.jsx(yt,{size:12,className:"text-emerald-500"}):e.jsx(Qt,{size:12}),n(d?"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(Pe,{size:K.xl,className:"text-blue-500 animate-spin"})}):e.jsx("div",{className:"px-4 xl:px-6 2xl:px-8 py-6 max-w-4xl mx-auto",children:e.jsx(Et,{content:s,className:"wiki-reader"})})})]})},Zi=()=>{const{t}=Me();return e.jsxs("div",{className:"h-72 flex flex-col items-center justify-center bg-[var(--bg-surface)] rounded-2xl border border-dashed border-[var(--border-default)] text-[var(--fg-muted)]",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-[var(--bg-subtle)] flex items-center justify-center mb-4",children:e.jsx(Qe,{size:32,className:"text-[var(--fg-muted)]"})}),e.jsx("p",{className:"text-sm font-medium text-[var(--fg-secondary)]",children:t("wiki.emptyTitle")}),e.jsx("p",{className:"mt-2 text-xs max-w-sm text-center leading-relaxed text-[var(--fg-muted)]",children:t("wiki.emptyDesc")}),e.jsx("p",{className:"mt-3 text-[11px] text-[var(--fg-muted)]",children:t("wiki.emptyHint")})]})},ec=({meta:t,onSelectFile:s,isGenerating:a,progress:r,message:o})=>{var x;const{t:n}=Me(),d=[{path:"index.md",label:n("wiki.quickOverview"),desc:n("wiki.quickOverviewDesc"),icon:Qe,color:"bg-blue-50 text-blue-600 border-blue-200"},{path:"architecture.md",label:n("wiki.quickArch"),desc:n("wiki.quickArchDesc"),icon:ht,color:"bg-violet-50 text-violet-600 border-violet-200"},{path:"getting-started.md",label:n("wiki.quickStart"),desc:n("wiki.quickStartDesc"),icon:Tt,color:"bg-emerald-50 text-emerald-600 border-emerald-200"},{path:"protocols.md",label:n("wiki.quickProtocols"),desc:n("wiki.quickProtocolsDesc"),icon:Je,color:"bg-amber-50 text-amber-600 border-amber-200"}],u=new Set(((x=t==null?void 0:t.files)==null?void 0:x.map(v=>v.path||v.name))??[]),c=d.filter(v=>u.size===0||u.has(v.path));return e.jsxs("div",{className:"p-4 xl:p-6 2xl:p-8 overflow-y-auto flex-1",children:[a&&e.jsxs("div",{className:"mb-8 flex flex-col items-center",children:[e.jsxs("div",{className:"relative w-20 h-20 mb-5",children:[e.jsx("span",{className:"absolute inset-0 rounded-full bg-blue-100 animate-ping opacity-20"}),e.jsx("span",{className:"absolute inset-2 rounded-full bg-blue-50 animate-pulse"}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx(na,{size:36,className:"text-blue-500 animate-pulse"})})]}),e.jsx("h3",{className:"text-lg font-semibold text-[var(--fg-primary)] mb-1",children:n("wiki.wikiGenerating")}),e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] max-w-md text-center leading-relaxed",children:o||n("wiki.generating")}),typeof r=="number"&&e.jsxs("div",{className:"mt-4 w-48",children:[e.jsx("div",{className:"w-full bg-[var(--bg-subtle)] rounded-full h-2",children:e.jsx("div",{className:"bg-gradient-to-r from-blue-500 to-indigo-500 h-2 rounded-full transition-all duration-700 ease-out",style:{width:`${Math.max(r,3)}%`}})}),e.jsxs("p",{className:"text-xs text-center text-blue-500 mt-1.5 font-mono",children:[r,"%"]})]})]}),!a&&e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"w-12 h-12 bg-[var(--bg-subtle)] rounded-xl flex items-center justify-center mx-auto mb-3",children:e.jsx(ft,{size:24,className:"text-[var(--fg-muted)]"})}),e.jsx("h3",{className:"text-lg font-semibold text-[var(--fg-primary)]",children:n("wiki.selectFile")}),e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] mt-1",children:n("wiki.selectPlaceholder")})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 max-w-lg mx-auto",children:c.map(v=>{const g=v.icon;return e.jsxs("button",{onClick:()=>s(v.path),className:`text-left p-4 rounded-xl border ${v.color} hover:shadow-sm transition-all group`,children:[e.jsx(g,{size:20,className:"mb-2 opacity-70 group-hover:opacity-100"}),e.jsx("div",{className:"font-medium text-sm",children:v.label}),e.jsx("div",{className:"text-xs opacity-60 mt-0.5",children:v.desc})]},v.path)})}),t&&e.jsxs("div",{className:"mt-8 text-center text-xs text-[var(--fg-muted)]",children:[t.generatedAt&&`${n("wiki.lastGenerated")}: ${new Date(t.generatedAt).toLocaleString()}`,t.duration!=null&&` · ${n("wiki.duration")} ${Kr(t.duration)}`,t.version&&` · v${t.version}`]})]})},tc=()=>{const{t}=Me(),[s,a]=l.useState({task:{status:"idle"}}),[r,o]=l.useState([]),[n,d]=l.useState(!1),[u,c]=l.useState(null),[x,v]=l.useState(""),[g,m]=l.useState(!1),[i,f]=l.useState(!0),[j,C]=l.useState(""),[I,D]=l.useState(null),$=l.useRef(null),O=l.useCallback(async()=>{try{const b=await ne.wikiStatus();return a(b),b}catch{return null}},[]),T=l.useCallback(async()=>{try{const b=await ne.wikiFiles();o(b.files||[]),d(b.exists)}catch{}},[]),Z=l.useCallback(async()=>{try{const b=await ne.wikiFileContent("meta.json");b!=null&&b.content&&D(JSON.parse(b.content))}catch{}},[]);l.useEffect(()=>{(async()=>{f(!0),await Promise.all([O(),T(),Z()]),f(!1)})()},[O,T,Z]),l.useEffect(()=>{if(s.task.status==="running"){let b=0;$.current=setInterval(async()=>{const h=await O();b++,b%3===0&&await T(),h&&h.task.status!=="running"&&(await Promise.all([T(),Z()]),$.current&&clearInterval($.current))},1500)}else $.current&&clearInterval($.current);return()=>{$.current&&clearInterval($.current)}},[s.task.status,O,T,Z]);const W=async()=>{try{await ne.wikiUpdate(),a(b=>({...b,task:{...b.task,status:"running",progress:0,message:t("wiki.incrementalUpdating")}}))}catch(b){console.error("Wiki update failed:",b)}},M=async b=>{if(b!=="meta.json"){c(b),m(!0);try{const h=await ne.wikiFileContent(b);v(h.content)}catch{v(`# ${t("wiki.loadFailed")}
124
+
125
+ ${t("wiki.loadFailedDesc")}`)}finally{m(!1)}}},F=()=>{c(null),v("")},k=l.useMemo(()=>r.filter(b=>b.path!=="meta.json"),[r]),E=l.useMemo(()=>Yi(k,I==null?void 0:I.files),[k,I]);if(i)return e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx(Pe,{size:K.xl,className:"text-blue-500 animate-spin"})});const B=!n&&k.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(Ji,{task:s.task,wiki:s.wiki}),B?e.jsx(Zi,{}):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(Pe,{size:16,className:"text-blue-600 animate-spin relative"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium text-blue-800",children:t("wiki.wikiGenerating")}),s.task.message&&e.jsx("span",{className:"text-xs text-blue-500 ml-2 truncate",children:s.task.message})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("div",{className:"w-24 bg-blue-100 rounded-full h-1.5",children:e.jsx("div",{className:"bg-blue-500 h-1.5 rounded-full transition-all duration-700 ease-out",style:{width:`${Math.max(s.task.progress||0,3)}%`}})}),e.jsxs("span",{className:"text-xs font-mono text-blue-600 w-8 text-right",children:[s.task.progress||0,"%"]})]})]}),e.jsxs("div",{className:"flex gap-4 flex-1 min-h-0 overflow-hidden",children:[e.jsxs("div",{className:`w-64 flex-shrink-0 bg-[var(--bg-surface)] border border-[var(--border-default)] rounded-xl flex flex-col overflow-hidden ${u?"hidden lg:flex":""}`,children:[e.jsxs("div",{className:"px-3 pt-3 pb-2 border-b border-[var(--border-default)] shrink-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qe,{size:16,className:"text-blue-500"}),e.jsx("span",{className:"text-sm font-semibold text-[var(--fg-primary)]",children:"Wiki"}),(I==null?void 0:I.version)&&e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)]",children:["v",I.version]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[n&&e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)]",children:t("wiki.fileCount",{count:k.length})}),s.task.status!=="running"&&n&&e.jsx("button",{onClick:W,title:t("wiki.incrementalUpdate"),className:"p-1 rounded-md text-blue-500 hover:bg-blue-50 transition-colors",children:e.jsx(jt,{size:13})})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Ct,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-[var(--fg-muted)]"}),e.jsx("input",{type:"text",placeholder:t("wiki.searchPlaceholder"),value:j,onChange:b=>C(b.target.value),className:"w-full pl-8 pr-3 py-2 text-sm bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-200 focus:border-blue-300 transition-all"})]})]}),e.jsxs("div",{className:"p-2 overflow-y-auto flex-1 min-h-0 scrollbar-light",children:[e.jsx(Qi,{tree:E,selectedFile:u,onSelect:M,searchQuery:j}),s.task.status==="running"&&e.jsxs("div",{className:"mx-2 mt-3 mb-1 flex items-center gap-2 px-3 py-2 bg-blue-50 border border-blue-100 rounded-lg",children:[e.jsx(Pe,{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")})]})]}),(I==null?void 0:I.generatedAt)&&e.jsx("div",{className:"px-3 py-2 border-t border-[var(--border-default)] shrink-0",children:e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] text-[var(--fg-muted)]",children:[e.jsx(it,{size:10}),e.jsx("span",{children:Vi(I.generatedAt)}),I.duration!=null&&e.jsxs("span",{children:["· ",Kr(I.duration)]})]})})]}),e.jsx("div",{className:`flex-1 bg-[var(--bg-surface)] border border-[var(--border-default)] rounded-xl overflow-hidden flex flex-col min-h-0 ${u?"":"hidden lg:flex"}`,children:u?e.jsx(Xi,{filePath:u,content:x,loading:g,meta:I,onBack:F}):e.jsx(ec,{meta:I,onSelectFile:M,isGenerating:s.task.status==="running",progress:s.task.progress,message:s.task.message})})]})]})]})},sc={authority:0,guardUsageCount:0,humanUsageCount:0,aiUsageCount:0,lastUsedAt:null,authorityScore:0},ac=({editingRecipe:t,setEditingRecipe:s,handleSaveRecipe:a,closeRecipeEdit:r,isSavingRecipe:o=!1})=>{var m,i,f,j,C,I,D,$,O,T,Z,W,M,F,k,E,B;const{t:n}=Me(),[d,u]=l.useState("preview"),c=l.useRef(!0);l.useEffect(()=>()=>{c.current=!1},[]);const x=(()=>{const b=(t.language||"").toLowerCase();return["objectivec","objc","objective-c","obj-c"].includes(b)?"objectivec":t.language||"text"})(),v=async b=>{try{if(await ne.setRecipeAuthority(t.name,b),c.current){const h=t.stats?{...t.stats,authority:b}:{...sc,authority:b};s({...t,stats:h})}}catch(h){console.warn(n("recipeEditor.authorityFailed"),h==null?void 0:h.message)}},g=b=>{if(!b)return"";const h=typeof b=="string"?new Date(b).getTime():b;return isNaN(h)?"":new Date(h).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-black/20 dark:bg-black/40 backdrop-blur-sm"}),e.jsxs("div",{className:"relative bg-[var(--bg-surface)] w-full max-w-6xl rounded-2xl shadow-2xl flex flex-col h-[85vh]",children:[e.jsxs("div",{className:"p-6 border-b border-[var(--border-default)] flex justify-between items-center flex-wrap gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h2",{className:"text-xl font-bold",children:n("recipeEditor.title")}),t.kind&&(()=>{const h={rule:{label:"Rule",color:"text-red-700",bg:"bg-red-50",border:"border-red-200",icon:mt},pattern:{label:"Pattern",color:"text-violet-700",bg:"bg-violet-50",border:"border-violet-200",icon:Ut},fact:{label:"Fact",color:"text-cyan-700",bg:"bg-cyan-50",border:"border-cyan-200",icon:Qe}}[t.kind];if(!h)return null;const L=h.icon;return e.jsxs("span",{className:`text-[10px] font-bold px-2 py-1 rounded uppercase flex items-center gap-1 border ${h.bg} ${h.color} ${h.border}`,children:[e.jsx(L,{size:K.sm}),h.label]})})(),t.status&&t.status!=="active"&&t.status!=="published"&&e.jsx("span",{className:`text-[10px] font-bold px-2 py-1 rounded uppercase border ${t.status==="draft"?"bg-[var(--bg-subtle)] text-[var(--fg-muted)] border-[var(--border-default)]":t.status==="archived"?"bg-orange-50 text-orange-600 border-orange-200":"bg-[var(--bg-subtle)] text-[var(--fg-muted)] border-[var(--border-default)]"}`,children:t.status})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-medium text-[var(--fg-muted)]",children:n("recipeEditor.authorityScore")}),d==="preview"?e.jsx("span",{className:"text-sm text-[var(--fg-primary)]",children:((m=t.stats)==null?void 0:m.authority)??3}):e.jsx(lt,{value:String(((i=t.stats)==null?void 0:i.authority)??3),onChange:b=>v(parseInt(b)),options:[{value:"1",label:`1 - ${n("recipeEditor.qualityLevels.basic")}`,icon:"⭐"},{value:"2",label:`2 - ${n("recipeEditor.qualityLevels.good")}`,icon:"⭐⭐"},{value:"3",label:`3 - ${n("recipeEditor.qualityLevels.solid")}`,icon:"⭐⭐⭐"},{value:"4",label:`4 - ${n("recipeEditor.qualityLevels.great")}`,icon:"⭐⭐⭐⭐"},{value:"5",label:`5 - ${n("recipeEditor.qualityLevels.excellent")}`,icon:"⭐⭐⭐⭐⭐"}],size:"xs",className:"font-bold text-amber-600 bg-amber-50 border-amber-100"})]}),e.jsxs("div",{className:"flex bg-[var(--bg-subtle)] p-1 rounded-lg mr-4",children:[e.jsxs("button",{onClick:()=>u("preview"),className:`px-4 py-1.5 rounded-md text-xs font-bold transition-all flex items-center gap-2 ${d==="preview"?"bg-[var(--bg-surface)] shadow-sm text-[var(--accent)]":"text-[var(--fg-muted)]"}`,children:[e.jsx(Es,{size:K.sm})," ",n("recipeEditor.preview")]}),e.jsxs("button",{onClick:()=>u("edit"),className:`px-4 py-1.5 rounded-md text-xs font-bold transition-all flex items-center gap-2 ${d==="edit"?"bg-[var(--bg-surface)] shadow-sm text-[var(--accent)]":"text-[var(--fg-muted)]"}`,children:[e.jsx($t,{size:K.sm})," ",n("recipeEditor.edit")]})]}),e.jsx("button",{onClick:r,className:"p-2 hover:bg-[var(--bg-subtle)] rounded-full",children:e.jsx(Xe,{size:K.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:d==="edit"?e.jsxs("div",{className:"flex-1 overflow-y-auto space-y-5 pr-1",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-[var(--fg-muted)] uppercase mb-1",children:n("recipeEditor.path")}),e.jsx("input",{className:"w-full p-2 bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-lg text-sm",value:t.name,onChange:b=>s({...t,name:b.target.value})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-[var(--fg-muted)] uppercase mb-1",children:n("recipeEditor.description")}),e.jsx("textarea",{className:"w-full px-3 py-2 text-sm border border-[var(--border-default)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)] resize-none",rows:2,value:t.description||"",onChange:b=>s({...t,description:b.target.value}),placeholder:n("recipeEditor.descPlaceholder")})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-bold text-[var(--fg-muted)] uppercase mb-1.5 flex items-center gap-1.5",children:[e.jsx(ft,{size:11,className:"text-blue-400"})," ",n("recipeEditor.markdown")]}),e.jsx("div",{className:"border border-[var(--border-default)] rounded-lg overflow-hidden",style:{minHeight:180},children:e.jsx(Ls,{value:((f=t.content)==null?void 0:f.markdown)||"",onChange:b=>s({...t,content:{...t.content,markdown:b}}),language:"markdown",height:"180px",showLineNumbers:!0})})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-xs font-bold text-[var(--fg-muted)] uppercase mb-1.5 flex items-center gap-1.5",children:[e.jsx(Yt,{size:11,className:"text-emerald-500"})," ",n("recipeEditor.code")]}),e.jsx("div",{className:"border border-[var(--border-default)] rounded-lg overflow-hidden",style:{minHeight:180},children:e.jsx(Ls,{value:((j=t.content)==null?void 0:j.pattern)||"",onChange:b=>s({...t,content:{...t.content,pattern:b}}),language:x,height:"180px",showLineNumbers:!0})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-[var(--fg-muted)] uppercase mb-1",children:n("recipeEditor.rationale")}),e.jsx("textarea",{className:"w-full px-3 py-2 text-sm border border-[var(--border-default)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)] resize-y",rows:3,value:((C=t.content)==null?void 0:C.rationale)||"",onChange:b=>s({...t,content:{...t.content,rationale:b.target.value}}),placeholder:n("recipeEditor.rationalePlaceholder")})]})]}):e.jsxs("div",{className:"flex-1 overflow-y-auto space-y-6 scrollbar-light",children:[(()=>{const b=[["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?g(t.updatedAt):void 0]].filter(([,h])=>!!h);return b.length===0?null:e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-2xl p-6",children:[e.jsx("h3",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase tracking-widest mb-4",children:"Recipe Metadata"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-y-4 gap-x-8",children:b.map(([h,L])=>e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] font-bold uppercase mb-1",children:h}),e.jsx("span",{className:"text-sm text-[var(--fg-primary)] break-all font-medium",children:L})]},h))})]})})(),t.description&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-[var(--border-default)] p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:n("recipeEditor.description")}),e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] leading-relaxed",children:t.description})]}),((I=t.content)==null?void 0:I.markdown)&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-blue-100 p-6",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-3 block flex items-center gap-1.5",children:[e.jsx(ft,{size:11,className:"text-blue-400"})," ",n("recipeEditor.markdown")]}),e.jsx("div",{className:"bg-blue-50/30 border border-blue-100 rounded-xl p-4",children:e.jsx("div",{className:"markdown-body text-sm text-[var(--fg-primary)] leading-relaxed",children:e.jsx(Et,{content:t.content.markdown})})})]}),((D=t.content)==null?void 0:D.pattern)&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-emerald-100 p-6",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-3 block flex items-center gap-1.5",children:[e.jsx(Yt,{size:11,className:"text-emerald-500"})," ",n("recipeEditor.code")]}),e.jsx(St,{code:t.content.pattern,language:x,showLineNumbers:!0})]}),(($=t.content)==null?void 0:$.rationale)&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-[var(--border-default)] p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:n("recipeEditor.rationale")}),e.jsx("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-xl p-4",children:e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] leading-relaxed",children:t.content.rationale})})]}),((O=t.content)==null?void 0:O.steps)&&t.content.steps.length>0&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-[var(--border-default)] p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:n("recipeEditor.steps")}),e.jsx("div",{className:"space-y-2",children:t.content.steps.map((b,h)=>typeof b=="string"?e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-lg p-3 border border-[var(--border-default)] flex items-start gap-2.5",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0 mt-0.5",children:h+1}),e.jsx("p",{className:"text-xs text-[var(--fg-primary)] leading-relaxed",children:b})]},h):e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-lg p-3 border border-[var(--border-default)]",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-[10px] font-bold text-blue-600 bg-blue-50 rounded-full w-5 h-5 flex items-center justify-center shrink-0",children:h+1}),b.title&&e.jsx("span",{className:"text-xs font-bold text-[var(--fg-primary)]",children:b.title})]}),b.description&&e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] ml-7 leading-relaxed",children:b.description}),b.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:b.code})]},h))})]}),((T=t.content)==null?void 0:T.codeChanges)&&t.content.codeChanges.length>0&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-[var(--border-default)] p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:n("recipeEditor.codeChanges")}),e.jsx("div",{className:"space-y-2",children:t.content.codeChanges.map((b,h)=>e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-3 py-1.5 bg-[var(--bg-subtle)] border-b border-[var(--border-default)] flex items-center gap-2",children:[e.jsx(Tt,{size:11,className:"text-blue-400"}),e.jsx("code",{className:"text-[10px] font-mono text-[var(--fg-secondary)]",children:b.file})]}),b.explanation&&e.jsx("p",{className:"text-[11px] text-[var(--fg-muted)] px-3 py-1.5 border-b border-[var(--border-default)] bg-yellow-50/30",children:b.explanation}),e.jsxs("div",{className:"p-2 bg-red-50/20 border-b border-[var(--border-default)]",children:[e.jsx("div",{className:"text-[9px] font-bold text-red-400 mb-0.5 uppercase",children:"Before"}),e.jsx("pre",{className:"text-[11px] text-[var(--fg-secondary)] whitespace-pre-wrap break-words font-mono",children:b.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-[var(--fg-primary)] whitespace-pre-wrap break-words font-mono",children:b.after})]})]},h))})]}),((Z=t.content)==null?void 0:Z.verification)&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-teal-100 p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:n("recipeEditor.validation")}),e.jsxs("div",{className:"bg-teal-50/50 border border-teal-100 rounded-xl p-4 space-y-1.5",children:[t.content.verification.method&&e.jsxs("p",{className:"text-xs text-[var(--fg-secondary)]",children:[e.jsx("span",{className:"font-bold text-teal-600",children:n("recipeEditor.validationMethod")})," ",t.content.verification.method]}),t.content.verification.expectedResult&&e.jsxs("p",{className:"text-xs text-[var(--fg-secondary)]",children:[e.jsx("span",{className:"font-bold text-teal-600",children:n("recipeEditor.validationExpected")})," ",t.content.verification.expectedResult]}),t.content.verification.testCode&&e.jsx("pre",{className:"text-[11px] font-mono bg-slate-800 text-green-300 p-2.5 rounded-md overflow-x-auto whitespace-pre-wrap mt-1",children:t.content.verification.testCode})]})]}),t.tags&&t.tags.length>0&&e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-2xl p-6",children:[e.jsxs("h3",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase tracking-widest mb-3 flex items-center gap-1.5",children:[e.jsx(mr,{size:11,className:"text-blue-400"})," ",n("recipeEditor.tags")]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.tags.map((b,h)=>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:b},h))})]}),!!(t.constraints&&((W=t.constraints.guards)!=null&&W.length||(M=t.constraints.boundaries)!=null&&M.length||(F=t.constraints.preconditions)!=null&&F.length||(k=t.constraints.sideEffects)!=null&&k.length))&&e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-2xl p-6 space-y-4",children:[e.jsxs("h3",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase tracking-widest flex items-center gap-1.5",children:[e.jsx(mt,{size:11,className:"text-amber-500"})," ",n("recipeEditor.constraints")]}),t.constraints.guards&&t.constraints.guards.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-[var(--fg-muted)] block mb-1.5",children:n("recipeEditor.guardRules")}),e.jsx("ul",{className:"text-sm text-[var(--fg-secondary)] space-y-1",children:t.constraints.guards.map((b,h)=>e.jsxs("li",{className:"flex gap-2 items-start",children:[e.jsx("span",{className:`text-xs mt-0.5 ${b.severity==="error"?"text-red-500":"text-yellow-500"}`,children:"●"}),e.jsx("code",{className:"font-mono text-xs bg-[var(--bg-subtle)] px-1.5 py-0.5 rounded",children:b.pattern}),b.message&&e.jsxs("span",{className:"text-xs text-[var(--fg-muted)]",children:["— ",b.message]})]},h))})]}),t.constraints.boundaries&&t.constraints.boundaries.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-[var(--fg-muted)] block mb-1.5",children:n("recipeEditor.boundaryConstraints")}),e.jsx("ul",{className:"text-sm text-[var(--fg-secondary)] space-y-1",children:t.constraints.boundaries.map((b,h)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-orange-400",children:"●"}),b]},h))})]}),t.constraints.preconditions&&t.constraints.preconditions.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-[var(--fg-muted)] block mb-1.5",children:n("recipeEditor.preconditions")}),e.jsx("ul",{className:"text-sm text-[var(--fg-secondary)] space-y-1",children:t.constraints.preconditions.map((b,h)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-blue-400",children:"◆"}),b]},h))})]}),t.constraints.sideEffects&&t.constraints.sideEffects.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-semibold text-[var(--fg-muted)] block mb-1.5",children:n("recipeEditor.sideEffects")}),e.jsx("ul",{className:"text-sm text-[var(--fg-secondary)] space-y-1",children:t.constraints.sideEffects.map((b,h)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-pink-400",children:"⚡"}),b]},h))})]})]}),t.relations&&Object.entries(t.relations).some(([,b])=>Array.isArray(b)&&b.length>0)&&e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-2xl p-6",children:[e.jsx("h3",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase tracking-widest mb-4",children:n("recipeEditor.relations")}),e.jsx("div",{className:"space-y-2",children:[{key:"inherits",label:n("recipeEditor.relationTypes.inherits"),color:"text-green-600",icon:"↑"},{key:"implements",label:n("recipeEditor.relationTypes.implements"),color:"text-blue-600",icon:"◇"},{key:"calls",label:n("recipeEditor.relationTypes.calls"),color:"text-cyan-600",icon:"→"},{key:"dependsOn",label:n("recipeEditor.relationTypes.dependsOn"),color:"text-yellow-600",icon:"⊕"},{key:"dataFlow",label:n("recipeEditor.relationTypes.dataFlow"),color:"text-purple-600",icon:"⇢"},{key:"conflicts",label:n("recipeEditor.relationTypes.conflicts"),color:"text-red-600",icon:"✕"},{key:"extends",label:n("recipeEditor.relationTypes.extends"),color:"text-teal-600",icon:"⊃"},{key:"related",label:n("recipeEditor.relationTypes.associates"),color:"text-[var(--fg-muted)]",icon:"∼"}].map(({key:b,label:h,color:L,icon:ie})=>{var ge;const Y=(ge=t.relations)==null?void 0:ge[b];return!Y||!Array.isArray(Y)||Y.length===0?null:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("span",{className:`text-xs font-mono ${L} shrink-0 whitespace-nowrap pt-0.5`,children:[ie," ",h]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:Y.map((Ne,fe)=>e.jsx("span",{className:"px-2 py-0.5 bg-[var(--bg-surface)] border border-[var(--border-default)] text-[var(--fg-secondary)] rounded-lg text-xs font-mono",children:typeof Ne=="string"?Ne:Ne.id||Ne.title||JSON.stringify(Ne)},fe))})]},b)})})]}),!((E=t.content)!=null&&E.markdown)&&!((B=t.content)!=null&&B.pattern)&&!t.description&&e.jsx("div",{className:"bg-[var(--bg-surface)] p-8 rounded-2xl border border-[var(--border-default)] shadow-sm min-h-[200px] flex items-center justify-center",children:e.jsx("div",{className:"text-[var(--fg-muted)] italic",children:n("recipeEditor.noContent")})})]})})}),e.jsxs("div",{className:"p-6 border-t border-[var(--border-default)] flex justify-end gap-3",children:[e.jsx("button",{onClick:r,disabled:o,className:"px-4 py-2 text-[var(--fg-secondary)] font-medium disabled:opacity-50",children:n("recipeEditor.cancel")}),e.jsxs("button",{onClick:a,disabled:o,className:"px-6 py-2 bg-blue-600 text-white rounded-lg font-medium flex items-center gap-2 hover:bg-blue-700 disabled:opacity-60 disabled:cursor-not-allowed",children:[o?e.jsx(Pe,{size:K.lg,className:"animate-spin"}):e.jsx(Ms,{size:K.lg}),n(o?"recipeEditor.saving":"recipeEditor.saveChanges")]})]})]})]})},rc=({setShowCreateModal:t,createPath:s,setCreatePath:a,handleCreateFromPath:r,handleCreateFromClipboard:o,isExtracting:n})=>{const{t:d}=Me();return e.jsxs(Ze,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx(Ze.Backdrop,{className:"bg-black/20 dark:bg-black/40 backdrop-blur-sm"}),e.jsxs("div",{className:"relative w-full max-w-lg rounded-2xl shadow-2xl overflow-hidden bg-[var(--bg-surface)]",children:[e.jsxs("div",{className:"p-6 border-b flex justify-between items-center bg-[var(--bg-subtle)] border-[var(--border-default)]",children:[e.jsxs("h2",{className:"text-xl font-bold flex items-center gap-2 text-[var(--fg-primary)]",children:[e.jsx(kt,{size:K.xl,className:"text-blue-600"})," ",d("createModal.title")]}),e.jsx("button",{onClick:()=>t(!1),className:"p-2 rounded-full transition-all duration-150 text-[var(--fg-muted)] hover:bg-[var(--bg-subtle)] hover:text-[var(--fg-primary)]",children:e.jsx(Xe,{size:K.lg})})]}),e.jsxs("div",{className:"p-8 space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs font-bold uppercase tracking-widest text-[var(--fg-muted)]",children:[e.jsx(Us,{size:K.sm})," ",d("createModal.importFromPath")]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:"flex-1 p-3 rounded-xl text-sm outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)] border bg-[var(--bg-subtle)] border-[var(--border-default)] text-[var(--fg-primary)]",placeholder:d("createModal.pathPlaceholder"),value:s,onChange:u=>a(u.target.value)}),e.jsxs("button",{onClick:r,disabled:!s||n,className:"px-5 py-2 rounded-xl text-sm font-bold whitespace-nowrap disabled:opacity-40 transition-all duration-150 bg-[var(--accent)] text-white hover:opacity-90 shadow-sm",children:[e.jsx(Us,{size:14,className:"inline -mt-0.5 mr-1"}),d("createModal.scanFile")]})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("div",{className:"w-full border-t border-[var(--border-default)]"})}),e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"px-2 font-bold bg-[var(--bg-surface)] text-[var(--fg-muted)]",children:d("createModal.or")})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs font-bold uppercase tracking-widest text-[var(--fg-muted)]",children:[e.jsx(Kn,{size:K.sm})," ",d("createModal.importFromClipboard")]}),e.jsxs("button",{onClick:()=>o(),disabled:n,className:"w-full flex items-center justify-center gap-3 p-4 rounded-xl font-bold transition-all duration-150 border bg-[var(--accent-subtle)] text-[var(--accent)] border-[var(--accent-emphasis)]/20 hover:bg-[var(--accent-emphasis)]/10",children:[e.jsx(et,{size:K.lg})," ",d("createModal.useClipboard")]})]})]}),n&&e.jsxs("div",{className:"bg-blue-600 text-white p-4 flex items-center justify-center gap-3 animate-pulse",children:[e.jsx(ps,{size:K.lg,className:"animate-spin"}),e.jsx("span",{className:"font-bold text-sm",children:d("createModal.aiThinking")})]})]})]})};function nc(t){if(!t)return"";if(typeof t=="object"){const o=t.code||t.pattern||t.markdown||t.snippet||t.body||"";if(o)return o}const a=(typeof t=="string"?t:JSON.stringify(t)).replace(/^---[\s\S]*?---\s*\n?/,"").trim(),r=a.match(/```[\w]*\n([\s\S]*?)```/);return r&&r[1]?r[1].trim():a.slice(0,8e3)}const lc=({searchQ:t,insertPath:s,onClose:a})=>{const{t:r}=Me(),[o,n]=l.useState([]),[d,u]=l.useState(!0),[c,x]=l.useState(null),v=l.useRef(!0),g=l.useRef(null);l.useEffect(()=>(v.current=!0,g.current=new AbortController,ne.search(t||"",{mode:"bm25",type:"recipe",signal:g.current.signal}).then(i=>{v.current&&n((i.items||[]).map(f=>({name:(f.title||f.name||"")+".md",path:"",content:f.content,qualityScore:(f.quality||{}).overall||f.qualityScore||0,recommendReason:""})))}).catch(i=>{i.name!=="AbortError"&&v.current&&n([])}).finally(()=>{v.current&&u(!1)}),()=>{v.current=!1,g.current&&g.current.abort()}),[t]);const m=async i=>{x(i.name);try{const f=nc(i.content);await ne.insertAtSearchMark({path:s,content:f}),v.current&&(alert(r("searchModal.insertSuccess")+" "+s),a())}catch{v.current&&alert(r("searchModal.insertFailed"))}finally{v.current&&x(null)}};return e.jsxs(Ze,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx(Ze.Backdrop,{className:"bg-black/20 dark:bg-black/40 backdrop-blur-sm"}),e.jsxs("div",{className:"relative bg-[var(--bg-surface)] w-full max-w-2xl rounded-2xl shadow-2xl overflow-hidden flex flex-col max-h-[85vh]",children:[e.jsxs("div",{className:"p-6 border-b border-[var(--border-default)] flex justify-between items-center bg-[var(--bg-subtle)]",children:[e.jsxs("h2",{className:"text-xl font-bold flex items-center gap-2 text-[var(--fg-primary)]",children:[e.jsx(Ct,{size:K.xl,className:"text-blue-600"})," ",r("searchModal.title")]}),e.jsx("button",{onClick:a,className:"p-2 hover:bg-[var(--bg-surface)] rounded-full transition-colors",children:e.jsx(Xe,{size:K.lg})})]}),e.jsxs("div",{className:"p-4 text-sm text-[var(--fg-muted)] border-b border-[var(--border-default)]",children:[r("searchModal.keyword")," ",t||r("searchModal.keywordAll")," · ",r("searchModal.insertTo")," ",s]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:d?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"})}):o.length===0?e.jsx("div",{className:"text-[var(--fg-muted)] text-center py-8",children:r("searchModal.noResults")}):e.jsx("ul",{className:"space-y-2",children:o.map(i=>e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>m(i),disabled:c!==null,className:"w-full flex items-center justify-between gap-3 p-4 rounded-xl border border-[var(--border-default)] hover:border-[var(--accent-emphasis)] hover:bg-[var(--accent-subtle)]/50 transition-all text-left disabled:opacity-50",children:[e.jsxs("div",{className:"flex-1 flex flex-col gap-1",children:[e.jsx("span",{className:"font-medium text-[var(--fg-primary)] truncate",children:i.name}),(i.qualityScore!==void 0||i.recommendReason)&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.qualityScore!==void 0&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-blue-100 rounded text-xs text-blue-700 font-medium",children:["🤖 ",r("searchModal.quality")," ",(i.qualityScore*100).toFixed(0),"%"]}),i.recommendReason&&e.jsx("span",{className:"text-xs text-[var(--fg-secondary)] italic truncate max-w-xs",children:i.recommendReason})]})]}),c===i.name?e.jsxs("span",{className:"text-blue-600 text-sm flex items-center gap-1",children:[e.jsx("span",{className:"animate-spin",children:"⏳"})," ",r("searchModal.inserting")]}):e.jsxs("span",{className:"text-blue-600 text-sm flex items-center gap-1",children:[e.jsx(fr,{size:K.md})," ",r("searchModal.insertBtn")]})]})},i.name))})})]})]})},qs=[{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:""}],oc=({onClose:t,onSaved:s})=>{const{t:a}=Me(),[r,o]=l.useState(!0),[n,d]=l.useState(!1),[u,c]=l.useState(!1),[x,v]=l.useState("google"),[g,m]=l.useState("gemini-2.0-flash"),[i,f]=l.useState(""),[j,C]=l.useState(""),[I,D]=l.useState(!1),[$,O]=l.useState({}),[T,Z]=l.useState(!1);l.useEffect(()=>{W()},[]);const W=async()=>{o(!0);try{const h=await ne.getLlmEnvConfig();c(h.hasEnvFile);const L=h.vars||{};L.ASD_AI_PROVIDER&&v(L.ASD_AI_PROVIDER),L.ASD_AI_MODEL&&m(L.ASD_AI_MODEL),L.ASD_AI_PROXY&&C(L.ASD_AI_PROXY),O(L)}catch{}finally{o(!1)}},M=qs.find(h=>h.id===x),F=(M==null?void 0:M.keyEnv)||"",k=F?!!$[F]:!0,E=h=>{v(h);const L=qs.find(ie=>ie.id===h);L&&m(L.defaultModel),f("")},B=async()=>{if(x){if(F&&!k&&!i.trim()){alert(a("llmConfig.apiKeyRequired"));return}d(!0),Z(!1);try{await ne.saveLlmEnvConfig({provider:x,model:g||void 0,apiKey:i.trim()||void 0,proxy:j.trim()||void 0}),Z(!0),setTimeout(()=>{s(),t()},800)}catch(h){alert((h==null?void 0:h.message)||a("llmConfig.saveFailed"))}finally{d(!1)}}},b=h=>!h||h.length<10?h?"••••••":"":`${h.slice(0,6)}••••${h.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 bg-[var(--bg-surface)]",onClick:h=>h.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsx("h2",{className:"text-lg font-semibold text-[var(--fg-primary)]",children:a("llmConfig.title")}),e.jsx("button",{onClick:t,className:"p-1 rounded-lg transition-all duration-150 hover:bg-[var(--bg-subtle)] text-[var(--fg-muted)] hover:text-[var(--fg-primary)]",children:e.jsx(Xe,{size:K.md})})]}),e.jsx("div",{className:"px-6 py-5 space-y-5",children:r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Pe,{size:24,className:"animate-spin text-blue-500"})}):e.jsxs(e.Fragment,{children:[!u&&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(Bt,{size:16,className:"mt-0.5 shrink-0"}),e.jsx("span",{children:a("llmConfig.envWarning")})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-2 text-[var(--fg-primary)]",children:a("llmConfig.provider")}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:qs.map(h=>e.jsx("button",{type:"button",onClick:()=>E(h.id),className:`px-3 py-2 rounded-lg text-sm font-medium border transition-all ${x===h.id?"bg-[var(--accent-subtle)] border-[var(--accent-emphasis)] text-[var(--accent)] ring-1 ring-[var(--accent-emphasis)]/30":"bg-[var(--bg-surface)] border-[var(--border-default)] text-[var(--fg-secondary)] hover:border-[var(--border-emphasis)] hover:bg-[var(--bg-subtle)]"}`,children:a(h.labelKey)},h.id))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5 text-[var(--fg-primary)]",children:a("llmConfig.model")}),e.jsx("input",{type:"text",value:g,onChange:h=>m(h.target.value),placeholder:(M==null?void 0:M.defaultModel)||"",className:"w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)]/20 focus:border-[var(--accent-emphasis)] border-[var(--border-default)] bg-[var(--bg-subtle)] text-[var(--fg-primary)]"})]}),F&&e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium mb-1.5 text-[var(--fg-primary)]",children:[a("llmConfig.apiKey"),k&&e.jsxs("span",{className:"ml-2 text-xs text-green-600 font-normal",children:["(",a("llmConfig.configured")," ",b($[F]),")"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:I?"text":"password",value:i,onChange:h=>f(h.target.value),placeholder:a(k?"llmConfig.apiKeyPlaceholderSet":"llmConfig.apiKeyPlaceholderEmpty"),className:"w-full px-3 py-2 pr-10 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)]/20 focus:border-[var(--accent-emphasis)] border-[var(--border-default)] bg-[var(--bg-subtle)] text-[var(--fg-primary)]"}),e.jsx("button",{type:"button",onClick:()=>D(h=>!h),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-[var(--fg-muted)] hover:text-[var(--fg-secondary)]",children:I?e.jsx(qn,{size:16}):e.jsx(Es,{size:16})})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium mb-1.5 text-[var(--fg-primary)]",children:[a("llmConfig.proxy")," ",e.jsx("span",{className:"text-xs font-normal text-[var(--fg-muted)]",children:a("llmConfig.optional")})]}),e.jsx("input",{type:"text",value:j,onChange:h=>C(h.target.value),placeholder:"http://127.0.0.1:7890",className:"w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)]/20 focus:border-[var(--accent-emphasis)] border-[var(--border-default)] bg-[var(--bg-subtle)] text-[var(--fg-primary)]"})]})]})}),e.jsxs("div",{className:"flex items-center justify-end gap-3 px-6 py-4 border-t border-[var(--border-default)] bg-[var(--bg-subtle)]",children:[e.jsx("button",{onClick:t,className:"px-4 py-2 text-sm font-medium transition-colors text-[var(--fg-secondary)] hover:text-[var(--fg-primary)]",children:a("llmConfig.cancel")}),e.jsxs("button",{onClick:B,disabled:n||r||T,className:`flex items-center gap-2 px-5 py-2 rounded-lg text-sm font-medium transition-all ${T?"bg-green-500 text-white":"bg-blue-600 text-white hover:bg-blue-700 shadow-sm"} disabled:opacity-60`,children:[n?e.jsx(Pe,{size:16,className:"animate-spin"}):T?e.jsx(ms,{size:16}):e.jsx(Ms,{size:16}),a(T?"llmConfig.saved":"llmConfig.saveToEnv")]})]})]})})};class ic extends Pt.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:Ys.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:Ys.app.errorBoundary.refreshBtn})]}):this.props.children}}function ns(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 cc=()=>{var Ve,st,xa;const t=yl(),s=wl((Ve=t.user)==null?void 0:Ve.role),a=Nl(),{t:r}=Me(),o=()=>{const R=window.location.pathname.replace(/^\//,"").split("/")[0]||"";return dl.includes(R)?R:"help"},[n,d]=l.useState(null),[u,c]=l.useState(o()),[x,v]=l.useState(""),[g,m]=l.useState(!1),[i,f]=l.useState(!0),[j,C]=l.useState(null),[I,D]=l.useState([]),[$,O]=l.useState([]),[T,Z]=l.useState(null),[W,M]=l.useState(!1),[F,k]=l.useState({current:0,total:0,status:""}),[E,B]=l.useState([]),[b,h]=l.useState([]),[L,ie]=l.useState(null),[Y,ge]=l.useState(1),[Ne,fe]=l.useState(12),[w,N]=l.useState(!1),[P,U]=l.useState(""),[Q,ue]=l.useState(!1),[ce,ke]=l.useState(null),[Le,Ie]=l.useState(null),[Be,H]=l.useState(!1),[S,se]=l.useState(!0),[we,V]=l.useState(!1),[ye,Re]=l.useState(0),je=l.useRef(null),pe=l.useRef(null);l.useEffect(()=>{ge(1)},[x]),l.useEffect(()=>{if(n!=null&&n.projectRoot)try{const R=`asd:custom-folder-targets:${n.projectRoot}`,oe=localStorage.getItem(R);O(oe?JSON.parse(oe):[])}catch{O([])}},[n==null?void 0:n.projectRoot]);const _e=()=>{je.current&&je.current.abort()};l.useEffect(()=>{let R=!1;const oe=async()=>{var me,Ce,Se;try{const De=await ne.getSignalStatus();if(!R){const Ee=((me=De==null?void 0:De.suggestions)==null?void 0:me.length)||0,Ae=((Se=(Ce=De==null?void 0:De.snapshot)==null?void 0:Ce.lastResult)==null?void 0:Se.newSuggestions)||0;Re(Ee||Ae)}}catch{}};oe();const ee=setInterval(oe,300*1e3);return()=>{R=!0,clearInterval(ee)}},[]);const q=l.useRef(null);l.useEffect(()=>{if(a.isAllDone&&a.session){if(q.current!==a.session.id){q.current=a.session.id;const R=a.session.failed>0?r("bootstrap.notifyPartial",{completed:a.session.completed,total:a.session.total,failed:a.session.failed}):r("bootstrap.notifySuccess",{completed:a.session.completed});re(R,{title:r("bootstrap.coldStartComplete"),type:a.session.failed>0?"error":"success"})}G()}},[a.isAllDone,(st=a.session)==null?void 0:st.id]),l.useEffect(()=>{if(a.candidateCreatedTick>0){const R=setTimeout(()=>G(),2e3);return()=>clearTimeout(R)}},[a.candidateCreatedTick]);const y=(R,oe)=>{c(R);const ee=oe!=null&&oe.preserveSearch&&window.location.search?window.location.search:"";window.history.pushState({},document.title,`/${R}${ee}`)},p=R=>{C(R),c("recipes");const oe=new URLSearchParams(window.location.search);oe.set("edit",encodeURIComponent(R.name)),window.history.pushState({},document.title,`/recipes?${oe.toString()}`)},z=()=>{C(null),window.history.replaceState({},document.title,"/recipes")};l.useEffect(()=>{x===""&&ke(null)},[x]),l.useEffect(()=>{c(o())},[]),l.useEffect(()=>{if(!n)return;const R=window.location.pathname.replace(/^\//,"").split("/")[0],ee=new URLSearchParams(window.location.search).get("edit");if(R==="recipes"&&ee&&n.recipes)try{const me=decodeURIComponent(ee),Ce=n.recipes.find(Se=>Se.name===me);Ce&&!j&&(c("recipes"),p(Ce))}catch{}},[n]),l.useEffect(()=>{G(),A(),_();const R=()=>{c(o())};window.addEventListener("popstate",R);const oe=new URLSearchParams(window.location.search),ee=oe.get("action"),me=oe.get("path"),Ce=oe.get("q")||"";return ee==="search"&&me?Ie({q:Ce,path:me}):ee==="create"&&me&&(U(me),N(!0),oe.get("autoScan")==="1"&&setTimeout(()=>be(me),500)),ee&&window.history.replaceState({},document.title,window.location.pathname),()=>{window.removeEventListener("popstate",R)}},[]);const G=async()=>{f(!0);try{const R=await ne.fetchData();d(R)}catch(R){re((R==null?void 0:R.message)||r("app.load.failed"),{title:r("app.load.failedTitle"),type:"error"})}finally{f(!1)}},A=async()=>{try{const R=await ne.fetchTargets();D(R)}catch(R){console.warn("删除候选残留失败:",R==null?void 0:R.message)}},_=async()=>{try{const R=await ne.getLlmEnvConfig();se(R.llmReady)}catch{}},J=async()=>{try{await ne.syncSnippets("all"),re(r("app.sync.success"),{title:r("app.sync.successTitle")})}catch{re(r("app.sync.failedHint"),{title:r("app.sync.failed"),type:"error"})}},ae=async()=>{try{await ne.refreshProject(),A(),re(r("app.projectRefresh.success"),{title:r("app.projectRefresh.successTitle")})}catch{re(r("app.load.failedHint"),{title:r("app.projectRefresh.failed"),type:"error"})}},be=async R=>{var oe;ue(!0);try{const ee=await ne.extractFromPath(R);h(ee.result.map(me=>({...ns(me,"extract"),mode:"full",lang:"cn"}))),y("spm"),N(!1),G(),((oe=ee.result)==null?void 0:oe.length)>0&&re(r("app.extract.success"),{title:r("app.extract.successTitle")})}catch{re(r("app.extract.failed"),{type:"error"})}finally{ue(!1)}},X=async()=>{var R;if(P){ue(!0);try{const oe=await ne.extractFromPath(P);h(oe.result.map(ee=>({...ns(ee,"extract"),mode:"full",lang:"cn"}))),y("spm"),N(!1),G(),((R=oe.result)==null?void 0:R.length)>0?re(oe.isMarked?r("app.extract.markerSuccess"):r("app.extract.normalSuccess"),{title:r("app.extract.successTitle")}):oe.isMarked||re(r("app.extract.noMarker"),{title:r("app.extract.extracting"),type:"info"})}catch{re(r("app.extract.failed"),{type:"error"})}finally{ue(!1)}}},xe=async R=>{var oe,ee,me,Ce;try{const Se=await navigator.clipboard.readText();if(!Se)return re(r("app.clipboard.empty"),{title:r("app.clipboard.emptyTitle"),type:"info"});re(r("app.clipboard.analyzing"),{title:r("app.clipboard.analyzingTitle"),type:"info"}),ue(!0);const De=R||P;try{const Ee=await ne.extractFromText(Se,De||void 0),Ae=Ee._multipleCount;h([{...ns(Ee,"clipboard"),mode:"full",lang:"cn"}]),y("spm"),N(!1),G(),re(Ae?r("app.clipboard.resultMulti",{count:Ae}):r("app.extract.normalSuccess"),{title:r("app.clipboard.resultTitle")})}catch(Ee){const Ae=((ee=(oe=Ee.response)==null?void 0:oe.data)==null?void 0:ee.aiError)===!0,Ge=((Ce=(me=Ee.response)==null?void 0:me.data)==null?void 0:Ce.error)||Ee.message;Ae?re(Ge,{title:r("app.clipboard.aiFailed"),type:"error"}):re(Ge,{title:r("common.operationFailed"),type:"error"})}}catch{re(r("app.clipboard.permissionError"),{title:r("app.clipboard.permissionTitle"),type:"error"})}finally{ue(!1)}},he={"scan:started":{percent:5,status:r("app.scan.events.initializing")},"scan:files-loaded":{percent:15,status:R=>r("app.scan.events.filesLoaded",{count:R.count||0})},"scan:reading":{percent:25,status:R=>r("app.scan.events.readingFiles",{count:R.count||0})},"scan:ai-extracting":{percent:40,status:r("app.scan.events.aiAnalyzing")},"scan:enriching":{percent:85,status:R=>r("app.scan.events.enriching",{count:R.recipeCount||0})},"scan:completed":{percent:95,status:r("app.scan.events.completing")}},Fe=async R=>{var ee;if(W)return;je.current&&je.current.abort(),pe.current&&(clearInterval(pe.current),pe.current=null);const oe=new AbortController;je.current=oe,Z(R.name),M(!0),h([]),ie(null),B([]),k({current:0,total:100,status:r("app.scan.streamInit")});try{const me=await ne.scanTargetStream(R,De=>{const Ee=he[De.type];if(Ee){const Ae=typeof Ee.status=="function"?Ee.status(De):Ee.status;k({current:Ee.percent,total:100,status:Ae})}De.type==="scan:files-loaded"&&De.files&&B(De.files),De.type==="scan:ai-extracting"&&(pe.current&&clearInterval(pe.current),pe.current=setInterval(()=>{k(Ae=>({...Ae,current:Math.min(Ae.current+1,80)}))},3e3)),(De.type==="scan:enriching"||De.type==="scan:completed")&&pe.current&&(clearInterval(pe.current),pe.current=null)},oe.signal);pe.current&&(clearInterval(pe.current),pe.current=null),k({current:100,total:100,status:r("app.scan.completed")});const Ce=me.recipes||[],Se=me.scannedFiles||[];if(Ce.length>0||Se.length>0){const De=typeof R=="string"?R:(R==null?void 0:R.name)||"unknown",Ee=Ce.map(Ae=>({...ns(Ae,"ai-scan"),mode:"full",lang:"cn",candidateTargetName:De,scanMode:"target"}));if(h(Ee),Se.length>0&&B(Se),G(),Ce.length>0)re(r("app.scan.targetSuccess",{count:Ce.length}),{title:r("app.scan.targetSuccessTitle")});else if(me.message){const Ae=me.noAi;re(me.message,{title:r(Ae?"app.scan.aiNotConfigured":"app.scan.noResults"),type:Ae?"info":"error"})}else re(r("app.scan.noSnippets"),{title:r("app.scan.scanComplete"),type:"info"})}else re(r("app.scan.scanFailedHint"),{title:r("app.scan.scanFailed"),type:"error"})}catch(me){if(pe.current&&(clearInterval(pe.current),pe.current=null),me.name==="AbortError")return;const Ce=(ee=me.message)==null?void 0:ee.includes("timeout"),Se=Ce?r("app.scan.timeout"):me.message||r("app.scan.scanError");re(Se,{title:r(Ce?"app.scan.timeoutTitle":"app.scan.scanError"),type:"error"})}finally{je.current===oe&&(M(!1),k({current:0,total:0,status:""}),je.current=null)}},Oe=async()=>{var oe,ee,me,Ce,Se,De;if(W)return;je.current&&je.current.abort();const R=new AbortController;je.current=R,y("candidates"),M(!0),h([]),ie(null),B([]),k({current:0,total:100,status:r("app.coldStart.collecting")}),a.resetSession();try{const Ee=await ne.bootstrap(R.signal);k({current:100,total:100,status:r("app.coldStart.skeletonCreated")}),Ee.bootstrapSession&&a.initFromApiResponse(Ee.bootstrapSession),G();const Ae=Ee.report||{},Ge=((oe=Ee.targets)==null?void 0:oe.length)||0,pt=((ee=Ae.totals)==null?void 0:ee.files)||0,Lt=((me=Ae.totals)==null?void 0:me.graphEdges)||0,Zt=Ee.guardSummary,zs=Zt?`, ${r("app.coldStart.guardSuffix",{count:Zt.totalViolations})}`:"";re(r("app.coldStart.skeletonDetail",{targets:Ge,files:pt,deps:Lt})+zs)}catch(Ee){if(ds.isCancel(Ee))return;const Ge=Ee.code==="ECONNABORTED"||((Ce=Ee.message)==null?void 0:Ce.includes("timeout"))?r("app.coldStart.timeout"):((De=(Se=Ee.response)==null?void 0:Se.data)==null?void 0:De.error)||Ee.message;re(Ge,{type:"error"})}finally{je.current===R&&(M(!1),k({current:0,total:0,status:""}),je.current=null)}},qe=async()=>{var Ce,Se,De,Ee;if(W)return;je.current&&je.current.abort();const R=new AbortController;je.current=R,y("spm"),Z("__project__"),M(!0),h([]),ie(null),B([]),k({current:0,total:100,status:r("app.fullScan.collecting")});const oe=[{status:r("app.fullScan.phase5"),percent:5},{status:r("app.fullScan.phase15"),percent:15},{status:r("app.fullScan.phase25"),percent:25},{status:r("app.fullScan.phase35"),percent:35},{status:r("app.fullScan.phase45"),percent:45},{status:r("app.fullScan.phase55"),percent:55},{status:r("app.fullScan.phase65"),percent:65},{status:r("app.fullScan.phase75"),percent:75},{status:r("app.fullScan.phase85"),percent:85}];let ee=0;const me=setInterval(()=>{ee=Math.min(ee+1,oe.length);const Ae=oe[ee-1];Ae&&k(Ge=>({...Ge,current:Ae.percent,status:Ae.status}))},15e3);try{const Ae=await ne.scanProject(R.signal);clearInterval(me),k({current:100,total:100,status:Ae.partial?r("app.fullScan.partialComplete"):r("app.fullScan.completed")});const Ge=Ae.recipes||[],pt=Ae.scannedFiles||[];if(Ge.length>0||pt.length>0){const Lt=Ge.map(Ur=>({...ns(Ur,"ai-scan"),mode:"full",lang:"cn",candidateTargetName:"__project__",scanMode:"project"}));h(Lt),B(pt),ie(Ae.guardAudit||null),G();const Zt=(Ce=Ae.guardAudit)==null?void 0:Ce.summary,zs=Zt?`, ${r("app.fullScan.guardSuffix",{count:Zt.totalViolations})}`:"",qr=Ae.partial?r("app.fullScan.timeoutSuffix"):"";re(r("app.fullScan.resultDetail",{count:Ge.length})+zs+qr)}else re(r("app.fullScan.noContent"))}catch(Ae){if(clearInterval(me),ds.isCancel(Ae))return;const pt=Ae.code==="ECONNABORTED"||((Se=Ae.message)==null?void 0:Se.includes("timeout"))?r("app.fullScan.timeout"):((Ee=(De=Ae.response)==null?void 0:De.data)==null?void 0:Ee.error)||Ae.message;re(pt,{type:"error"})}finally{je.current===R&&(M(!1),k({current:0,total:0,status:""}),je.current=null)}},te=(R,oe)=>{const ee=[...b],me={...ee[R],...oe};ee[R]=me,h(ee)},de=async R=>{var oe;if(!Be){H(!0);try{const ee=(((oe=R.content)==null?void 0:oe.pattern)||"").trim(),me=(()=>{if(!ee)return!1;const Ge=ee.split(`
126
+ `).filter(Lt=>Lt.trim());return Ge.filter(Lt=>/^\s*(#{1,6}\s|[-*>]\s|\d+\.\s)/.test(Lt)).length<=Ge.length*.3})(),Ce=(R.trigger||"").split(/[,,\s]+/).map(Ge=>Ge.trim()).filter(Boolean);if(me&&Ce.length===0){re(r("app.recipe.triggerRequired"),{type:"error"}),H(!1);return}const Se={title:R.title||"Untitled",description:R.description||"",trigger:Ce.join(", ")||"",language:R.language||"",category:R.category||"Utility",kind:R.kind||"pattern",knowledgeType:R.knowledgeType||"code-pattern",complexity:R.complexity||"intermediate",scope:R.scope||null,difficulty:R.difficulty||"",tags:R.tags||[],source:R.source||"ai-scan",sourceFile:R.sourceFile||"",moduleName:R.moduleName||"",doClause:R.doClause||"",dontClause:R.dontClause||"",whenClause:R.whenClause||"",topicHint:R.topicHint||"",coreCode:R.coreCode||"",content:R.content||{},reasoning:R.reasoning||{},quality:R.quality||{},constraints:R.constraints||{},relations:R.relations||{},stats:R.stats||{},headers:R.headers||[],headerPaths:R.headerPaths||[],includeHeaders:R.includeHeaders||!1},De=await ne.knowledgeCreate(Se);if(De!=null&&De.id)try{await ne.knowledgeLifecycle(De.id,"publish")}catch(Ge){console.warn("auto-publish after save failed:",Ge)}re(r(me?"app.recipe.savedAsRecipe":"app.recipe.savedToKb")),h(Ge=>Ge.filter(pt=>pt.title!==R.title));const Ee=R.candidateTargetName,Ae=R.candidateId;if(Ee&&Ae)try{await ne.deleteCandidate(Ae)}catch{}G()}catch(ee){const me=Na(ee)??Ss(ee);re(me??r("app.recipe.saveFailed"),{type:"error"})}finally{H(!1)}}},Ke=async()=>{var R,oe;if(!(!j||Be)){H(!0);try{const ee=j.id||((R=j.name)==null?void 0:R.replace(/\.md$/,"")),me=typeof j.content=="string"?{pattern:j.content,markdown:"",rationale:"",steps:[],codeChanges:[],verification:null}:j.content||{};await ne.knowledgeUpdate(ee,{title:((oe=j.name)==null?void 0:oe.replace(/\.md$/,""))||"",description:j.description||"",content:me,tags:j.tags||[],kind:j.kind,language:j.language,category:j.category}),z(),G()}catch(ee){const me=Na(ee)??Ss(ee);re(me??r("app.recipe.saveRecipeFailed"),{type:"error"})}finally{H(!1)}}},He=async R=>{if(window.confirm(r("common.areYouSure")))try{await ne.deleteRecipe(R),G()}catch(oe){const ee=Ss(oe);re(ee??r("common.deleteFailed"),{type:"error"})}},Ue=async(R,oe)=>{try{await ne.deleteCandidate(oe),h(ee=>ee.filter(me=>!(me.candidateId===oe&&me.candidateTargetName===R))),d(ee=>{if(!(ee!=null&&ee.candidates))return ee;const me={...ee.candidates};if(me[R]){const Ce=me[R].items.filter(Se=>Se.id!==oe);Ce.length===0?delete me[R]:me[R]={...me[R],items:Ce}}return{...ee,candidates:me}})}catch{re(r("common.operationFailed"),{type:"error"})}},tt=async R=>{if(window.confirm(r("app.candidate.clearConfirm",{name:R})))try{await ne.deleteAllCandidatesInTarget(R),G(),re(r("app.candidate.clearDone",{name:R}))}catch{re(r("common.operationFailed"),{type:"error"})}},bt=async(R,oe)=>{var ee,me;try{await ne.promoteToCandidate(R,R.candidateTargetName||T||"_review"),re(r("app.candidate.pushSuccess")),h(Ce=>Ce.filter((Se,De)=>De!==oe)),G()}catch(Ce){const Se=(me=(ee=Ce.response)==null?void 0:ee.data)==null?void 0:me.error,De=typeof Se=="string"?Se:(Se==null?void 0:Se.message)||r("app.candidate.pushFailed");re(De,{type:"error"})}},Ye=((n==null?void 0:n.recipes)||[]).filter(R=>{var Ce,Se;if(ce)return ce.some(De=>De.metadata.type==="recipe"&&De.metadata.name===R.name);const oe=R.name||"",ee=typeof R.content=="string"?R.content:[(Ce=R.content)==null?void 0:Ce.pattern,(Se=R.content)==null?void 0:Se.markdown].filter(Boolean).join(" ");return oe.toLowerCase().includes(x.toLowerCase())||ee.toLowerCase().includes(x.toLowerCase())||(R.description||"").toLowerCase().includes(x.toLowerCase())}).sort((R,oe)=>{var Ce,Se,De,Ee;if(ce){const Ae=((Ce=ce.find(pt=>pt.metadata.name===R.name))==null?void 0:Ce.similarity)||0;return(((Se=ce.find(pt=>pt.metadata.name===oe.name))==null?void 0:Se.similarity)||0)-Ae}const ee=((De=R.stats)==null?void 0:De.authorityScore)??0;return(((Ee=oe.stats)==null?void 0:Ee.authorityScore)??0)-ee}),wt=Pt.useMemo(()=>{const R=new Set(I.map(ee=>`${ee.discovererId||""}::${ee.name}`)),oe=$.filter(ee=>!R.has(`${ee.discovererId||""}::${ee.name}`));return[...I,...oe]},[I,$]),ze=wt.filter(R=>R.name.toLowerCase().includes(x.toLowerCase())).sort((R,oe)=>{const ee=gs(R.name),me=gs(oe.name);if(ee&&!me)return 1;if(!ee&&me)return-1;const Ce=R.isVirtual?1:0,Se=oe.isVirtual?1:0;return Ce!==Se?Ce-Se:R.name.localeCompare(oe.name)}),dt=l.useCallback(R=>{O(oe=>{if(oe.some(me=>me.path===R.path))return oe;const ee=[...oe,R];return n!=null&&n.projectRoot&&localStorage.setItem(`asd:custom-folder-targets:${n.projectRoot}`,JSON.stringify(ee)),ee})},[n==null?void 0:n.projectRoot]),ut=l.useCallback(R=>{O(oe=>{const ee=oe.filter(me=>me.path!==R);return n!=null&&n.projectRoot&&localStorage.setItem(`asd:custom-folder-targets:${n.projectRoot}`,JSON.stringify(ee)),ee})},[n==null?void 0:n.projectRoot]),nt=Object.values((n==null?void 0:n.candidates)||{}).reduce((R,oe)=>R+oe.items.length,0);return e.jsx(ic,{children:e.jsx(Ol,{children:e.jsxs("div",{className:"flex h-screen bg-[var(--bg-root)] text-[var(--fg-primary)] overflow-hidden font-sans ambient-bg",children:[e.jsx(un,{position:"top-center",toastOptions:{duration:5e3,style:{background:"none",padding:0,boxShadow:"none",border:"none"}},containerStyle:{top:24}}),e.jsx(kl,{activeTab:u,navigateToTab:y,candidateCount:nt,signalSuggestionCount:ye,currentUser:s.user!=="anonymous"?s.user:void 0,currentRole:s.role,permissionMode:s.mode,onLogout:void 0,projectName:n==null?void 0:n.projectName}),e.jsxs("main",{className:"flex-1 flex flex-col overflow-hidden relative",children:[e.jsx(Zl,{setShowCreateModal:N,handleSyncSnippets:J,aiConfig:n==null?void 0:n.aiConfig,llmReady:S,onOpenLlmConfig:()=>V(!0),onBeforeAiSwitch:_e,onAiConfigChange:G,activeTab:u,onOpenCommandPalette:()=>m(!0),projectName:n==null?void 0:n.projectName,candidateCount:nt}),e.jsx("div",{className:`flex-1 ${u==="wiki"?"overflow-hidden":"overflow-y-auto p-4 xl:p-6 2xl:p-8"}`,children:e.jsx(Un,{mode:"wait",children:e.jsx(Wn.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0,transition:{duration:.2,ease:[.4,0,.2,1]}},exit:{opacity:0,transition:{duration:.15}},className:"h-full",children:i?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-[var(--accent-emphasis)]"})}):u==="recipes"?e.jsx(Ko,{recipes:Ye,openRecipeEdit:p,handleDeleteRecipe:He,onRefresh:G,idTitleMap:n==null?void 0:n.idTitleMap,currentPage:Y,onPageChange:ge,pageSize:Ne,onPageSizeChange:R=>{fe(R),ge(1)}}):u==="guard"?e.jsx(fi,{onRefresh:G}):u==="skills"?e.jsx(zi,{onRefresh:G,signalSuggestionCount:ye,onSuggestionCountChange:Re}):u==="candidates"?e.jsxs(e.Fragment,{children:[a.session&&e.jsx("div",{className:"mb-4",children:e.jsx(Ki,{session:a.session,isAllDone:a.isAllDone,reviewState:a.reviewState,onDismiss:()=>a.resetSession()})}),e.jsx(ti,{data:n,isShellTarget:gs,isSilentTarget:pl,isPendingTarget:ml,handleDeleteCandidate:Ue,onEditRecipe:p,onColdStart:Oe,isScanning:W,isBootstrapping:((xa=a.session)==null?void 0:xa.status)==="running",onRefresh:G,onAuditCandidate:(R,oe)=>{var Ce,Se;const ee=(((Ce=R.content)==null?void 0:Ce.pattern)||"").trim(),me=!!ee&&(()=>{const De=ee.split(`
127
+ `).filter(Ae=>Ae.trim());return De.filter(Ae=>/^\s*(#{1,6}\s|[-*>]\s|\d+\.\s)/.test(Ae)).length<=De.length*.3})();h([{...R,mode:me?"full":"preview",lang:"cn",includeHeaders:!0,difficulty:R.difficulty||R.complexity||"intermediate",authority:((Se=R.stats)==null?void 0:Se.authority)||3,candidateId:R.id,candidateTargetName:oe}]),y("spm")},onAuditAllInTarget:(R,oe)=>{h(R.map(ee=>{var Se,De;const me=(((Se=ee.content)==null?void 0:Se.pattern)||"").trim(),Ce=!!me&&(()=>{const Ee=me.split(`
128
+ `).filter(Ge=>Ge.trim());return Ee.filter(Ge=>/^\s*(#{1,6}\s|[-*>]\s|\d+\.\s)/.test(Ge)).length<=Ee.length*.3})();return{...ee,mode:Ce?"full":"preview",lang:"cn",includeHeaders:!0,difficulty:ee.difficulty||ee.complexity||"intermediate",authority:((De=ee.stats)==null?void 0:De.authority)||3,candidateId:ee.id,candidateTargetName:oe}})),y("spm")},handleDeleteAllInTarget:tt})]}):u==="knowledge"?e.jsx(Fi,{onRefresh:ae,idTitleMap:n==null?void 0:n.idTitleMap}):u==="depgraph"?e.jsx(hi,{}):u==="knowledgegraph"?e.jsx(Ti,{}):u==="spm"?e.jsx(di,{targets:wt,filteredTargets:ze,selectedTargetName:T,isScanning:W,scanProgress:F,scanFileList:E,scanResults:b,guardAudit:L,handleScanTarget:Fe,handleScanProject:qe,handleUpdateScanResult:te,handleSaveExtracted:de,handlePromoteToCandidate:bt,handleDeleteCandidate:Ue,onEditRecipe:p,isShellTarget:gs,recipes:(n==null?void 0:n.recipes)??[],isSavingRecipe:Be,handleRefreshProject:ae,onAddCustomFolder:dt,onRemoveCustomFolder:ut}):u==="wiki"?e.jsx(tc,{}):u==="help"?e.jsx(Vo,{}):e.jsx(yi,{})},u)})}),j&&e.jsx(ac,{editingRecipe:j,setEditingRecipe:C,handleSaveRecipe:Ke,closeRecipeEdit:z,isSavingRecipe:Be}),w&&e.jsx(rc,{setShowCreateModal:N,createPath:P,setCreatePath:U,handleCreateFromPath:X,handleCreateFromClipboard:xe,isExtracting:Q}),Le&&e.jsx(lc,{searchQ:Le.q,insertPath:Le.path,onClose:()=>{Ie(null),window.history.replaceState({},document.title,window.location.pathname)}}),we&&e.jsx(oc,{onClose:()=>V(!1),onSaved:()=>{_(),G()}})]}),e.jsx(dc,{}),e.jsx(no,{open:g,onOpenChange:m,navigateToTab:y,setShowCreateModal:N,handleSyncSnippets:J,searchQuery:x,setSearchQuery:v,onOpenLlmConfig:()=>V(!0),candidateCount:nt})]})})})},dc=()=>{const{isOpen:t}=xs();return t?e.jsx(Kl,{}):null};pn.createRoot(document.getElementById("root")).render(e.jsx(Pt.StrictMode,{children:e.jsx(el,{children:e.jsx(Qn,{children:e.jsx(cc,{})})})}));