autosnippet 3.2.11 → 3.2.12

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 (268) hide show
  1. package/README.md +1 -1
  2. package/dashboard/dist/assets/axios-42ANG6Sg.js +6 -0
  3. package/dashboard/dist/assets/framer-motion-CZfOSYpP.js +9 -0
  4. package/dashboard/dist/assets/icons-C1dUryS-.js +1 -0
  5. package/dashboard/dist/assets/index-CKMy5LY6.js +128 -0
  6. package/dashboard/dist/assets/index-D0whuycy.css +1 -0
  7. package/dashboard/dist/assets/vendor-BZEJEVBn.js +3068 -0
  8. package/dashboard/dist/index.html +6 -6
  9. package/dist/lib/core/ast/ProjectGraph.d.ts.map +1 -1
  10. package/dist/lib/core/ast/ProjectGraph.js.map +1 -1
  11. package/dist/lib/core/ast/lang-go.js.map +1 -1
  12. package/dist/lib/core/ast/lang-java.d.ts.map +1 -1
  13. package/dist/lib/core/ast/lang-java.js.map +1 -1
  14. package/dist/lib/core/ast/lang-kotlin.d.ts.map +1 -1
  15. package/dist/lib/core/ast/lang-kotlin.js.map +1 -1
  16. package/dist/lib/core/ast/lang-python.d.ts.map +1 -1
  17. package/dist/lib/core/ast/lang-python.js +4 -2
  18. package/dist/lib/core/ast/lang-python.js.map +1 -1
  19. package/dist/lib/core/ast/parser-init.d.ts.map +1 -1
  20. package/dist/lib/core/ast/parser-init.js +0 -1
  21. package/dist/lib/core/ast/parser-init.js.map +1 -1
  22. package/dist/lib/core/capability/CapabilityProbe.d.ts.map +1 -1
  23. package/dist/lib/core/capability/CapabilityProbe.js +4 -2
  24. package/dist/lib/core/capability/CapabilityProbe.js.map +1 -1
  25. package/dist/lib/domain/task/TaskIdGenerator.d.ts +2 -1
  26. package/dist/lib/domain/task/TaskIdGenerator.d.ts.map +1 -1
  27. package/dist/lib/domain/task/TaskIdGenerator.js +2 -2
  28. package/dist/lib/domain/task/TaskIdGenerator.js.map +1 -1
  29. package/dist/lib/external/ai/AiProvider.d.ts +1 -1
  30. package/dist/lib/external/ai/providers/ClaudeProvider.js +1 -1
  31. package/dist/lib/external/ai/providers/ClaudeProvider.js.map +1 -1
  32. package/dist/lib/external/ai/providers/GoogleGeminiProvider.d.ts.map +1 -1
  33. package/dist/lib/external/ai/providers/GoogleGeminiProvider.js +2 -2
  34. package/dist/lib/external/ai/providers/GoogleGeminiProvider.js.map +1 -1
  35. package/dist/lib/external/ai/providers/OpenAiProvider.js +1 -1
  36. package/dist/lib/external/ai/providers/OpenAiProvider.js.map +1 -1
  37. package/dist/lib/external/mcp/handlers/bootstrap/ExternalSubmissionTracker.d.ts.map +1 -1
  38. package/dist/lib/external/mcp/handlers/bootstrap/ExternalSubmissionTracker.js +2 -0
  39. package/dist/lib/external/mcp/handlers/bootstrap/ExternalSubmissionTracker.js.map +1 -1
  40. package/dist/lib/external/mcp/handlers/bootstrap/shared/bootstrap-phases.d.ts +1 -0
  41. package/dist/lib/external/mcp/handlers/bootstrap/shared/bootstrap-phases.d.ts.map +1 -1
  42. package/dist/lib/external/mcp/handlers/bootstrap/shared/bootstrap-phases.js +11 -1
  43. package/dist/lib/external/mcp/handlers/bootstrap/shared/bootstrap-phases.js.map +1 -1
  44. package/dist/lib/external/mcp/handlers/bootstrap-external.d.ts +4 -0
  45. package/dist/lib/external/mcp/handlers/bootstrap-external.d.ts.map +1 -1
  46. package/dist/lib/external/mcp/handlers/bootstrap-external.js +19 -2
  47. package/dist/lib/external/mcp/handlers/bootstrap-external.js.map +1 -1
  48. package/dist/lib/external/mcp/handlers/bootstrap-internal.d.ts.map +1 -1
  49. package/dist/lib/external/mcp/handlers/bootstrap-internal.js +2 -1
  50. package/dist/lib/external/mcp/handlers/bootstrap-internal.js.map +1 -1
  51. package/dist/lib/external/mcp/handlers/candidate.d.ts.map +1 -1
  52. package/dist/lib/external/mcp/handlers/candidate.js +2 -1
  53. package/dist/lib/external/mcp/handlers/candidate.js.map +1 -1
  54. package/dist/lib/external/mcp/handlers/consolidated.js +1 -1
  55. package/dist/lib/external/mcp/handlers/consolidated.js.map +1 -1
  56. package/dist/lib/external/mcp/handlers/dimension-complete-external.d.ts.map +1 -1
  57. package/dist/lib/external/mcp/handlers/dimension-complete-external.js +17 -5
  58. package/dist/lib/external/mcp/handlers/dimension-complete-external.js.map +1 -1
  59. package/dist/lib/external/mcp/handlers/guard.d.ts.map +1 -1
  60. package/dist/lib/external/mcp/handlers/guard.js +31 -24
  61. package/dist/lib/external/mcp/handlers/guard.js.map +1 -1
  62. package/dist/lib/external/mcp/handlers/knowledge.d.ts.map +1 -1
  63. package/dist/lib/external/mcp/handlers/knowledge.js +14 -10
  64. package/dist/lib/external/mcp/handlers/knowledge.js.map +1 -1
  65. package/dist/lib/external/mcp/handlers/skill.d.ts +5 -5
  66. package/dist/lib/external/mcp/handlers/skill.d.ts.map +1 -1
  67. package/dist/lib/external/mcp/handlers/skill.js +27 -28
  68. package/dist/lib/external/mcp/handlers/skill.js.map +1 -1
  69. package/dist/lib/external/mcp/handlers/structure.d.ts.map +1 -1
  70. package/dist/lib/external/mcp/handlers/structure.js +10 -7
  71. package/dist/lib/external/mcp/handlers/structure.js.map +1 -1
  72. package/dist/lib/external/mcp/handlers/system.d.ts.map +1 -1
  73. package/dist/lib/external/mcp/handlers/system.js +2 -1
  74. package/dist/lib/external/mcp/handlers/system.js.map +1 -1
  75. package/dist/lib/external/mcp/handlers/task.js +2 -2
  76. package/dist/lib/external/mcp/handlers/task.js.map +1 -1
  77. package/dist/lib/external/mcp/handlers/wiki-external.d.ts.map +1 -1
  78. package/dist/lib/external/mcp/handlers/wiki-external.js +3 -2
  79. package/dist/lib/external/mcp/handlers/wiki-external.js.map +1 -1
  80. package/dist/lib/http/HttpServer.d.ts +2 -2
  81. package/dist/lib/http/HttpServer.js +64 -64
  82. package/dist/lib/http/HttpServer.js.map +1 -1
  83. package/dist/lib/http/middleware/errorHandler.d.ts +1 -5
  84. package/dist/lib/http/middleware/errorHandler.d.ts.map +1 -1
  85. package/dist/lib/http/middleware/errorHandler.js +0 -8
  86. package/dist/lib/http/middleware/errorHandler.js.map +1 -1
  87. package/dist/lib/http/middleware/validate.d.ts +2 -2
  88. package/dist/lib/http/middleware/validate.js +2 -2
  89. package/dist/lib/http/routes/ai.d.ts.map +1 -1
  90. package/dist/lib/http/routes/ai.js +32 -33
  91. package/dist/lib/http/routes/ai.js.map +1 -1
  92. package/dist/lib/http/routes/auth.d.ts.map +1 -1
  93. package/dist/lib/http/routes/auth.js +4 -5
  94. package/dist/lib/http/routes/auth.js.map +1 -1
  95. package/dist/lib/http/routes/candidates.d.ts.map +1 -1
  96. package/dist/lib/http/routes/candidates.js +10 -11
  97. package/dist/lib/http/routes/candidates.js.map +1 -1
  98. package/dist/lib/http/routes/commands.d.ts.map +1 -1
  99. package/dist/lib/http/routes/commands.js +14 -15
  100. package/dist/lib/http/routes/commands.js.map +1 -1
  101. package/dist/lib/http/routes/extract.d.ts.map +1 -1
  102. package/dist/lib/http/routes/extract.js +4 -5
  103. package/dist/lib/http/routes/extract.js.map +1 -1
  104. package/dist/lib/http/routes/guard.d.ts.map +1 -1
  105. package/dist/lib/http/routes/guard.js +4 -5
  106. package/dist/lib/http/routes/guard.js.map +1 -1
  107. package/dist/lib/http/routes/guardRules.d.ts.map +1 -1
  108. package/dist/lib/http/routes/guardRules.js +22 -23
  109. package/dist/lib/http/routes/guardRules.js.map +1 -1
  110. package/dist/lib/http/routes/knowledge.d.ts.map +1 -1
  111. package/dist/lib/http/routes/knowledge.js +24 -25
  112. package/dist/lib/http/routes/knowledge.js.map +1 -1
  113. package/dist/lib/http/routes/modules.d.ts.map +1 -1
  114. package/dist/lib/http/routes/modules.js +26 -27
  115. package/dist/lib/http/routes/modules.js.map +1 -1
  116. package/dist/lib/http/routes/recipes.d.ts.map +1 -1
  117. package/dist/lib/http/routes/recipes.js +6 -9
  118. package/dist/lib/http/routes/recipes.js.map +1 -1
  119. package/dist/lib/http/routes/remote.d.ts.map +1 -1
  120. package/dist/lib/http/routes/remote.js +59 -33
  121. package/dist/lib/http/routes/remote.js.map +1 -1
  122. package/dist/lib/http/routes/search.d.ts.map +1 -1
  123. package/dist/lib/http/routes/search.js +16 -66
  124. package/dist/lib/http/routes/search.js.map +1 -1
  125. package/dist/lib/http/routes/skills.d.ts.map +1 -1
  126. package/dist/lib/http/routes/skills.js +14 -15
  127. package/dist/lib/http/routes/skills.js.map +1 -1
  128. package/dist/lib/http/routes/snippets.d.ts.map +1 -1
  129. package/dist/lib/http/routes/snippets.js +4 -5
  130. package/dist/lib/http/routes/snippets.js.map +1 -1
  131. package/dist/lib/http/routes/task.d.ts.map +1 -1
  132. package/dist/lib/http/routes/task.js +2 -3
  133. package/dist/lib/http/routes/task.js.map +1 -1
  134. package/dist/lib/http/routes/violations.d.ts.map +1 -1
  135. package/dist/lib/http/routes/violations.js +6 -7
  136. package/dist/lib/http/routes/violations.js.map +1 -1
  137. package/dist/lib/http/routes/wiki.d.ts.map +1 -1
  138. package/dist/lib/http/routes/wiki.js +14 -14
  139. package/dist/lib/http/routes/wiki.js.map +1 -1
  140. package/dist/lib/http/utils/sse-sessions.d.ts +1 -1
  141. package/dist/lib/infrastructure/audit/AuditStore.d.ts +2 -1
  142. package/dist/lib/infrastructure/audit/AuditStore.d.ts.map +1 -1
  143. package/dist/lib/infrastructure/audit/AuditStore.js +2 -2
  144. package/dist/lib/infrastructure/audit/AuditStore.js.map +1 -1
  145. package/dist/lib/infrastructure/config/ConfigLoader.d.ts.map +1 -1
  146. package/dist/lib/infrastructure/config/ConfigLoader.js +1 -2
  147. package/dist/lib/infrastructure/config/ConfigLoader.js.map +1 -1
  148. package/dist/lib/infrastructure/database/DatabaseConnection.d.ts.map +1 -1
  149. package/dist/lib/infrastructure/database/DatabaseConnection.js +3 -3
  150. package/dist/lib/infrastructure/database/DatabaseConnection.js.map +1 -1
  151. package/dist/lib/infrastructure/database/drizzle/index.d.ts +2 -0
  152. package/dist/lib/infrastructure/database/drizzle/index.d.ts.map +1 -1
  153. package/dist/lib/infrastructure/database/drizzle/index.js +2 -0
  154. package/dist/lib/infrastructure/database/drizzle/index.js.map +1 -1
  155. package/dist/lib/injection/ServiceContainer.d.ts.map +1 -1
  156. package/dist/lib/injection/ServiceContainer.js +13 -1
  157. package/dist/lib/injection/ServiceContainer.js.map +1 -1
  158. package/dist/lib/injection/modules/AgentModule.d.ts.map +1 -1
  159. package/dist/lib/injection/modules/AgentModule.js +2 -1
  160. package/dist/lib/injection/modules/AgentModule.js.map +1 -1
  161. package/dist/lib/injection/modules/AppModule.d.ts.map +1 -1
  162. package/dist/lib/injection/modules/AppModule.js +13 -6
  163. package/dist/lib/injection/modules/AppModule.js.map +1 -1
  164. package/dist/lib/injection/modules/GuardModule.d.ts.map +1 -1
  165. package/dist/lib/injection/modules/GuardModule.js +7 -3
  166. package/dist/lib/injection/modules/GuardModule.js.map +1 -1
  167. package/dist/lib/injection/modules/InfraModule.d.ts.map +1 -1
  168. package/dist/lib/injection/modules/InfraModule.js +18 -5
  169. package/dist/lib/injection/modules/InfraModule.js.map +1 -1
  170. package/dist/lib/injection/modules/KnowledgeModule.d.ts.map +1 -1
  171. package/dist/lib/injection/modules/KnowledgeModule.js +3 -4
  172. package/dist/lib/injection/modules/KnowledgeModule.js.map +1 -1
  173. package/dist/lib/platform/ios/routes/spm.d.ts.map +1 -1
  174. package/dist/lib/platform/ios/routes/spm.js +16 -17
  175. package/dist/lib/platform/ios/routes/spm.js.map +1 -1
  176. package/dist/lib/platform/ios/spm/PolicyEngine.d.ts.map +1 -1
  177. package/dist/lib/platform/ios/spm/PolicyEngine.js +3 -1
  178. package/dist/lib/platform/ios/spm/PolicyEngine.js.map +1 -1
  179. package/dist/lib/repository/knowledge/KnowledgeRepository.impl.d.ts +2 -1
  180. package/dist/lib/repository/knowledge/KnowledgeRepository.impl.d.ts.map +1 -1
  181. package/dist/lib/repository/knowledge/KnowledgeRepository.impl.js +2 -2
  182. package/dist/lib/repository/knowledge/KnowledgeRepository.impl.js.map +1 -1
  183. package/dist/lib/repository/remote/RemoteCommandRepository.d.ts +2 -1
  184. package/dist/lib/repository/remote/RemoteCommandRepository.d.ts.map +1 -1
  185. package/dist/lib/repository/remote/RemoteCommandRepository.js +2 -2
  186. package/dist/lib/repository/remote/RemoteCommandRepository.js.map +1 -1
  187. package/dist/lib/repository/task/TaskRepository.impl.d.ts +2 -1
  188. package/dist/lib/repository/task/TaskRepository.impl.d.ts.map +1 -1
  189. package/dist/lib/repository/task/TaskRepository.impl.js +2 -2
  190. package/dist/lib/repository/task/TaskRepository.impl.js.map +1 -1
  191. package/dist/lib/repository/token/TokenUsageStore.d.ts +2 -1
  192. package/dist/lib/repository/token/TokenUsageStore.d.ts.map +1 -1
  193. package/dist/lib/repository/token/TokenUsageStore.js +2 -2
  194. package/dist/lib/repository/token/TokenUsageStore.js.map +1 -1
  195. package/dist/lib/service/agent/AgentEventBus.d.ts.map +1 -1
  196. package/dist/lib/service/agent/AgentEventBus.js +10 -10
  197. package/dist/lib/service/agent/AgentEventBus.js.map +1 -1
  198. package/dist/lib/service/agent/context/ExplorationTracker.d.ts.map +1 -1
  199. package/dist/lib/service/agent/context/ExplorationTracker.js +5 -2
  200. package/dist/lib/service/agent/context/ExplorationTracker.js.map +1 -1
  201. package/dist/lib/service/agent/forced-summary.d.ts +4 -2
  202. package/dist/lib/service/agent/forced-summary.d.ts.map +1 -1
  203. package/dist/lib/service/agent/forced-summary.js +78 -11
  204. package/dist/lib/service/agent/forced-summary.js.map +1 -1
  205. package/dist/lib/service/agent/tools/index.d.ts.map +1 -1
  206. package/dist/lib/service/agent/tools/infrastructure.d.ts.map +1 -1
  207. package/dist/lib/service/agent/tools/infrastructure.js +6 -2
  208. package/dist/lib/service/agent/tools/infrastructure.js.map +1 -1
  209. package/dist/lib/service/automation/FileWatcher.d.ts.map +1 -1
  210. package/dist/lib/service/automation/FileWatcher.js +4 -8
  211. package/dist/lib/service/automation/FileWatcher.js.map +1 -1
  212. package/dist/lib/service/automation/handlers/AlinkHandler.d.ts.map +1 -1
  213. package/dist/lib/service/automation/handlers/AlinkHandler.js +4 -2
  214. package/dist/lib/service/automation/handlers/AlinkHandler.js.map +1 -1
  215. package/dist/lib/service/guard/ViolationsStore.d.ts +2 -1
  216. package/dist/lib/service/guard/ViolationsStore.d.ts.map +1 -1
  217. package/dist/lib/service/guard/ViolationsStore.js +2 -2
  218. package/dist/lib/service/guard/ViolationsStore.js.map +1 -1
  219. package/dist/lib/service/skills/SkillAdvisor.d.ts.map +1 -1
  220. package/dist/lib/service/skills/SkillAdvisor.js +3 -1
  221. package/dist/lib/service/skills/SkillAdvisor.js.map +1 -1
  222. package/dist/lib/service/skills/SkillHooks.d.ts +5 -1
  223. package/dist/lib/service/skills/SkillHooks.d.ts.map +1 -1
  224. package/dist/lib/service/skills/SkillHooks.js +5 -4
  225. package/dist/lib/service/skills/SkillHooks.js.map +1 -1
  226. package/dist/lib/shared/UnifiedValidator.d.ts +1 -1
  227. package/dist/lib/shared/UnifiedValidator.d.ts.map +1 -1
  228. package/dist/lib/shared/UnifiedValidator.js +2 -2
  229. package/dist/lib/shared/UnifiedValidator.js.map +1 -1
  230. package/dist/lib/shared/isOwnDevRepo.d.ts.map +1 -1
  231. package/dist/lib/shared/isOwnDevRepo.js +11 -11
  232. package/dist/lib/shared/isOwnDevRepo.js.map +1 -1
  233. package/dist/lib/shared/package-root.d.ts.map +1 -1
  234. package/dist/lib/shared/package-root.js +1 -3
  235. package/dist/lib/shared/package-root.js.map +1 -1
  236. package/dist/lib/shared/resolveProjectRoot.d.ts +26 -0
  237. package/dist/lib/shared/resolveProjectRoot.d.ts.map +1 -0
  238. package/dist/lib/shared/resolveProjectRoot.js +24 -0
  239. package/dist/lib/shared/resolveProjectRoot.js.map +1 -0
  240. package/dist/lib/shared/schemas/http-requests.d.ts +0 -6
  241. package/dist/lib/shared/schemas/http-requests.d.ts.map +1 -1
  242. package/dist/lib/shared/schemas/http-requests.js +0 -6
  243. package/dist/lib/shared/schemas/http-requests.js.map +1 -1
  244. package/dist/lib/shared/schemas/mcp-tools.d.ts +1 -1
  245. package/dist/lib/types/database.d.ts +14 -0
  246. package/dist/lib/types/database.d.ts.map +1 -0
  247. package/dist/lib/types/database.js +2 -0
  248. package/dist/lib/types/database.js.map +1 -0
  249. package/dist/scripts/build-native-ui.js +1 -4
  250. package/dist/scripts/build-native-ui.js.map +1 -1
  251. package/dist/scripts/install-cursor-skill.js +2 -5
  252. package/dist/scripts/install-cursor-skill.js.map +1 -1
  253. package/dist/scripts/install-full.js +1 -4
  254. package/dist/scripts/install-full.js.map +1 -1
  255. package/dist/scripts/install-vscode-copilot.js +1 -4
  256. package/dist/scripts/install-vscode-copilot.js.map +1 -1
  257. package/dist/scripts/release.js +1 -4
  258. package/dist/scripts/release.js.map +1 -1
  259. package/package.json +23 -24
  260. package/scripts/postbuild.mjs +2 -3
  261. package/scripts/{postinstall-safe.js → postinstall-safe.mjs} +1 -4
  262. package/templates/guard-ci.yml +1 -1
  263. package/dashboard/dist/assets/axios-C0Zqfgkc.js +0 -6
  264. package/dashboard/dist/assets/framer-motion-DOATyqla.js +0 -9
  265. package/dashboard/dist/assets/icons-0-btqT36.js +0 -531
  266. package/dashboard/dist/assets/index--XYC2yVO.js +0 -128
  267. package/dashboard/dist/assets/index-DNCrgh_C.css +0 -1
  268. package/dashboard/dist/assets/vendor-Ck-HBmg5.js +0 -3122
@@ -0,0 +1,128 @@
1
+ import{r as n,j as e,_ as Ba,$ as Wr,a0 as Vr,a1 as Jr,a2 as Yr,a3 as Ga,a4 as Qr,a5 as Xr,a6 as Zr,a7 as $a,a8 as Ha,a9 as Oa,aa as en,ab as tn,ac as Ka,ad as qa,ae as Ua,af as sn,ag as Wa,ah as Va,ai as Ja,aj as Ya,ak as Qa,al as Xa,am as Za,an,ao as rn,ap as er,aq as nn,ar as tr,as as ln,at as sr,au as ar,av as on,aw as st,ax as St,ay as cn,az as dn,aA as rr,aB as nr,aC as un,aD as pn}from"./vendor-BZEJEVBn.js";import{Z as Ke,L as Qs,S as mn,B as qt,H as Xs,C as xn,a as at,W as gn,G as Ds,b as qe,c as rt,d as js,e as hn,f as fn,D as Os,g as as,P as bn,h as _t,i as lr,F as jt,j as tt,k as ws,l as ct,M as wt,m as or,n as vn,o as yn,p as jn,U as ir,q as wn,r as He,s as gt,X as Ue,t as Ce,u as pt,R as cr,v as Qe,w as Zs,A as dr,x as Nn,y as ht,z as Ns,E as Nt,I as mt,J as kn,K as Cn,N as ea,O as Sn,T as ur,Q as Ft,V as kt,Y as An,_ as pr,$ as Dn,a0 as Rn,a1 as In,a2 as Tn,a3 as ks,a4 as Et,a5 as et,a6 as Ht,a7 as Rs,a8 as ta,a9 as mr,aa as Zt,ab as En,ac as ma,ad as xa,ae as ga,af as Pn,ag as Ps,ah as xr,ai as gs,aj as Ks,ak as Ln,al as rs,am as hs,an as Ot,ao as ha,ap as Kt,aq as Mn,ar as gr,as as qs,at as It,au as _n,av as hr,aw as Us,ax as fr,ay as Fn,az as zn,aA as Ws,aB as Bn,aC as sa,aD as Gn,aE as $n,aF as Hn,aG as On,aH as Kn}from"./icons-C1dUryS-.js";import{a as aa}from"./axios-42ANG6Sg.js";import{A as qn,m as Un}from"./framer-motion-CZfOSYpP.js";import"./yaml-qRaU8Ldn.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const o of i)if(o.type==="childList")for(const u of o.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function a(i){const o={};return i.integrity&&(o.integrity=i.integrity),i.referrerPolicy&&(o.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?o.credentials="include":i.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(i){if(i.ep)return;i.ep=!0;const o=a(i);fetch(i.href,o)}})();const Vs={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:"内置 Agent",modeLogin:"登录",modeProbe:"探针",logout:"登出",tokenLabel:"7日 Token",tokenCalls:"次调用",tokenCallsFull:"{count} 次 AI 调用"},header:{searchPlaceholder:"搜索知识库...",semanticSearch:"语义搜索",semanticSearchTitle:"语义搜索 (AI 向量检索)",semanticSearchFailed:"语义搜索失败。请确保已运行 asd embed 构建索引。",aiSwitchFailed:"切换 AI 失败,请检查项目根目录是否可写。",aiNotConfigured:"AI 未配置 — 点击设置 LLM",configureLlm:"配置 LLM",clickSwitchAi:"点击切换 AI 提供商",switchAi:"切换 AI",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:"✓ 无匹配内容",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 · 22 MCP 工具 · Agent Runtime · 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:"冷启动知识库",step4Desc1:"多维度 AI 扫描代码库",step4Desc2:"生成 Candidate → Dashboard 审核 → Recipe",threeRoles:"三大角色",roleColumn:"角色",responsibilityColumn:"职责",capabilityColumn:"能力",roleDeveloper:"开发者",roleCursorAgent:"IDE Agent",roleChatAgent:"内置 Agent",developerResp:"审核与决策、维护项目标准",cursorAgentResp:"按规范生成代码、检索知识库、管理任务",chatAgentResp:"冷启动分析、飞书编程、Skills 推荐、扫描审查",coreComponents:"核心组件",bootstrapLabel:"Bootstrap(冷启动)",bootstrapDesc:"14 维度 × 7 阶段双路径知识提取引擎",candidatesLabel:"Candidates(候选)",candidatesDesc:"V3 结构化候选条目,Agent 只提交、人类审核",recipeLabel:"Recipe(配方)",recipeDesc:"统一 V3 知识模型 + 知识图谱关系网络",chatAgentLabel:"Agent 运行时(统一引擎)",chatAgentDesc:"单一 Runtime + Preset 配置驱动,支撑所有 AI 能力",searchPipelineLabel:"4 层检索管线",searchPipelineDesc:"5 层漏斗 + 6 信号精排 + Cross-Encoder AI 重排",guardLabel:"Guard(代码审查)",guardDesc:"知识驱动规则,写码即检测;Agent 静默自修复",knowledgeLoop:"知识库闭环",loopStep1:"发现提取",loopStep1Sub:"Bootstrap / Agent / Cursor",loopStep2:"审核筛选",loopStep2Sub:"自动 + 人工",loopStep3:"持久化",loopStep3Sub:".md + DB + 图谱",loopStep4:"交付使用",loopStep4Sub:"IDE / Agent / Guard",loopStep5:"反馈学习",loopStep5Sub:"规则精度 + 质量评分",knowledgeBuild:"知识库构建",semanticSearchLabel:"语义检索",codeAudit:"代码审查(Audit)",dataSync:"数据同步",usageExamples:"使用示例",exampleSearchKB:"检索知识库",exampleSearchKBDesc:'对 Cursor 说:"查找网络请求错误处理的代码"',exampleBatchScan:"批量扫描",exampleBatchScanDesc:'对 Cursor 说:"扫描 NetworkModule,生成 Recipes 到候选"',exampleSubmitCode:"提交代码",exampleSubmitCodeDesc:'对 Cursor 说:"把这段代码保存为 Recipe"',skills10:"11 个 Skills",mcp16:"22 个 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 理解规范;22 个 MCP 工具按需检索、提交候选;写操作经 Gateway 审核;TaskGraph DAG 任务编排 + tokenBudget 感知消费",chatAgentCap:'统一 AgentRuntime 驱动;飞书 Lark Preset 编程对话;Skills 智能推荐 + 自动注入;<code class="bg-slate-100 px-1 rounded">asd coldstart</code> 冷启动 + <code class="bg-slate-100 px-1 rounded">asd ais</code> 扫描',bootstrapBullet1:"14 维度知识提取(7 通用 + 7 语言),按语言/框架自动激活",bootstrapBullet2:"双路径:Analyst/Producer AI 管线 或 IDE Agent + MCP",bootstrapBullet3:"副产品自动生成:Repo Wiki + 4 Project Skills + Phase 6 AI 润色",candidatesBullet1:"V3 格式 16+ 必填字段,Reasoning 强验证",candidatesBullet2:"Jaccard 0.85 去重 + 严格权限:Agent 只能提交候选",candidatesBullet3:"来源:AI 扫描 / Cursor / 剪贴板 / Dashboard,完整生命周期管理",recipeBullet1:"融合 kind(rule/pattern/fact)+ 12 knowledgeType + 8 图谱关系",recipeBullet2:'<code class="bg-blue-100 px-1 rounded">kind=rule</code> 自动成为 Guard 规则,知识→规范→检测闭环',recipeBullet3:'.md = 唯一数据源,<code class="bg-blue-100 px-1 rounded">asd sync</code> 增量同步 → DB',chatAgentCompBullet1:"统一 AgentRuntime + 4 策略 + CoALA(感知→记忆→推理→行动)",chatAgentCompBullet2:"三层记忆 + 三级上下文压缩 + 5 Provider 自动 fallback",chatAgentCompBullet3:"AgentRouter 5 级意图级联:手动→渠道→关键词→LLM→默认 chat",searchPipelineBullet1:"倒排索引召回 → Cross-Encoder AI 重排 → E-E-A-T 粗排 → 6 信号精排",searchPipelineBullet2:"自研中英文 BM25 分词 + 会话上下文感知重排",searchPipelineBullet3:"search MCP 工具:5 种模式路由,单次 40 候选 AI 评分",guardCompBullet1:"三源规则:内置 + 知识库 kind=rule 自动衍生 + Enhancement Pack 扩展",guardCompBullet2:"Agent 自修复回路:违规 + 内联 Recipe 修复指南 → 静默修复 → 再检测(最多 5 轮)",guardCompBullet3:"VSCode 实时诊断 + Quick Fix;FeedbackLoop 自动跟踪修复、学习规则精度",kbBuildBullet1:'<strong>AI 扫描</strong>:<code class="bg-slate-100 px-1 rounded text-xs">asd ais [Target]</code> 批量提取',kbBuildBullet2:'<strong>Cursor 扫描</strong>:对 Copilot 说 "扫描 Module"',kbBuildBullet3:"<strong>手动创建</strong>:New Recipe → Use Copied Code",kbBuildBullet4:'<strong>编辑器内</strong>:复制代码 → <code class="bg-slate-100 px-1 rounded text-xs">// as:create -c</code>',semSearchBullet1:"<strong>4 层管线</strong>:InvertedIndex → CoarseRanker → MultiSignalRanker → RetrievalFunnel",semSearchBullet2:'<strong>编辑器内</strong>:<code class="bg-slate-100 px-1 rounded text-xs">// as:search keyword</code>',semSearchBullet3:"<strong>Cursor MCP</strong>:search 统合工具(mode 路由 5 种模式)",semSearchBullet4:"<strong>Dashboard</strong>:搜索框支持语义 + 关键词",auditFeatureBullet1:'<strong>文件审查</strong>:<code class="bg-slate-100 px-1 rounded text-xs">// as:audit</code>',auditFeatureBullet2:'<strong>Target 审查</strong>:<code class="bg-slate-100 px-1 rounded text-xs">// as:audit target</code>',auditFeatureBullet3:'<strong>Guard 审查</strong>:MCP <code class="bg-slate-100 px-1 rounded text-xs">guard</code>(code / files 参数)',auditFeatureBullet4:"<strong>Dashboard</strong>:Guard 页面可视化审查",syncBullet1:'<strong>同步</strong>:<code class="bg-slate-100 px-1 rounded text-xs">asd sync</code> .md → DB(增量)',syncBullet2:'<strong>Hash 校验</strong>:<code class="bg-slate-100 px-1 rounded text-xs">_contentHash</code> 检测手动编辑',syncBullet3:"<strong>向量索引</strong>:启动时自动构建语义索引",syncBullet4:'<strong>依赖图</strong>:<code class="bg-slate-100 px-1 rounded text-xs">structure</code>(operation: targets / files)MCP 工具',coreFeaturesDesc:"覆盖知识采集、智能检索、代码合规、任务编排、文档生成、数据同步六大能力",kbBuildDesc:"多通道采集,AI 驱动的知识库全生命周期管理",semSearchDescShort:"4 层管线融合 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 层(18 个)— 默认对外暴露",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",mcpCallContextDesc:"调用链上下文:callers / callees / both / impact",mcpSkillDesc:"operation 路由 list / load / create / update / delete / suggest",mcpBootstrapDesc:"无参数,返回 Mission Briefing + 维度任务清单",mcpDimensionCompleteDesc:"维度完成通知 + Checkpoint + Hints 分发",mcpWikiPlanDesc:"文档规划:扫描项目 → 主题 + 数据包",mcpWikiFinalizeDesc:"文档完成:meta.json + 去重 + 文件验证",mcpTaskDesc:"15 种操作:create / ready / claim / close / decompose / prime / stats 等",archBootstrapStep1:"① 项目扫描 → 依赖 / 目录 / 入口分析",archBootstrapStep2:"② AI 批量提取 → Candidate 候选列表",archBootstrapStep3:"③ 审阅 + Promote → Recipe 知识库就绪",archBootstrapNote:"支持 bootstrap → dimension_complete 循环迭代、session 断点续跑",archPipelineL1:"InvertedIndex — 倒排索引快速召回",archPipelineL2:"CoarseRanker — 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 × 22 工具",archHttpDesc:"Express × 18 路由模块",archSkillsDesc:"11 个 Skills",archVscodeDesc:"lm.registerTool × 深度集成",v3ArchDesc:"从冷启动到知识消费,端到端的 AI 工程化架构",archOverviewLabel:"端到端架构流",archOverviewBootstrap:"冷启动",archOverviewKB:"知识库",archOverviewPipeline:"检索管线",archOverviewAgent:"Agent 引擎",archOverviewTask:"TaskGraph",archOverviewOutput:"多通道交付",archOverviewSecurity:"Guard + Gateway(知识驱动验证 + 权限审计)",archOverviewIDE:"IDE 集成(MCP + Skills + Extension 三通道)",ideIntegrationLabel:"IDE 集成",ideIntegrationDesc:"6 种 IDE + 飞书,MCP/Extension/Directives 三通道接入",ideIntegrationBullet1:"MCP Server:22 工具 + Skills 自动发现 + Tier 可见性",ideIntegrationBullet2:"VSCode Extension:11 模块(Guard + CodeLens + #asd Agent + Decision)",ideIntegrationBullet3:'一键 <code class="bg-slate-100 px-1 rounded text-xs">asd setup</code> 生成 Cursor / VS Code / Claude Code 模板',securityLabel:"安全与权限",securityDesc:"Gateway 4 步管线 + 宪法治理 + 3 角色 RBAC",securityBullet1:"Gateway 四步:validate → guard → route → audit,写操作唯一入口",securityBullet2:"3 级信任:外部 Agent 受限 → 内置 Agent 只读+提交 → 开发者全权限",securityBullet3:"SafetyPolicy:命令沙箱 + 文件写入保护 + 全链路审计",constitutionSecurity:"Constitution / Gateway 安全模型",constitutionSecurityDesc:"三重安全保障:权限校验 + 宪法规则 + 审计追踪",archConstitutionBullet1:"<strong>Gateway 权限</strong>:MCP 写操作经 Gateway 层统一拦截",archConstitutionBullet2:"<strong>Constitution 宪法</strong>:YAML 定义的行为准则,约束 AI 操作边界",archConstitutionBullet3:"<strong>审计日志</strong>:全链路操作可追溯,异常自动报警",archConstitutionBullet4:"<strong>Tier 隔离</strong>:Agent / Admin 分层,敏感操作需提升权限",archTaskGraphTitle:"TaskGraph 任务体系",archTaskGraphDesc:"DAG 有向无环图驱动的结构化任务管理:",archTaskGraphBullet1:"<strong>Task DAG</strong>:依赖关系建模 → 拓扑排序 → 并行调度",archTaskGraphBullet2:"<strong>状态机</strong>:pending → ready → claimed → done,自动流转",archTaskGraphBullet3:"<strong>tokenBudget</strong>:剩余 token 感知,智能裁剪任务详情",archTaskGraphBullet4:"<strong>Session 持久化</strong>:断点续跑 + 进度可视化",agentArchTitle:"Agent 架构",agentArchDesc:"统一运行时 + 正交组合配置,驱动所有 AI 能力",agentArchPresetTitle:"4 种 Preset 模式",agentArchPresetDesc:"同一个 AgentRuntime,不同的配置组合:",agentArchPresetChat:"<strong>chat</strong>:对话问答(8 轮 / 120s)— Dashboard 和飞书日常对话",agentArchPresetInsight:"<strong>insight</strong>:深度洞察(24 轮 / 600s)— 冷启动多维度分析 + 知识提取",agentArchPresetLark:"<strong>lark</strong>:飞书对话(12 轮 / 180s)— 飞书渠道知识管理",agentArchPresetRemoteExec:"<strong>remote-exec</strong>:远程执行(6 轮 / 60s)— 终端命令沙箱",agentArchStrategyTitle:"4 种执行策略",agentArchStrategyDesc:"参考 Anthropic Agents 设计模式:",agentArchStrategySingle:"<strong>Single</strong>:单次 ReAct 循环 — 对话、飞书、远程执行",agentArchStrategyPipeline:"<strong>Pipeline</strong>:顺序多阶段 + 质量门控(通过/重试/降级三态)— 扫描分析",agentArchStrategyFanOut:"<strong>FanOut</strong>:并发子任务 + 分层限流 — 冷启动多维度并行",agentArchStrategyAdaptive:"<strong>Adaptive</strong>:运行时自动选择策略 — 动态调度",agentArchCapTitle:"5 种能力集",agentArchCapDesc:"每种能力贡献提示词 + 工具白名单 + 钩子:",agentArchCapConversation:"<strong>Conversation</strong>(9 工具):多轮对话 · 知识检索 · 记忆 · SOUL.md 人格",agentArchCapCodeAnalysis:"<strong>CodeAnalysis</strong>(15 工具):AST 分析 · 类继承 · 调用图 · 代码搜索",agentArchCapKnowledgeProd:"<strong>KnowledgeProduction</strong>(3 工具):带验证的知识提交",agentArchCapScanProd:"<strong>ScanProduction</strong>(2 工具):扫描管线内存收集",agentArchCapSystem:"<strong>SystemInteraction</strong>(8 工具):安全命令 · 文件写入 · 环境探测",agentArchMemoryTitle:"三层记忆体系",agentArchMemoryDesc:"参考 CoALA / MemGPT 设计,Budget-Aware 注入(12.5% 上下文窗口):",agentArchMemoryWorking:"<strong>工作记忆</strong>(ActiveContext):Scratchpad + 观察日志 + 计划追踪",agentArchMemorySession:"<strong>会话记忆</strong>(SessionStore):跨维度报告 + 只读缓存(LRU + TTL)",agentArchMemoryPersistent:"<strong>持久记忆</strong>(PersistentMemory):三维评分 × 记忆合并(SQLite)",agentArchContextTitle:"上下文管理",agentArchContextDesc:"保障长对话不溢出,模型感知 Token 预算:",agentArchContextWindow:"<strong>ContextWindow</strong>:三级压缩 — L1 截断旧工具结果 → L2 摘要历史 → L3 仅保留提示词",agentArchContextTracker:"<strong>ExplorationTracker</strong>:阶段状态机 + 信号检测 + Nudge 引导 + 优雅退出",agentArchToolsTitle:"工具体系",agentArchToolsDesc:"58 个内部工具 + 22 个 MCP 工具,写操作经 Gateway 审计:",agentArchToolsInternal:"<strong>内部工具</strong>(58 个):10 类 — 项目访问 · 查询 · AST · 组合 · Guard · 知识图谱 · 生命周期 · 基础设施 · 系统 · 扫描",agentArchToolsMcp:"<strong>MCP 工具</strong>(22 个):18 Agent 层 + 4 Admin 层,stdio 传输",agentArchRouterTitle:"意图路由",agentArchRouterDesc:"AgentRouter 5 级优先级:手动指定 → 渠道检测 → 关键词正则 → LLM 分类 → 默认 chat",cliSetupDesc:"初始化项目",cliStatusDesc:"环境自检",cliUiDesc:"启动 Dashboard",cliUpgradeDesc:"升级 IDE 集成",cliSyncDesc:".md → DB 增量同步",cliAisDesc:"AI 扫描提取 Candidates",cliAisForceDesc:"强制重新扫描全量",cliWatchDesc:"文件监控 + 指令触发",cliSearchDesc:"搜索知识库",cliSearchSemanticDesc:"语义搜索模式",cliGuardDesc:"Guard 规则检查",cliServerDesc:"单独启动 API 服务",cliUpgradeMcpDesc:"升级 MCP / Skills / Rules",cliInstallFullDesc:"全量安装 IDE 集成",cliSyncForceDesc:"全量重建 DB",cliSyncDryDesc:"预览同步变更",taskGraphLabel:"TaskGraph(任务图)",taskGraphDesc:"为外部 Agent 解构执行步骤,跨会话持久化任务与上下文",taskGraphBullet1:"decompose 拆解 Epic → DAG 子任务,7 种依赖 + 递归就绪检测,完成后自动解锁下游",taskGraphBullet2:"prime 会话恢复:注入进行中任务 + 团队决策 + 知识上下文,不丢进度",taskGraphBullet3:"团队约定持久化 + supersedes 演化链 + 30 天 Stale 自动检测",vscodeExtension:"VSCode Extension",vscodeExtDesc:"基于 lm.registerTool API 的原生 Copilot 深度集成",vscodeExtTaskTool:"TaskGraph 代理工具",vscodeExtTaskToolDesc:"通过 tokenBudget 感知实现 WARNING / CRITICAL 分级保护,CRITICAL 时自动内联 prime 数据",vscodeExtGuardDiag:"保存时 Guard 自动检查",vscodeExtGuardDiagDesc:"onDidSave → Guard API → DiagnosticCollection 波浪线标记 + 灯泡菜单搜索修复",vscodeExtCodeLens:"指令检测 CodeLens",vscodeExtCodeLensDesc:"检测 // as:search / // as:create 等指令,提供可视化操作按钮",vscodeExtCmd1:"autosnippet.search — 搜索知识库(Cmd+Shift+F5)",vscodeExtCmd2:"autosnippet.create — 从选区创建候选",vscodeExtCmd3:"autosnippet.audit — 审计当前文件",vscodeExtCmd4:"autosnippet.auditProject — 审计整个项目",vscodeExtCmd5:"autosnippet.status — 显示连接状态",cliColdstartAndScan:"冷启动与扫描",cliTaskManagement:"任务管理",cliGuardCi:"Guard CI/CD",cliColdstartDesc:"9 维度冷启动知识库",cliGuardCiDesc:"CI/CD 全项目 Guard 检查",cliGuardStagedDesc:"Git staged 文件检查",cliCursorRulesDesc:"生成 Cursor 多通道交付物料",cliMirrorDesc:"镜像到 .qoder / .trae",cliTaskListDesc:"列出任务图谱",cliTaskReadyDesc:"就绪任务 + 知识上下文",cliTaskPrimeDesc:"恢复会话上下文",cliTaskStatsDesc:"任务统计"},moduleExplorer:{title:"Module Explorer",scanTargets:"扫描 Targets",scanning:"扫描中...",scanComplete:"扫描完成",targetFiles:"{count} 个文件",noTargets:"未发现 Target",recipesInTarget:"关联 Recipes",guardSummary:"Guard 概况",guardViolations:"{count} 项违规",noViolations:"无违规",openFile:"打开文件",refreshTree:"刷新文件树",extractFromFile:"提取代码",fileDetail:"文件详情",projectModules:"项目模块 ({count})",addFolderScan:"添加目录扫描",refreshProject:"刷新项目结构",discovererFolderScan:"目录扫描",removeFolder:"移除此目录",fullProjectResults:"全项目扫描结果",moduleLabel:"模块: {name}",reviewResults:"审核提取结果",resultsCount:"{count} 条",candidateSuffix:" Candidate",fullProjectScanning:"全项目扫描中",moduleScanLabel:"模块扫描: {name}",filesInScan:"本次扫描的文件 ({count})",knowledgeExtract:"知识提取",knowledgeExtractHint:"在左侧选择模块扫描,或点击 + 添加任意目录。提取代码模式并生成 Recipe 知识卡片。",guardAuditSummary:"Guard 审计摘要",auditedFiles:"已审计文件:",totalViolationsLabel:"违反总数:",errorsCount:"{count} 错误",warningsCount:"{count} 警告",recipeNotExist:"「{name}」不存在于当前知识库",recipeNotExistTitle:"Recipe 不存在",loadRecipeFailed:"加载 Recipe 失败",browseFailedTitle:"目录浏览失败",browseFailedDefault:"无法加载目录列表",selectFolderTitle:"选择要扫描的目录",scanningDirs:"正在扫描项目目录...",noDirs:"未发现可扫描的目录",sourceFileCount:"{count} 文件",selectFolderHint:"选择包含源码文件的目录,系统将自动检测语言并执行 AI 扫描",modulesTabLabel:"模块 ({count})",foldersTabLabel:"目录"},search:{title:"智能搜索",searchPlaceholder:"输入搜索关键词...",noResults:"未找到匹配结果",resultCount:"找到 {count} 条结果",relevance:"相关度",source:"来源",category:"分类",language:"语言",matchType:"匹配类型",matchExact:"精确",matchFuzzy:"模糊",matchSemantic:"语义匹配",matchKeyword:"关键词匹配",viewRecipe:"查看 Recipe",insertCode:"插入代码",searchFailed:"搜索失败。请重试。",searching:"搜索中...",searchBtn:"搜索",emptyHint:"输入关键词后点击搜索",contextRelevant:"上下文相关",authorityScore:"权威分",usage:"使用",usageCount:"{count}次",recommendReason:"推荐理由",viewFullContent:"查看完整内容",similarity:"相似度",quality:"质量",noContent:"无内容",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"}},Wn={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:"Built-in Agent",modeLogin:"Login",modeProbe:"Probe",logout:"Log out",tokenLabel:"7-Day Tokens",tokenCalls:"calls",tokenCallsFull:"{count} AI calls"},header:{searchPlaceholder:"Search knowledge...",semanticSearch:"Semantic",semanticSearchTitle:"Semantic Search (Brain AI)",semanticSearchFailed:"Semantic search failed. Make sure you have run `asd embed` to build the index.",aiSwitchFailed:"Failed to switch AI provider. Check if the project root is writable.",aiNotConfigured:"AI not configured — click to set up LLM",configureLlm:"Configure LLM",clickSwitchAi:"Click to switch AI provider",switchAi:"Switch AI",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",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 · 22 MCP Tools · Agent Runtime · TaskGraph · VSCode Extension · 4-Layer Retrieval",viewGithub:"View on GitHub",fullDocs:"Full Documentation",tokenUsageLast7Days:"Token Usage (Last 7 Days)",quickStart:"Quick Start",coreConcepts:"Core Concepts",coreFeatures:"Core Features",editorDirectives:"Editor Directives",cursorIntegration:"IDE Integration",v3Architecture:"V3 Architecture",cliReference:"CLI Quick Reference",step1Title:"Install & Initialize",step2Title:"Start Dashboard",step2Desc:"Start HTTP API + Dashboard + FileWatcher",step3Title:"IDE Integration",step3Desc:"Install MCP + Skills + Cursor Rules + VSCode Extension",step4Title:"Cold Start Knowledge Base",step4Desc1:"Multi-dimension AI scan of codebase",step4Desc2:"Generate Candidates → Dashboard review → Recipe",threeRoles:"Three Roles",roleColumn:"Role",responsibilityColumn:"Responsibility",capabilityColumn:"Capabilities",roleDeveloper:"Developer",roleCursorAgent:"IDE Agent",roleChatAgent:"Built-in Agent",developerResp:"Review & decide, maintain project standards",cursorAgentResp:"Generate code per standards, search knowledge base, manage tasks",chatAgentResp:"Cold start analysis, Lark programming, Skills recommendation, scan & audit",coreComponents:"Core Components",bootstrapLabel:"Bootstrap (Cold Start)",bootstrapDesc:"14 dimensions × 7-phase dual-path knowledge extraction engine",candidatesLabel:"Candidates",candidatesDesc:"V3 structured entries — Agent submits, humans review",recipeLabel:"Recipe",recipeDesc:"Unified V3 knowledge model + knowledge graph relations",chatAgentLabel:"Agent Runtime (Unified Engine)",chatAgentDesc:"Single Runtime + Preset-driven configuration, powering all AI capabilities",searchPipelineLabel:"4-Layer Retrieval Pipeline",searchPipelineDesc:"5-layer funnel + 6-signal ranking + Cross-Encoder AI reranking",guardLabel:"Guard (Code Review)",guardDesc:"Knowledge-driven rules, detect on write; Agent silent self-repair",knowledgeLoop:"Knowledge Loop",loopStep1:"Discover & Extract",loopStep1Sub:"Bootstrap / Agent / Cursor",loopStep2:"Review & Filter",loopStep2Sub:"Auto + Human",loopStep3:"Persist",loopStep3Sub:".md + DB + Graph",loopStep4:"Deliver & Use",loopStep4Sub:"IDE / Agent / Guard",loopStep5:"Feedback & Learn",loopStep5Sub:"RuleLearner + Quality",knowledgeBuild:"Knowledge Base Building",semanticSearchLabel:"Semantic Search",codeAudit:"Code Audit",dataSync:"Data Sync",usageExamples:"Usage Examples",exampleSearchKB:"Search Knowledge Base",exampleSearchKBDesc:'Tell Cursor: "Find error handling code for network requests"',exampleBatchScan:"Batch Scan",exampleBatchScanDesc:'Tell Cursor: "Scan NetworkModule, generate Recipes to candidates"',exampleSubmitCode:"Submit Code",exampleSubmitCodeDesc:'Tell Cursor: "Save this code as a Recipe"',skills10:"11 Skills",mcp16:"22 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; 22 MCP tools for on-demand retrieval & candidate submission; writes go through Gateway review; TaskGraph DAG orchestration + tokenBudget-aware consumption",chatAgentCap:'Unified AgentRuntime; Lark Preset programming chat; Skills smart recommendation + auto-injection; <code class="bg-slate-100 px-1 rounded">asd coldstart</code> cold start + <code class="bg-slate-100 px-1 rounded">asd ais</code> scan',bootstrapBullet1:"14 dimensions (7 universal + 7 language), auto-activated by lang/framework",bootstrapBullet2:"Dual-path: Analyst/Producer AI pipeline or IDE Agent + MCP",bootstrapBullet3:"Auto by-products: Repo Wiki + 4 Project Skills + Phase 6 AI refinement",candidatesBullet1:"V3 format 16+ required fields, Reasoning strong validation",candidatesBullet2:"Jaccard 0.85 dedup + strict boundary: Agent can only submit",candidatesBullet3:"Sources: AI scan / Cursor / clipboard / Dashboard, full lifecycle mgmt",recipeBullet1:"Fuses kind (rule/pattern/fact) + 12 knowledgeTypes + 8 graph relations",recipeBullet2:'<code class="bg-blue-100 px-1 rounded">kind=rule</code> auto-becomes Guard rule: knowledge→standard→detection loop',recipeBullet3:'.md = single source of truth, <code class="bg-blue-100 px-1 rounded">asd sync</code> incremental → DB',chatAgentCompBullet1:"Unified AgentRuntime + 4 strategies + CoALA (Perceive→Memory→Reason→Act)",chatAgentCompBullet2:"3-tier memory + 3-level context compression + 5-provider auto-fallback",chatAgentCompBullet3:"AgentRouter 5-level cascade: manual→channel→keyword→LLM→default chat",searchPipelineBullet1:"Inverted index → Cross-Encoder AI rerank → E-E-A-T coarse → 6-signal fine rank",searchPipelineBullet2:"Custom CJK/English BM25 tokenizer + session context-aware reranking",searchPipelineBullet3:"search MCP tool: 5 mode routes, batch 40-candidate AI scoring",guardCompBullet1:"3 rule sources: built-in + knowledge base kind=rule auto-derived + Enhancement Pack",guardCompBullet2:"Agent self-repair loop: violation + inline Recipe fix guide → silent fix → re-check (up to 5 rounds)",guardCompBullet3:"VSCode real-time diagnostics + Quick Fix; FeedbackLoop auto-tracks fixes & learns rule precision",kbBuildBullet1:'<strong>AI Scan</strong>: <code class="bg-slate-100 px-1 rounded text-xs">asd ais [Target]</code> batch extraction',kbBuildBullet2:'<strong>Cursor Scan</strong>: Tell Copilot "scan Module"',kbBuildBullet3:"<strong>Manual Create</strong>: New Recipe → Use Copied Code",kbBuildBullet4:'<strong>In Editor</strong>: Copy code → <code class="bg-slate-100 px-1 rounded text-xs">// as:create -c</code>',semSearchBullet1:"<strong>4-Layer Pipeline</strong>: InvertedIndex → CoarseRanker → MultiSignalRanker → RetrievalFunnel",semSearchBullet2:'<strong>In Editor</strong>: <code class="bg-slate-100 px-1 rounded text-xs">// as:search keyword</code>',semSearchBullet3:"<strong>Cursor MCP</strong>: search unified tool (mode routes 5 modes)",semSearchBullet4:"<strong>Dashboard</strong>: Search box supports semantic + keyword",auditFeatureBullet1:'<strong>File Audit</strong>: <code class="bg-slate-100 px-1 rounded text-xs">// as:audit</code>',auditFeatureBullet2:'<strong>Target Audit</strong>: <code class="bg-slate-100 px-1 rounded text-xs">// as:audit target</code>',auditFeatureBullet3:'<strong>Guard Audit</strong>: MCP <code class="bg-slate-100 px-1 rounded text-xs">guard</code> (code / files param)',auditFeatureBullet4:"<strong>Dashboard</strong>: Guard page visual audit",syncBullet1:'<strong>Sync</strong>: <code class="bg-slate-100 px-1 rounded text-xs">asd sync</code> .md → DB (incremental)',syncBullet2:'<strong>Hash Check</strong>: <code class="bg-slate-100 px-1 rounded text-xs">_contentHash</code> detect manual edits',syncBullet3:"<strong>Vector Index</strong>: Auto-build semantic index on startup",syncBullet4:'<strong>Dependency Graph</strong>: <code class="bg-slate-100 px-1 rounded text-xs">structure</code> (operation: targets / files) MCP tool',coreFeaturesDesc:"Six key capabilities: knowledge collection, intelligent search, code compliance, task orchestration, document generation, and data sync",kbBuildDesc:"Multi-channel collection, AI-driven full lifecycle knowledge base management",semSearchDescShort:"4-layer pipeline fusing 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 (18) — exposed by default",mcpAdminLayerHeader:"Admin Layer (4) — requires ASD_MCP_TIER=admin",mcpHealthDesc:"Service health check",mcpCapabilitiesDesc:"Service capabilities list (Agent self-discovery)",mcpGuardDesc:"code=single file audit / files=batch audit",mcpSubmitDesc:"Submit candidate / batch / save document",mcpEnrichDesc:"AI enrich / validate / dedup",mcpLifecycleDesc:"Batch lifecycle operations",mcpSearchDesc:"mode routes auto / keyword / bm25 / semantic / context",mcpKnowledgeDesc:"operation routes list / get / insights / confirm_usage",mcpStructureDesc:"operation routes targets / files / metadata",mcpGraphDesc:"operation routes query / impact / path / stats",mcpCallContextDesc:"Call chain context: callers / callees / both / impact",mcpSkillDesc:"operation routes list / load / create / update / delete / suggest",mcpBootstrapDesc:"No params — returns Mission Briefing + dimension task list",mcpDimensionCompleteDesc:"Dimension complete notification + Checkpoint + Hints dispatch",mcpWikiPlanDesc:"Document planning: scan project → topics + data packages",mcpWikiFinalizeDesc:"Document finalization: meta.json + dedup + file validation",mcpTaskDesc:"15 operations: create / ready / claim / close / decompose / prime / stats etc.",archBootstrapStep1:"① Project scan → dependency / directory / entry analysis",archBootstrapStep2:"② AI batch extraction → Candidate list",archBootstrapStep3:"③ Review + Promote → Recipe knowledge base ready",archBootstrapNote:"Supports bootstrap → dimension_complete loop iteration & session resume from breakpoint",archPipelineL1:"InvertedIndex — inverted index fast recall",archPipelineL2:"CoarseRanker — 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 × 22 tools",archHttpDesc:"Express × 18 route modules",archSkillsDesc:"11 Skills",archVscodeDesc:"lm.registerTool × deep integration",v3ArchDesc:"End-to-end AI engineering architecture from cold start to knowledge consumption",archOverviewLabel:"End-to-End Architecture Flow",archOverviewBootstrap:"Cold Start",archOverviewKB:"Knowledge Base",archOverviewPipeline:"Retrieval Pipeline",archOverviewAgent:"Agent Engine",archOverviewTask:"TaskGraph",archOverviewOutput:"Multi-Channel Delivery",archOverviewSecurity:"Guard + Gateway (Knowledge-Driven Validation + Access Audit)",archOverviewIDE:"IDE Integration (MCP + Skills + Extension Triple-Channel)",ideIntegrationLabel:"IDE Integration",ideIntegrationDesc:"6 IDEs + Lark, MCP/Extension/Directives triple-channel access",ideIntegrationBullet1:"MCP Server: 22 tools + Skills auto-discovery + Tier visibility",ideIntegrationBullet2:"VSCode Extension: 11 modules (Guard + CodeLens + #asd Agent + Decision)",ideIntegrationBullet3:'One-click <code class="bg-slate-100 px-1 rounded text-xs">asd setup</code> generates Cursor / VS Code / Claude Code templates',securityLabel:"Security & Permissions",securityDesc:"Gateway 4-step pipeline + Constitution governance + 3-role RBAC",securityBullet1:"Gateway 4-step: validate → guard → route → audit, single write entry",securityBullet2:"3-tier trust: external Agent (restricted) → built-in Agent (read+submit) → developer (full)",securityBullet3:"SafetyPolicy: command sandbox + file write protection + full audit trail",constitutionSecurity:"Constitution / Gateway Security",constitutionSecurityDesc:"Triple security: permission check + constitution rules + audit trail",archConstitutionBullet1:"<strong>Gateway Permission</strong>: MCP write ops intercepted by Gateway layer",archConstitutionBullet2:"<strong>Constitution</strong>: YAML-defined behavioral rules constraining AI operation boundaries",archConstitutionBullet3:"<strong>Audit Log</strong>: Full-chain operation traceability, auto-alert on anomalies",archConstitutionBullet4:"<strong>Tier Isolation</strong>: Agent / Admin layered, sensitive ops require escalation",archTaskGraphTitle:"TaskGraph System",archTaskGraphDesc:"DAG-driven structured task management:",archTaskGraphBullet1:"<strong>Task DAG</strong>: Dependency modeling → topological sort → parallel scheduling",archTaskGraphBullet2:"<strong>State Machine</strong>: pending → ready → claimed → done, auto-transition",archTaskGraphBullet3:"<strong>tokenBudget</strong>: Remaining token aware, intelligent task detail trimming",archTaskGraphBullet4:"<strong>Session Persistence</strong>: Resume from breakpoint + progress visualization",agentArchTitle:"Agent Architecture",agentArchDesc:"Unified runtime + orthogonal configuration, powering all AI capabilities",agentArchPresetTitle:"4 Preset Modes",agentArchPresetDesc:"One AgentRuntime, different configuration combos:",agentArchPresetChat:"<strong>chat</strong>: Conversation Q&A (8 rounds / 120s) — Dashboard & Lark daily chat",agentArchPresetInsight:"<strong>insight</strong>: Deep Insight (24 rounds / 600s) — cold start multi-dimension analysis + knowledge extraction",agentArchPresetLark:"<strong>lark</strong>: Lark Chat (12 rounds / 180s) — Lark channel knowledge management",agentArchPresetRemoteExec:"<strong>remote-exec</strong>: Remote Exec (6 rounds / 60s) — terminal command sandbox",agentArchStrategyTitle:"4 Execution Strategies",agentArchStrategyDesc:"Based on Anthropic Agents design patterns:",agentArchStrategySingle:"<strong>Single</strong>: One ReAct loop — chat, Lark, remote exec",agentArchStrategyPipeline:"<strong>Pipeline</strong>: Sequential stages + quality gates (pass/retry/degrade) — scan analysis",agentArchStrategyFanOut:"<strong>FanOut</strong>: Concurrent sub-tasks + tier-based throttle — cold start parallel dimensions",agentArchStrategyAdaptive:"<strong>Adaptive</strong>: Auto-select strategy at runtime — dynamic dispatch",agentArchCapTitle:"5 Capability Sets",agentArchCapDesc:"Each contributes prompts + tool whitelist + hooks:",agentArchCapConversation:"<strong>Conversation</strong> (9 tools): Multi-turn dialog · knowledge search · memory · SOUL.md persona",agentArchCapCodeAnalysis:"<strong>CodeAnalysis</strong> (15 tools): AST analysis · class hierarchy · call graph · code search",agentArchCapKnowledgeProd:"<strong>KnowledgeProduction</strong> (3 tools): Knowledge submission with validation",agentArchCapScanProd:"<strong>ScanProduction</strong> (2 tools): In-memory scan pipeline collection",agentArchCapSystem:"<strong>SystemInteraction</strong> (8 tools): Safe commands · file write · environment detection",agentArchMemoryTitle:"3-Tier Memory System",agentArchMemoryDesc:"Inspired by CoALA / MemGPT, Budget-Aware injection (12.5% context window):",agentArchMemoryWorking:"<strong>Working Memory</strong> (ActiveContext): Scratchpad + observation log + plan tracking",agentArchMemorySession:"<strong>Session Memory</strong> (SessionStore): Cross-dimension reports + read-only cache (LRU + TTL)",agentArchMemoryPersistent:"<strong>Persistent Memory</strong> (PersistentMemory): 3-axis scoring × memory consolidation (SQLite)",agentArchContextTitle:"Context Management",agentArchContextDesc:"Prevent long conversations from overflowing, model-aware token budgets:",agentArchContextWindow:"<strong>ContextWindow</strong>: 3-level compression — L1 truncate old tool results → L2 summarize history → L3 keep only prompt",agentArchContextTracker:"<strong>ExplorationTracker</strong>: Phase state machine + signal detection + nudge guidance + graceful exit",agentArchToolsTitle:"Tool System",agentArchToolsDesc:"58 internal tools + 22 MCP tools, writes go through Gateway audit:",agentArchToolsInternal:"<strong>Internal Tools</strong> (58): 10 categories — project access · query · AST · composite · Guard · knowledge graph · lifecycle · infra · system · scan",agentArchToolsMcp:"<strong>MCP Tools</strong> (22): 18 Agent tier + 4 Admin tier, stdio transport",agentArchRouterTitle:"Intent Routing",agentArchRouterDesc:"AgentRouter 5-level priority: manual preset → channel detection → keyword regex → LLM classification → default chat",cliSetupDesc:"Initialize project",cliStatusDesc:"Environment check",cliUiDesc:"Start Dashboard",cliUpgradeDesc:"Upgrade IDE integration",cliSyncDesc:".md → DB incremental sync",cliAisDesc:"AI scan extract Candidates",cliAisForceDesc:"Force full rescan",cliWatchDesc:"File watch + directive trigger",cliSearchDesc:"Search knowledge base",cliSearchSemanticDesc:"Semantic search mode",cliGuardDesc:"Guard rule check",cliServerDesc:"Start API server only",cliUpgradeMcpDesc:"Upgrade MCP / Skills / Rules",cliInstallFullDesc:"Full IDE integration install",cliSyncForceDesc:"Full DB rebuild",cliSyncDryDesc:"Preview sync changes",taskGraphLabel:"TaskGraph",taskGraphDesc:"Decomposes Agent work into persistent, context-aware steps",taskGraphBullet1:"decompose Epic → DAG subtasks, 7 dep types + recursive ready detection, auto-cascade on close",taskGraphBullet2:"prime session recovery: injects in-progress + decisions + knowledge context, no lost progress",taskGraphBullet3:"Team decisions persisted + supersedes evolution chain + 30-day stale auto-detection",vscodeExtension:"VSCode Extension",vscodeExtDesc:"Native Copilot deep integration via lm.registerTool API",vscodeExtTaskTool:"TaskGraph Proxy Tool",vscodeExtTaskToolDesc:"tokenBudget-aware WARNING / CRITICAL tiered protection; auto-inlines prime data at CRITICAL level",vscodeExtGuardDiag:"Guard Check on Save",vscodeExtGuardDiagDesc:"onDidSave → Guard API → DiagnosticCollection squiggles + lightbulb menu search fix",vscodeExtCodeLens:"Directive CodeLens",vscodeExtCodeLensDesc:"Detects // as:search / // as:create directives and provides visual action buttons",vscodeExtCmd1:"autosnippet.search — Search knowledge base (Cmd+Shift+F5)",vscodeExtCmd2:"autosnippet.create — Create candidate from selection",vscodeExtCmd3:"autosnippet.audit — Audit current file",vscodeExtCmd4:"autosnippet.auditProject — Audit entire project",vscodeExtCmd5:"autosnippet.status — Show connection status",cliColdstartAndScan:"Cold Start & Scan",cliTaskManagement:"Task Management",cliGuardCi:"Guard CI/CD",cliColdstartDesc:"9-dimension cold start knowledge base",cliGuardCiDesc:"CI/CD full project Guard check",cliGuardStagedDesc:"Git staged files Guard check",cliCursorRulesDesc:"Generate Cursor multi-channel delivery",cliMirrorDesc:"Mirror to .qoder / .trae",cliTaskListDesc:"List task graph",cliTaskReadyDesc:"Ready tasks + knowledge context",cliTaskPrimeDesc:"Restore session context",cliTaskStatsDesc:"Task statistics"},moduleExplorer:{title:"Module Explorer",scanTargets:"Scan Targets",scanning:"Scanning...",scanComplete:"Scan complete",targetFiles:"{count} files",noTargets:"No Targets found",recipesInTarget:"Related Recipes",guardSummary:"Guard Summary",guardViolations:"{count} violations",noViolations:"No violations",openFile:"Open file",refreshTree:"Refresh file tree",extractFromFile:"Extract code",fileDetail:"File Detail",projectModules:"Project Modules ({count})",addFolderScan:"Add folder scan",refreshProject:"Refresh project structure",discovererFolderScan:"Folder Scan",removeFolder:"Remove this folder",fullProjectResults:"Full project scan results",moduleLabel:"Module: {name}",reviewResults:"Review extraction results",resultsCount:"{count} items",candidateSuffix:" Candidate",fullProjectScanning:"Full project scanning",moduleScanLabel:"Module scan: {name}",filesInScan:"Scanned files ({count})",knowledgeExtract:"Knowledge Extraction",knowledgeExtractHint:"Select a module on the left to scan, or click + to add a folder. Extract code patterns and generate Recipe knowledge cards.",guardAuditSummary:"Guard Audit Summary",auditedFiles:"Audited files:",totalViolationsLabel:"Total violations:",errorsCount:"{count} errors",warningsCount:"{count} warnings",recipeNotExist:'"{name}" does not exist in the current knowledge base',recipeNotExistTitle:"Recipe not found",loadRecipeFailed:"Failed to load Recipe",browseFailedTitle:"Browse folder failed",browseFailedDefault:"Unable to load directory listing",selectFolderTitle:"Select folder to scan",scanningDirs:"Scanning project directories...",noDirs:"No scannable directories found",sourceFileCount:"{count} files",selectFolderHint:"Select a folder with source files. Language will be auto-detected and AI scan will run.",modulesTabLabel:"Modules ({count})",foldersTabLabel:"Folders"},search:{title:"Smart Search",searchPlaceholder:"Enter search keywords...",noResults:"No matching results",resultCount:"{count} results found",relevance:"Relevance",source:"Source",category:"Category",language:"Language",matchType:"Match Type",matchExact:"Exact",matchFuzzy:"Fuzzy",matchSemantic:"Semantic Match",matchKeyword:"Keyword Match",viewRecipe:"View Recipe",insertCode:"Insert Code",searchFailed:"Search failed. Please try again.",searching:"Searching...",searchBtn:"Search",emptyHint:"Enter keywords and click Search",contextRelevant:"Context Relevant",authorityScore:"Authority",usage:"Usage",usageCount:"{count} times",recommendReason:"Recommendation Reason",viewFullContent:"View Full Content",similarity:"Similarity",quality:"Quality",noContent:"No content",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"}},fa={zh:Vs,en:Wn},fs="asd-dashboard-lang";function Vn(){try{const t=localStorage.getItem(fs);if(t==="en"||t==="zh")return t}catch{}return"zh"}function ba(t,s){const a=s.split(".");let r=t;for(const i of a){if(r==null||typeof r!="object")return;r=r[i]}return typeof r=="string"?r:void 0}function Jn(t,s){return s?t.replace(/\{(\w+)\}/g,(a,r)=>{const i=s[r];return i!=null?String(i):`{${r}}`}):t}const br=n.createContext(null);function Yn({children:t}){const[s,a]=n.useState(Vn);n.useEffect(()=>{const u=localStorage.getItem(fs);u==="en"||u==="zh"?fetch("/api/v1/ai/lang",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lang:u})}).catch(()=>{}):fetch("/api/v1/ai/lang").then(p=>p.json()).then(p=>{const c=p?.data?.lang;if(c==="en"||c==="zh"){a(c);try{localStorage.setItem(fs,c)}catch{}}}).catch(()=>{})},[]);const r=n.useCallback(u=>{a(u);try{localStorage.setItem(fs,u)}catch{}fetch("/api/v1/ai/lang",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({lang:u})}).catch(()=>{})},[]),i=n.useCallback((u,p)=>{const c=ba(fa[s],u)??ba(fa.zh,u)??u;return Jn(c,p)},[s]),o=n.useMemo(()=>({lang:s,setLang:r,t:i}),[s,r,i]);return e.jsx(br.Provider,{value:o,children:t})}function Ae(){const t=n.useContext(br);if(!t)throw new Error("useI18n must be used within <I18nProvider>");return t}const vr="asd-dashboard-theme";function Qn(){return typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches}function Xn(){try{const t=localStorage.getItem(vr);if(t==="light"||t==="dark"||t==="system")return t}catch{}return"system"}const yr=n.createContext(null);function Zn({children:t}){const[s,a]=n.useState(Xn),[r,i]=n.useState(Qn);n.useEffect(()=>{const x=window.matchMedia("(prefers-color-scheme: dark)"),h=g=>i(g.matches);return x.addEventListener("change",h),()=>x.removeEventListener("change",h)},[]);const o=s==="dark"?!0:s==="light"?!1:r;n.useEffect(()=>{const x=document.documentElement;o?x.classList.add("dark"):x.classList.remove("dark")},[o]);const u=n.useCallback(x=>{a(x);try{localStorage.setItem(vr,x)}catch{}},[]),p=n.useCallback(()=>{u(o?"light":"dark")},[o,u]),c=n.useMemo(()=>({isDark:o,mode:s,toggle:p,setTheme:u}),[o,s,p,u]);return e.jsx(yr.Provider,{value:c,children:t})}function Is(){const t=n.useContext(yr);if(!t)throw new Error("useTheme must be used within <ThemeProvider>");return t}const el="AutoSnippet";function tl(t){if(typeof window>"u"||!("Notification"in window))return;const s=()=>{try{new Notification(el,{body:t,tag:"autosnippet"})}catch{}};if(Notification.permission==="granted"){s();return}Notification.permission!=="denied"&&Notification.requestPermission().then(a=>{a==="granted"&&s()}).catch(()=>{})}const sl={success:5e3,error:8e3,info:5e3},va={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"}},al=()=>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"})}),rl=()=>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"})}),jr=()=>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"})}),nl={success:al,error:rl,info:jr},ll=({visible:t,toastId:s,body:a,type:r,title:i,duration:o})=>{const u=va[r]||va.info,p=nl[r]||jr,c=typeof document<"u"&&document.documentElement.classList.contains("dark");return e.jsxs("div",{onClick:()=>Ba.dismiss(s),style:{background:c?u.darkBg:u.bg,borderLeft:`4px solid ${c?u.darkBorder:u.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(p,{})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[i&&e.jsx("div",{style:{fontWeight:600,fontSize:13,lineHeight:1.3,color:c?"#e2e8f0":"#1e293b",marginBottom:2},children:i}),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:u.bar,opacity:.45,animation:`toast-progress ${o}ms linear forwards`}})]})};function Z(t,s){const a=s?.type??"success",r=s?.title,i=s?.duration??sl[a]??5e3;typeof document<"u"&&document.visibilityState==="visible"?ol(t,a,r,i):tl(r?`${r}: ${t}`:t)}function ol(t,s,a,r){Ba.custom(i=>e.jsx(ll,{visible:i.visible,toastId:i.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 it={All:{icon:_t,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:as,color:"text-indigo-600",bg:"bg-indigo-50",border:"border-indigo-100"},Tool:{icon:Ke,color:"text-amber-600",bg:"bg-amber-50",border:"border-amber-100"},Model:{icon:Os,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:js,color:"text-cyan-600",bg:"bg-cyan-50",border:"border-cyan-100"},Utility:{icon:rt,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:Ds,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:at,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:Xs,color:"text-teal-600",bg:"bg-teal-50",border:"border-teal-100"},"agent-guidelines":{icon:qt,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:Qs,color:"text-cyan-600",bg:"bg-cyan-50",border:"border-cyan-100"},bootstrap:{icon:Ke,color:"text-violet-600",bg:"bg-violet-50",border:"border-violet-100"}},il=["All","View","Service","Tool","Model","Network","Storage","UI","Utility"],cl=["recipes","ai","spm","candidates","knowledge","depgraph","knowledgegraph","guard","skills","wiki","help"],$t=[{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 ra(t){if(!t)return"";const s=t.toLowerCase().trim();for(const a of $t)if(a.id===s||a.aliases?.includes(s))return a.id;return s}function ya(t){switch(ra(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 dl="https://github.com/GxFn/AutoSnippet/issues/new?title=Guard%20误报%2F建议%3A%20&body=请描述误报的规则ID、代码片段或改进建议。",os=t=>["Example","Demo","Sample","Tests","Spec","Mock","Runner"].some(a=>t.endsWith(a)||t.includes(a)),ul=t=>t.startsWith("_"),pl=t=>t==="_pending",ml="您暂无写入权限,无法保存。如需此权限请联系管理员;请勿擅自修改核心代码或安装包,以免影响团队协作与数据安全。";function bs(t){const s=t?.response;if(s?.status!==403)return null;const a=s.data?.code,r=s.data?.error;return a==="RECIPE_WRITE_FORBIDDEN"||typeof r=="string"&&r.includes("没权限")?ml:null}const xl="保存过于频繁,请稍后再试。";function ja(t){const s=t?.response;return s?.data?s.status===403?bs(t)??null:s.status===429&&s.data?.code==="RECIPE_SAVE_RATE_LIMIT"?xl:null:null}function ve(t,s="Unknown error"){if(typeof t=="string")return t;if(t instanceof Error)return t.message;if(Ts(t)){const a=t.response?.data;if(a){if(typeof a.error=="string")return a.error;if(typeof a.error=="object"&&a.error?.message)return a.error.message;if(typeof a.message=="string")return a.message}if(t.message)return t.message}if(typeof t=="object"&&t!==null&&"message"in t){const a=t.message;if(typeof a=="string")return a}return s}function Ts(t){return typeof t=="object"&&t!==null&&"response"in t&&typeof t.response=="object"}function na(t){if(Ts(t))return t.response?.status}function Cs(t){return t instanceof Error&&t.name==="AbortError"}function wa(t){return typeof t=="object"&&t!==null&&"__CANCEL__"in t}function Ls(t){return Ts(t)&&t.code==="ECONNABORTED"?!0:ve(t,"").toLowerCase().includes("timeout")}function gl(t){return Ts(t)?t.response?.data?.aiError===!0:!1}const re=aa.create({baseURL:"/api/v1"});function Na(t){const s=t.quality||{},a=t.stats||t.statistics||{},r=t.content||{},i=t.trigger||"@"+(t.title||"").replace(/[\s_-]+(.)?/g,(u,p)=>p?p.toUpperCase():""),o={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:o,trigger:i,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="",i="",o="",u="",p="",c="",x="",h=[],g=[],d="",l=0,f="1.0.0",y="",D="",S="",T="",z="",O="",G="",le="",w="",k="",I=t;const q=t.match(/^---\n([\s\S]*?)\n---/);if(q){const W=q[1],K=P=>{const V=W.match(new RegExp(`^${P}:\\s*(.+)$`,"m"));return V?V[1].trim():null};s=K("language")||s,a=K("category")||a,r=K("title")||r,i=K("trigger")||"",o=K("summary_cn")||K("summary")||K("description")||o,u=K("summary_en")||"",p=K("knowledge_type")||K("knowledgeType")||"",c=K("complexity")||"",x=K("scope")||"",d=K("difficulty")||"",f=K("version")||"1.0.0";const C=K("authority");C&&(l=parseInt(C)||0);const v=K("tags");if(v)try{h=JSON.parse(v)}catch{h=v.split(",").map(P=>P.trim()).filter(Boolean)}const _=K("headers");if(_)try{g=JSON.parse(_)}catch{g=[_]}O=K("kind")||"",G=K("doClause")||"",le=K("dontClause")||"",w=K("whenClause")||"",k=K("topicHint")||"";const ae=t.match(/```[\w]*\n([\s\S]*?)```/);ae&&(I=ae[1].trim());const Q=t.replace(/^---\n[\s\S]*?\n---/,"").trim(),me=Q.match(/## (?:AI Context \/ )?Usage Guide(?:\s*\(CN\))?\n\n([\s\S]*?)(?=\n## |$)/);me&&(y=me[1].trim());const Se=Q.match(/## (?:AI Context \/ )?Usage Guide\s*\(EN\)\n\n([\s\S]*?)(?=\n## |$)/);Se&&(D=Se[1].trim());const ye=Q.match(/## Architecture Usage\n\n([\s\S]*?)(?=\n## |$)/);ye&&(S=ye[1].trim());const j=Q.match(/## Best Practices\n\n([\s\S]*?)(?=\n## |$)/);j&&(T=j[1].trim());const N=Q.match(/## Standards\n\n([\s\S]*?)(?=\n## |$)/);N&&(z=N[1].trim())}return{title:r,language:s,category:a,trigger:i,summary:o,summaryEn:u,knowledgeType:p,complexity:c,scope:x,tags:h,headers:g,difficulty:d,authority:l,version:f,codePattern:I,usageGuide:y,usageGuideEn:D,rationaleText:S,bestPracticesText:T,standardsText:z,kind:O,doClause:G,dontClause:le,whenClause:w,topicHint:k}}function fl(t,s,a){const r=Array.isArray(t.category)?t.category[0]:t.category||s||"general";return{title:t.title||"Untitled",content:t.content||{pattern:"",markdown:"",rationale:""},description:t.description||"",trigger:t.trigger||"",language:t.language||"",category:r,kind:t.kind||"pattern",knowledgeType:t.knowledgeType||"code-pattern",complexity:t.complexity||"intermediate",source:a,lifecycle:"pending",tags:t.tags||[],sourceFile:t.sourceFile||"",moduleName:t.moduleName||"",headers:t.headers||[],headerPaths:t.headerPaths||[],reasoning:{whyStandard:t.description||t.title||"Extracted from project",sources:[a],confidence:.6},metadata:{targetName:s||"",title:t.title||"",trigger:t.trigger||"",description:t.description||"",category:r,headers:t.headers||[],headerPaths:t.headerPaths||[],moduleName:t.moduleName||"",isMarked:t.isMarked||!1}}}async function Bt(t){const s=t.replace(/\.md$/i,"");if(/^[a-f0-9-]{8,}$/i.test(s))return s;const a=await re.get("/knowledge?limit=1000"),i=(a.data?.data?.data||a.data?.data||[]).find(o=>{const u=o.title||o.name||"";return u===s||u+".md"===t});if(i?.id)return i.id;throw new Error(`Knowledge entry not found: ${t}`)}async function bl(t,s){const a=t.body?.getReader();if(!a)throw new Error("ReadableStream not available");const r=new TextDecoder;let i="",o="";for(;;){const{done:u,value:p}=await a.read();if(u)break;const c=r.decode(p,{stream:!0});i+=c;const x=i.split(`
22
+ `);i=x.pop()||"";for(const h of x){if(h.startsWith(":")||!h.startsWith("data: "))continue;const g=h.slice(6).trim();if(!(!g||g==="[DONE]"))try{const d=JSON.parse(g);if(s(d),d.type==="text:delta"&&d.delta)o+=d.delta;else if(d.type==="stream:done"&&d.text)o=d.text;else if(d.type==="stream:error")throw new Error(d.message||"Stream error")}catch(d){if(d instanceof SyntaxError)continue;throw d}}}return o}const ee={async fetchData(){const[t,s,a]=await Promise.all([re.get("/knowledge?limit=1000").catch(()=>({data:{success:!0,data:{data:[]}}})),re.get("/ai/config").catch(()=>({data:{success:!0,data:{provider:"",model:""}}})),re.get("/modules/project-info").catch(()=>({data:{success:!0,data:{projectRoot:""}}}))]),r=t.data?.data?.data||t.data?.data?.items||[],o=r.filter(d=>d.lifecycle==="active").map(Na),u=r.filter(d=>d.lifecycle==="pending"),p={};for(const d of u){const l=d.category||d.language||"_pending";p[l]||(p[l]={targetName:l,scanTime:d.createdAt,items:[]}),p[l].items.push(d)}const c=s.data?.data||{provider:"",model:""},x={};for(const d of r)d.id&&d.title&&(x[d.id]=d.title);const h=a.data?.data?.projectRoot||"",g=a.data?.data?.projectName||"";return{rootSpec:{list:[]},recipes:o,candidates:p,projectRoot:h,projectName:g,watcherStatus:"active",aiConfig:{provider:c.provider||"",model:c.model||""},idTitleMap:x}},async fetchTargets(){return((await re.get("/modules/targets")).data?.data||{}).targets||[]},async getTargetFiles(t,s){const r=(await re.post("/modules/target-files",{target:t},{signal:s})).data?.data||{};return{files:r.files||[],count:r.total||r.files?.length||0}},async scanTarget(t,s){const r=(await re.post("/modules/scan",{target:t},{signal:s,timeout:6e5})).data?.data||{};return{recipes:r.recipes||r.result||[],scannedFiles:r.scannedFiles||[],message:r.message||"",noAi:!!r.noAi}},async scanTargetStream(t,s,a){let r;const i=await fetch("/api/v1/modules/scan/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({target:t}),signal:a});if(!i.ok)throw new Error(`Scan stream start failed: ${i.status}`);if(r=(await i.json()).sessionId,!r)throw new Error("No sessionId returned");return new Promise((u,p)=>{const c=`/api/v1/modules/scan/events/${r}`,x=new EventSource(c);let h=!1,g={recipes:[],scannedFiles:[],message:"",noAi:!1};function d(){x.close()}if(x.onmessage=l=>{try{const f=JSON.parse(l.data);s(f),f.type==="scan:result"&&(g={recipes:f.recipes||[],scannedFiles:f.scannedFiles||[],message:f.message||"",noAi:!!f.noAi}),f.type==="stream:done"&&(d(),h=!0,u(g)),f.type==="stream:error"&&(d(),h=!0,p(new Error(f.message||"Scan stream error")))}catch{}},x.onerror=()=>{h||(d(),h=!0,g.recipes.length>0?u(g):p(new Error("EventSource connection failed")))},a){const l=()=>{h||(d(),h=!0,p(new DOMException("The operation was aborted.","AbortError")))};if(a.aborted){l();return}a.addEventListener("abort",l,{once:!0})}})},async scanProject(t){const a=(await re.post("/modules/scan-project",{},{signal:t,timeout:6e5})).data?.data||{};return{targets:a.targets||[],recipes:a.recipes||[],guardAudit:a.guardAudit||null,scannedFiles:a.scannedFiles||[],partial:a.partial||!1}},async browseDirectories(t="",s=3){const a=new URLSearchParams;return t&&a.set("path",t),s&&a.set("depth",String(s)),(await re.get(`/modules/browse-dirs?${a.toString()}`)).data?.data?.directories||[]},async scanFolderStream(t,s,a){const r=await fetch("/api/v1/modules/scan-folder/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t}),signal:a});if(!r.ok)throw new Error(`Scan folder start failed: ${r.status}`);const o=(await r.json()).sessionId;if(!o)throw new Error("No sessionId returned");return new Promise((u,p)=>{const c=`/api/v1/modules/scan/events/${o}`,x=new EventSource(c);let h=!1,g={recipes:[],scannedFiles:[],message:"",noAi:!1};function d(){x.close()}if(x.onmessage=l=>{try{const f=JSON.parse(l.data);s(f),f.type==="scan:result"&&(g={recipes:f.recipes||[],scannedFiles:f.scannedFiles||[],message:f.message||"",noAi:!!f.noAi}),f.type==="stream:done"&&(d(),h=!0,u(g)),f.type==="stream:error"&&(d(),h=!0,p(new Error(f.message||"Scan folder stream error")))}catch{}},x.onerror=()=>{h||(d(),h=!0,g.recipes.length>0?u(g):p(new Error("EventSource connection failed")))},a){const l=()=>{h||(d(),h=!0,p(new DOMException("The operation was aborted.","AbortError")))};if(a.aborted){l();return}a.addEventListener("abort",l,{once:!0})}})},async bootstrap(t){const a=(await re.post("/modules/bootstrap",{},{signal:t,timeout:3e5})).data?.data||{};return{report:a.report||{},targets:a.targets||[],filesByTarget:a.filesByTarget||{},dependencyGraph:a.dependencyGraph||null,languageStats:a.languageStats||{},primaryLanguage:a.primaryLanguage||"",guardSummary:a.guardSummary||null,guardViolationFiles:a.guardViolationFiles||[],bootstrapCandidates:a.bootstrapCandidates||{created:0,failed:0},bootstrapSession:a.bootstrapSession||null,asyncFill:a.asyncFill||!1,message:a.message||""}},async getBootstrapStatus(){return(await re.get("/modules/bootstrap/status")).data?.data||{status:"idle"}},async getDepGraph(t){return(await re.get(`/modules/dep-graph?level=${t}`)).data?.data||{}},async getProjectInfo(){try{return(await re.get("/modules/project-info")).data?.data||{}}catch{return{primaryLanguage:"unknown",discoverers:[],hasSpm:!1}}},async syncSnippets(t="all"){return(await re.post("/commands/install",{target:t})).data},async refreshProject(){try{await re.post("/modules/update-map")}catch{await re.post("/commands/spm-map")}},async extractFromPath(t){const a=(await re.post("/extract/path",{relativePath:t})).data?.data||{};return{result:a.result||[],isMarked:a.isMarked||!1}},async extractFromText(t,s){const r=(await re.post("/extract/text",{text:t,...s?{relativePath:s}:{}})).data?.data||{};return Array.isArray(r.result)&&r.result.length>0?r.result[0]:r},async saveRecipe(t,s){const a=hl(s),r=a.title||t.replace(/\.md$/,""),i={trigger:a.trigger,headers:a.headers,difficulty:a.difficulty,authority:a.authority,version:a.version},o={pattern:a.codePattern||"",rationale:a.rationaleText||"",steps:a.bestPracticesText?[a.bestPracticesText]:[],codeChanges:[],verification:null,markdown:a.usageGuide||""},u={};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&&(u.preconditions=x);const h=c.filter(g=>!g.startsWith("- ")&&!g.startsWith("**"));h.length>0&&(u.boundaries=h)}const p={title:r,language:a.language,category:a.category,description:a.summary,knowledgeType:a.knowledgeType||"code-pattern",complexity:a.complexity||"intermediate",scope:a.scope||null,tags:a.tags||[],content:o,constraints:u,dimensions:i};a.kind&&(p.kind=a.kind),a.doClause&&(p.doClause=a.doClause),a.dontClause&&(p.dontClause=a.dontClause),a.whenClause&&(p.whenClause=a.whenClause),a.topicHint&&(p.topicHint=a.topicHint);try{const c=await Bt(t);await re.patch(`/knowledge/${c}`,p);return}catch{}await re.post("/knowledge",p)},async deleteRecipe(t){const s=await Bt(t);await re.delete(`/knowledge/${s}`)},async getRecipeByName(t){const s=await Bt(t),r=(await re.get(`/knowledge/${s}`)).data?.data;if(!r)throw new Error("Recipe not found");const i=r.content||{};return{name:t,content:i.pattern||i.markdown||""}},async setRecipeAuthority(t,s){const a=await Bt(t);await re.patch(`/knowledge/${a}/quality`,{codeCompleteness:s,projectAdaptation:s,documentationClarity:s})},async updateRecipeRelations(t,s){const a=await Bt(t);await re.patch(`/knowledge/${a}`,{relations:s})},async getCandidate(t){const a=(await re.get(`/knowledge/${t}`)).data?.data;if(!a)throw new Error("Knowledge entry not found");return a},async deleteCandidate(t){await re.delete(`/knowledge/${t}`)},async promoteCandidateToRecipe(t,s){const r=(await re.patch(`/knowledge/${t}/publish`)).data?.data;return{recipe:r,candidate:r}},async enrichCandidates(t){return(await re.post("/candidates/enrich",{candidateIds:t})).data?.data||{enriched:0,total:0,results:[]}},async bootstrapRefine(t,s,a){return(await re.post("/candidates/bootstrap-refine",{candidateIds:t,userPrompt:s,dryRun:a},{timeout:3e5})).data?.data||{refined:0,total:0,errors:[],results:[]}},async refinePreview(t,s){return(await re.post("/candidates/refine-preview",{candidateId:t,userPrompt:s},{timeout:12e4})).data?.data||{}},async refineApply(t,s,a){return(await re.post("/candidates/refine-apply",{candidateId:t,userPrompt:s,preview:a},{timeout:12e4})).data?.data||{}},async getKnowledgeGraph(t=500){return(await re.get(`/search/graph/all?limit=${t}`)).data?.data||{edges:[],nodeLabels:{},nodeTypes:{},nodeCategories:{}}},async getGraphStats(){return(await re.get("/search/graph/stats")).data?.data||{totalEdges:0,byRelation:{},nodeTypes:[]}},async discoverRelations(t=20){const s=await re.post("/recipes/discover-relations",{batchSize:t});if(!s.data?.success)throw new Error(s.data?.error?.message||"启动失败");return s.data?.data||{status:"unknown"}},async getDiscoverRelationsStatus(){return(await re.get("/recipes/discover-relations/status")).data?.data||{status:"idle"}},async deleteAllCandidatesInTarget(t){const a=(await re.get(`/knowledge?category=${encodeURIComponent(t)}&limit=1000`)).data?.data?.data||[];let r=0;for(const i of a)try{await re.delete(`/knowledge/${i.id}`),r++}catch{}return{deleted:r}},async promoteToCandidate(t,s){const a=fl(t,s,"review-promote");return{ok:!0,candidateId:(await re.post("/knowledge",a)).data?.data?.id||""}},async getCandidateSimilarity(t,s){return(await re.post("/search/similarity",{code:t,language:s}).catch(()=>({data:{data:{similar:[]}}}))).data?.data||{similar:[]}},async getCandidateSimilarityEx(t){return(await re.post("/search/similarity",t).catch(()=>({data:{data:{similar:[]}}}))).data?.data||{similar:[]}},async getRecipeContentByName(t){const s=await Bt(t),r=(await re.get(`/knowledge/${s}`)).data?.data;if(!r)throw new Error("Recipe not found");const o=Na(r).content,u=[o?.pattern,o?.markdown].filter(Boolean).join(`
24
+
25
+ `)||"";return{name:t,content:u}},async getAiProviders(){return(await re.get("/ai/providers")).data?.data||[]},async setAiConfig(t,s){return(await re.post("/ai/config",{provider:t,model:s})).data?.data||{provider:t,model:s}},async chat(t,s,a){const i=(await re.post("/ai/chat",{prompt:t,history:s},{signal:a})).data?.data||{};return{text:i.reply||i.text||"",hasContext:i.hasContext}},async chatStream(t,s,a,r,i){const o=await fetch("/api/v1/ai/chat/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:t,history:s,...i?{lang:i}:{}}),signal:r});if(!o.ok)throw new Error(`Chat start failed: ${o.status}`);if((o.headers.get("content-type")||"").includes("text/event-stream")){let x={text:""};const h=await bl(o,g=>{a(g),g.type==="stream:done"&&(g.text&&(x.text=g.text),x.toolCalls=g.toolCalls,x.hasContext=g.hasContext)});return!x.text&&h&&(x.text=h),x}const p=await o.json(),c=p.sessionId;if(!c)throw new Error(`No sessionId returned: ${JSON.stringify(p)}`);return new Promise((x,h)=>{const g=`/api/v1/ai/chat/events/${c}`,d=new EventSource(g);let l="",f={text:""},y=!1;function D(){d.close()}if(d.onmessage=S=>{try{const T=JSON.parse(S.data);if(T.type==="stream:start")return;a(T),T.type==="text:delta"&&T.delta&&(l+=T.delta),T.type==="stream:done"&&(f={text:T.text||l,toolCalls:T.toolCalls,hasContext:T.hasContext},D(),y=!0,x(f)),T.type==="stream:error"&&(D(),y=!0,h(new Error(T.message||"Stream error")))}catch{}},d.onerror=()=>{y||(D(),l?(y=!0,x({text:l})):(y=!0,h(new Error("EventSource connection failed"))))},r){const S=()=>{y||(D(),y=!0,h(new DOMException("The operation was aborted.","AbortError")))};r.aborted?S():r.addEventListener("abort",S,{once:!0})}})},async refinePreviewStream(t,s,a,r){const i=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(!i.ok)throw new Error(`Refine stream start failed: ${i.status}`);const u=(await i.json()).sessionId;if(!u)throw new Error("No sessionId returned");return new Promise((p,c)=>{const x=`/api/v1/candidates/refine-preview/events/${u}`,h=new EventSource(x);let g=!1;function d(){h.close()}r&&r.addEventListener("abort",()=>{d(),g||(g=!0,c(new DOMException("Aborted","AbortError")))},{once:!0}),h.onmessage=l=>{try{const f=JSON.parse(l.data);a(f),f.type==="stream:done"&&(d(),g=!0,p({candidateId:f.candidateId||t,before:f.before||{},after:f.after||{},preview:f.preview||null})),f.type==="stream:error"&&(d(),g=!0,c(new Error(f.message||"Refine stream error")))}catch{}},h.onerror=()=>{d(),g||(g=!0,c(new Error("Refine EventSource connection lost")))}})},async summarizeCode(t,s){const a=await re.post("/ai/summarize",{code:t,language:s});return a.data?.data||a.data||{}},async translate(t,s){const a=await re.post("/ai/translate",{summary:t,usageGuide:s}),r=a.data?.data||{summaryEn:"",usageGuideEn:""};return a.data?.warning&&(r.warning=a.data.warning),r},async search(t,s={}){const{mode:a="bm25",type:r,limit:i=20,signal:o,context:u}=s,p=d=>{if(!d)return{};if(typeof d=="object")return d;try{return JSON.parse(String(d))}catch{return{markdown:String(d)}}};if(u){const l=(await re.post("/search/context-aware",{keyword:t,limit:i,language:u.language,sessionHistory:u.sessionHistory||[]},{signal:o}).catch(()=>({data:{data:{}}}))).data?.data||{},f=(l.results||[]).map(y=>{const D=p(y.content);return{title:(y.name||"").replace(/\.md$/,""),content:D,score:y.similarity||0,qualityScore:y.qualityScore||0,usageCount:y.usageCount||0,authorityScore:y.authority||0,matchType:y.matchType}});return{items:f,total:l.total||f.length,mode:"bm25",ranked:!0}}const c=new URLSearchParams({q:t,mode:a,limit:String(i)});r&&c.set("type",r);const h=(await re.get(`/search?${c}`,{signal:o})).data?.data||{},g=(h.items||[]).map(d=>({...d,content:p(d.content)}));return{items:g,total:h.totalResults||h.total||g.length,mode:h.mode,ranked:h.ranked}},async getGuardRules(){const s=(await re.get("/rules?limit=100")).data?.data||{},a=s.data||s.items||[],r={};for(const i of a)r[i.id]=i;return{rules:r,projectLanguages:s.projectLanguages||[]}},async getGuardViolations(){const s=(await re.get("/violations")).data?.data||{};return{runs:s.data||s.items||[]}},async clearViolations(){await re.post("/violations/clear")},async saveGuardRule(t){return(await re.post("/rules",t)).data?.data||{}},async insertAtSearchMark(t){return{success:!1}},async listSkills(){return(await re.get("/skills")).data?.data||{skills:[],total:0}},async loadSkill(t,s){const a=s?`?section=${encodeURIComponent(s)}`:"";return(await re.get(`/skills/${encodeURIComponent(t)}${a}`)).data?.data||{}},async createSkill(t){return(await re.post("/skills",t)).data?.data||{}},async updateSkill(t,s){return(await re.put(`/skills/${encodeURIComponent(t)}`,s)).data?.data||{}},async deleteSkill(t){return(await re.delete(`/skills/${encodeURIComponent(t)}`)).data?.data||{}},async suggestSkills(){return(await re.get("/skills/suggest")).data?.data||{suggestions:[],analysisContext:{}}},async getSignalStatus(){return(await re.get("/skills/signal-status")).data?.data||{running:!1,mode:"off",snapshot:null}},async aiGenerateSkill(t){return(await re.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?.data||{reply:""}},async getLlmEnvConfig(){return(await re.get("/ai/env-config")).data?.data||{vars:{},hasEnvFile:!1,llmReady:!1}},async getTokenUsage7Days(){return(await re.get("/ai/token-usage")).data?.data||{daily:[],bySource:[],summary:{input_tokens:0,output_tokens:0,total_tokens:0,call_count:0,avg_per_call:0}}},async saveLlmEnvConfig(t){return(await re.post("/ai/env-config",t)).data?.data||{vars:{},hasEnvFile:!1,llmReady:!1}},async knowledgeList(t={}){const s=new URLSearchParams;t.page&&s.set("page",String(t.page)),t.limit&&s.set("limit",String(t.limit)),t.lifecycle&&s.set("lifecycle",t.lifecycle),t.kind&&s.set("kind",t.kind),t.category&&s.set("category",t.category),t.language&&s.set("language",t.language),t.keyword&&s.set("keyword",t.keyword),t.tag&&s.set("tag",t.tag),t.source&&s.set("source",t.source);const a=s.toString();return(await re.get(`/knowledge${a?`?${a}`:""}`)).data?.data||{data:[],pagination:{page:1,pageSize:20,total:0}}},async knowledgeStats(){return(await re.get("/knowledge/stats")).data?.data||{total:0,pending:0,active:0,deprecated:0,rules:0,patterns:0,facts:0}},async knowledgeGet(t){return(await re.get(`/knowledge/${t}`)).data?.data},async knowledgeCreate(t){return(await re.post("/knowledge",t)).data?.data},async knowledgeUpdate(t,s){return(await re.patch(`/knowledge/${t}`,s)).data?.data},async knowledgeDelete(t){await re.delete(`/knowledge/${t}`)},async knowledgeLifecycle(t,s,a){return(await re.patch(`/knowledge/${t}/${s}`,a?{reason:a}:{})).data?.data},async knowledgeBatchPublish(t){return(await re.post("/knowledge/batch-publish",{ids:t})).data?.data||{published:[],failed:[],successCount:0,failureCount:0}},async knowledgeRecordUsage(t,s="adoption",a){await re.post(`/knowledge/${t}/usage`,{type:s,feedback:a})},async knowledgeUpdateQuality(t){return(await re.patch(`/knowledge/${t}/quality`)).data?.data||{quality:{}}},async wikiGenerate(){await re.post("/wiki/generate")},async wikiUpdate(){await re.post("/wiki/update")},async wikiAbort(){await re.post("/wiki/abort")},async wikiStatus(){return(await re.get("/wiki/status")).data?.data||{task:{status:"idle"}}},async wikiFiles(){return(await re.get("/wiki/files")).data?.data||{files:[],exists:!1}},async wikiFileContent(t){return(await re.get(`/wiki/file/${t}`)).data?.data||{path:t,content:"",size:0}},async getLang(){return(await re.get("/ai/lang")).data?.data?.lang||"zh"},async setLang(t){await re.post("/ai/lang",{lang:t})}},vl=!1,Ms="auth_token",_s="auth_user";function yl(){const[t,s]=n.useState(()=>localStorage.getItem(Ms)),[a,r]=n.useState(()=>{try{const x=localStorage.getItem(_s);return x?JSON.parse(x):null}catch{return null}}),[i,o]=n.useState(!1),u=n.useCallback(async(x,h)=>{o(!0);try{const d=(await aa.post("/api/v1/auth/login",{username:x,password:h})).data;if(d.success){const l=d.data.token,f=d.data.user??{username:x,role:"developer"};return localStorage.setItem(Ms,l),localStorage.setItem(_s,JSON.stringify(f)),s(l),r(f),{success:!0}}return{success:!1,error:d.error?.message||"登录失败"}}catch(g){return{success:!1,error:ve(g,"网络错误")}}finally{o(!1)}},[]),p=n.useCallback(()=>{localStorage.removeItem(Ms),localStorage.removeItem(_s),s(null),r(null)},[]);n.useEffect(()=>{},[]);const c=n.useMemo(()=>!0,[t,a]);return{authEnabled:vl,isAuthenticated:c,isLoading:i,user:a,login:u,logout:p}}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]=n.useState(()=>"developer"),[r,i]=n.useState("anonymous"),[o,u]=n.useState("probe"),[p,c]=n.useState(!0),[x,h]=n.useState(null),g=n.useCallback(async()=>{c(!0);try{const D=localStorage.getItem("auth_token"),S={};D&&(S.Authorization=`Bearer ${D}`);const T=await aa.get("/api/v1/auth/probe",{headers:S});if(T.data.success){const z=T.data.data;a(z.role),i(z.user),u(z.mode),h(z.probeCache??null)}}catch{a("developer")}finally{c(!1)}},[]);n.useEffect(()=>{g()},[t,g]);const d=n.useCallback((D,S)=>{const T=jl[s]||[];if(T.includes("*"))return!0;const z=S?`${D}:${S}`:D;if(T.includes(z))return!0;const O=D.split(":")[0];return!!(T.includes(`${O}:*`)||O==="read"&&T.includes("read:*"))},[s]),l=n.useMemo(()=>s==="developer",[s]),f=n.useMemo(()=>s==="developer",[s]),y=n.useMemo(()=>s!=="developer",[s]);return{role:s,user:r,mode:o,isLoading:p,isAdmin:l,canWrite:f,isReadOnly:y,can:d,probeCache:x,refresh:g}}let Wt=null;function la(){return Wt||(Wt=Wr(window.location.origin,{path:"/socket.io",transports:["websocket"],reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:2e3,reconnectionDelayMax:1e4}),Wt.on("connect",()=>{Wt.emit("join-notifications")})),Wt}const Fs={activeRound:0,round1:{status:"idle"},round2:{status:"idle"},round3:{status:"idle"}};function Nl(){const[t,s]=n.useState(null),[a,r]=n.useState(!1),[i,o]=n.useState(Fs),[u,p]=n.useState(0),c=n.useRef(null),x=n.useRef(null);n.useEffect(()=>{const l=la(),f=()=>{r(!0),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>D(),500)},y=()=>r(!1),D=async()=>{try{const v=await ee.getBootstrapStatus();v&&v.status==="running"&&v.tasks&&s(_=>!_||_.id===v.id||v.progress>(_?.progress??0)?(c.current=v.id,v):_)}catch{}},S=()=>D(),T=v=>{c.current=v.sessionId,o(Fs),s({id:v.sessionId,status:"running",progress:0,total:v.total,completed:0,failed:0,filling:0,skeleton:v.total,startedAt:v.startedAt||Date.now(),totalToolCalls:0,elapsedMs:0,tasks:v.tasks.map(_=>({id:_.id,status:"skeleton",meta:{type:_.type,dimId:_.dimId,label:_.label,skillWorthy:_.skillWorthy,skillMeta:_.skillMeta}}))})},z=v=>{s(_=>{if(!_)return _;const ae=_.tasks.map(Q=>Q.id===v.taskId?{...Q,status:"filling",startedAt:Date.now()}:Q);return{..._,progress:v.progress,tasks:ae,filling:ae.filter(Q=>Q.status==="filling").length,skeleton:ae.filter(Q=>Q.status==="skeleton").length}})},O=v=>{s(ae=>{if(!ae)return ae;const Q=ae.tasks.map(me=>me.id===v.taskId?{...me,status:"completed",completedAt:Date.now(),result:v.result}:me);return{...ae,progress:v.progress,completed:v.completed,total:v.total,totalToolCalls:v.totalToolCalls??ae.totalToolCalls,elapsedMs:v.elapsedMs??ae.elapsedMs,tasks:Q,filling:Q.filter(me=>me.status==="filling").length,skeleton:Q.filter(me=>me.status==="skeleton").length}}),(Number(v.result?.created)||Number(v.result?.extracted)||0)>0&&p(ae=>ae+1)},G=v=>{s(_=>{if(!_)return _;const ae=_.tasks.map(Q=>Q.id===v.taskId?{...Q,status:"failed",completedAt:Date.now(),error:v.error}:Q);return{..._,progress:v.progress,failed:ae.filter(Q=>Q.status==="failed").length,tasks:ae,filling:ae.filter(Q=>Q.status==="filling").length,skeleton:ae.filter(Q=>Q.status==="skeleton").length}})},le=v=>{s(_=>{if(!_||v.sessionId&&_.id!==v.sessionId)return _;const ae=_.tasks.map(Q=>Q.status==="skeleton"||Q.status==="filling"?{...Q,status:"completed",completedAt:Date.now()}:Q);return{..._,status:ae.some(Q=>Q.status==="failed")?"completed_with_errors":"completed",progress:100,completed:ae.filter(Q=>Q.status==="completed").length,summary:v.summary,tasks:ae,filling:0,skeleton:0}})},w=v=>{o(_=>({..._,activeRound:1,round1:{status:"running",total:v.total}}))},k=v=>{o(_=>({..._,activeRound:1,round1:{status:"completed",total:v.total,kept:v.kept,dropped:v.dropped,merged:v.merged}}))},I=v=>{o(_=>({..._,activeRound:2,round2:{status:"running",total:v.total}}))},q=v=>{o(_=>({..._,activeRound:2,round2:{..._.round2,status:"running",current:v.current,total:v.total,progress:v.progress}}))},W=v=>{o(_=>({..._,activeRound:2,round2:{status:"completed",total:v.total,refined:v.refined,progress:100}}))},K=v=>{o(_=>({..._,activeRound:3,round3:{status:"running",total:v.total}}))},C=v=>{o(_=>({..._,activeRound:3,round3:{status:"completed",total:v.total,afterDedup:v.afterDedup,relationsFound:v.relationsFound}}))};return l.on("connect",f),l.on("disconnect",y),l.io.on("reconnect",S),l.on("bootstrap:started",T),l.on("bootstrap:task-started",z),l.on("bootstrap:task-completed",O),l.on("bootstrap:task-failed",G),l.on("bootstrap:all-completed",le),l.on("review:round1-started",w),l.on("review:round1-completed",k),l.on("review:round2-started",I),l.on("review:round2-progress",q),l.on("review:round2-completed",W),l.on("review:round3-started",K),l.on("review:round3-completed",C),r(l.connected),l.connected&&D(),()=>{x.current&&clearTimeout(x.current),l.off("connect",f),l.off("disconnect",y),l.io.off("reconnect",S),l.off("bootstrap:started",T),l.off("bootstrap:task-started",z),l.off("bootstrap:task-completed",O),l.off("bootstrap:task-failed",G),l.off("bootstrap:all-completed",le),l.off("review:round1-started",w),l.off("review:round1-completed",k),l.off("review:round2-started",I),l.off("review:round2-progress",q),l.off("review:round2-completed",W),l.off("review:round3-started",K),l.off("review:round3-completed",C)}},[]);const h=n.useCallback(()=>{c.current=null,s(null),o(Fs)},[]),g=n.useCallback(l=>{l&&s(f=>{if(f&&f.id===l.id){const y=(f.filling??0)+(f.completed??0)+(f.failed??0),D=(l.filling??0)+(l.completed??0)+(l.failed??0);if(f.progress>l.progress||y>D)return f}return c.current=l.id,l})},[]),d=t?.status==="completed"||t?.status==="completed_with_errors";return{session:t,isConnected:a,isAllDone:d,reviewState:i,candidateCreatedTick:u,resetSession:h,initFromApiResponse:g}}const H={xs:12,sm:14,md:16,lg:20,xl:24,xxl:32,xxxl:48};function he(...t){return Vr(Jr(t))}const wr=Qr,Pt=Xr,Lt=Zr,yt=n.forwardRef(({className:t,sideOffset:s=6,...a},r)=>e.jsx(Yr,{children:e.jsx(Ga,{ref:r,sideOffset:s,className:he("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})}));yt.displayName=Ga.displayName;function ka({item:t,active:s,onClick:a}){return e.jsxs(Pt,{delayDuration:300,children:[e.jsx(Lt,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:a,className:he("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(yt,{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:i,onLogout:o})=>{const{t:u,lang:p,setLang:c}=Ae(),{isDark:x,toggle:h}=Is(),g=[{tab:"recipes",icon:lr,label:u("sidebar.recipes")},{tab:"spm",icon:jt,label:u("sidebar.moduleExplorer")},{tab:"candidates",icon:tt,label:u("sidebar.candidates",{count:a})},{tab:"knowledge",icon:Qs,label:u("sidebar.batchManage")},{tab:"depgraph",icon:Ds,label:u("sidebar.depGraph")},{tab:"knowledgegraph",icon:ws,label:u("sidebar.knowledgeGraph")},{tab:"guard",icon:at,label:u("sidebar.guard")},{tab:"skills",icon:qe,label:u("sidebar.skills"),badge:r>0?r:void 0},{tab:"wiki",icon:ct,label:u("sidebar.repoWiki")},{tab:"ai",icon:wt,label:u("sidebar.aiAssistant")},{tab:"help",icon:or,label:u("sidebar.help")}],d=g.slice(0,9),l=g.slice(9);return e.jsx(wr,{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:[d.map(f=>e.jsx(ka,{item:f,active:t===f.tab,onClick:()=>s(f.tab)},f.tab)),e.jsx("div",{className:"w-6 separator-gradient my-2"}),l.map(f=>e.jsx(ka,{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(Pt,{delayDuration:300,children:[e.jsx(Lt,{asChild:!0,children:e.jsx("button",{onClick:()=>c(p==="zh"?"en":"zh"),className:"flex items-center justify-center w-10 h-10 rounded-[var(--radius-md)] text-[var(--fg-subtle)] hover:bg-[var(--bg-muted)] hover:text-[var(--fg-default)] transition-colors",children:e.jsx(vn,{size:18})})}),e.jsx(yt,{side:"right",children:u("header.langSwitch")})]}),e.jsxs(Pt,{delayDuration:300,children:[e.jsx(Lt,{asChild:!0,children:e.jsx("button",{onClick:h,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(yt,{side:"right",children:u(x?"header.lightMode":"header.darkMode")})]}),i&&e.jsxs(Pt,{delayDuration:300,children:[e.jsx(Lt,{asChild:!0,children:e.jsx("button",{onClick:o,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(ir,{size:18})})}),e.jsxs(yt,{side:"right",className:"flex items-center gap-2",children:[e.jsx("span",{children:i}),o&&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}),u("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 oa(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 ft=({code:t,language:s="text",className:a="",showLineNumbers:r=!1})=>{const i=Cl[s?.toLowerCase()]||s?.toLowerCase()||"text",o=a.includes("!rounded-none"),u=oa(t);return e.jsx("div",{className:`rounded-xl overflow-x-auto text-sm min-w-0 ${a}`,children:e.jsx($a,{language:i,style:Ha,showLineNumbers:r,customStyle:{margin:0,padding:"1rem 1.25rem",fontSize:"0.8125rem",lineHeight:1.5,borderRadius:o?0:"0.75rem",overflowX:"auto"},codeTagProps:{className:"language-highlighted",style:{fontFamily:"ui-monospace, monospace"}},PreTag:"div",children:u})})};let Sl=0,Ca="";function Al(t){const s=t?"dark":"default";s!==Ca&&(Oa.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"}}:{}}),Ca=s)}const Nr=({code:t})=>{const{t:s}=Ae(),{isDark:a}=Is(),[r,i]=n.useState(""),[o,u]=n.useState("");return n.useEffect(()=>{let p=!1;const c=`mermaid_${Sl++}`;async function x(){Al(a);try{const{svg:h}=await Oa.render(c,t.trim());p||(i(h),u(""))}catch(h){p||(u(ve(h,"Mermaid render failed")),i(""));try{document.getElementById("d"+c)?.remove()}catch{}}}return x(),()=>{p=!0}},[t,a]),o?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 ia(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 Rl(t){if(!t||typeof t!="string")return t;const s=t.split(`
52
+ `),a=[];let r=!1;for(let i=0;i<s.length;i++){const o=s[i];if(/^\s*(`{3,}|~{3,})/.test(o)){r=!r,a.push(o);continue}if(r){a.push(o);continue}const u=s[i+1];o!==""&&u!==void 0&&u!==""?a.push(o+" "):a.push(o)}return a.join(`
53
+ `)}const Il=/^\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=[],i=!1,o=!1,u=[];for(let p=0;p<a.length;p++){const c=a[p],x=/^\s*(`{3,}|~{3,})(.*)$/.exec(c);if(x&&!o&&!i)if(x[2].trim().toLowerCase()==="mermaid"){r.length>0&&(s.push({type:"markdown",content:r.join(`
55
+ `)}),r=[]),i=!0,u=[];continue}else{o=!0,r.push(c);continue}if(i&&x){s.push({type:"mermaid",content:u.join(`
56
+ `)}),i=!1,u=[];continue}if(o&&x){o=!1,r.push(c);continue}i?u.push(c):r.push(c)}return i&&u.length>0&&s.push({type:"mermaid",content:u.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,...i}){const o=/language-(\w+)/.exec(a||""),u=Array.isArray(r)?r.join(""):String(r),p=u.replace(/\n$/,""),c=u.includes(`
59
+ `)||!!o;return c&&Il.test(p)?e.jsx(Nr,{code:p}):c&&o?e.jsx(ft,{code:p,language:o[1],showLineNumbers:t}):c?e.jsx(ft,{code:p,language:"text",showLineNumbers:t}):e.jsx("code",{className:"px-1.5 py-0.5 bg-[var(--bg-subtle)] text-[var(--fg-primary)] rounded text-[0.9em] font-mono border border-[var(--border-default)]",...i,children:r})},p:({children:s})=>e.jsx("p",{className:"mb-4 leading-7 last:mb-0",children:s}),h1:({children:s,...a})=>{const r=typeof s=="string"?s.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g,"-").replace(/(^-|-$)/g,""):void 0;return e.jsx("h1",{id:r,className:"text-[1.75rem] font-bold mb-4 mt-8 first:mt-0 pb-2 border-b border-[var(--border-default)] text-[var(--fg-primary)] leading-tight scroll-mt-20",...a,children:s})},h2:({children:s,...a})=>{const r=typeof s=="string"?s.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g,"-").replace(/(^-|-$)/g,""):void 0;return e.jsx("h2",{id:r,className:"text-xl font-bold mb-3 mt-8 pb-1.5 border-b border-[var(--border-default)] text-[var(--fg-primary)] leading-snug scroll-mt-20",...a,children:s})},h3:({children:s,...a})=>{const r=typeof s=="string"?s.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g,"-").replace(/(^-|-$)/g,""):void 0;return e.jsx("h3",{id:r,className:"text-lg font-semibold mb-2 mt-6 text-[var(--fg-primary)] leading-snug scroll-mt-20",...a,children:s})},h4:({children:s,...a})=>{const r=typeof s=="string"?s.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g,"-").replace(/(^-|-$)/g,""):void 0;return e.jsx("h4",{id:r,className:"text-base font-semibold mb-2 mt-5 text-[var(--fg-primary)] scroll-mt-20",...a,children:s})},strong:({children:s})=>e.jsx("strong",{className:"font-semibold text-[var(--fg-primary)]",children:s}),em:({children:s})=>e.jsx("em",{className:"italic text-[var(--fg-secondary)]",children:s}),del:({children:s})=>e.jsx("del",{className:"line-through text-[var(--fg-muted)]",children:s}),hr:()=>e.jsx("hr",{className:"my-8 border-0 h-px bg-[var(--border-default)]"}),ul:({children:s})=>e.jsx("ul",{className:"list-disc pl-6 mb-4 space-y-1.5 marker:text-[var(--fg-muted)]",children:s}),ol:({children:s})=>e.jsx("ol",{className:"list-decimal pl-6 mb-4 space-y-1.5 marker:text-[var(--fg-secondary)]",children:s}),li:({children:s,...a})=>{const r=a.node,i=r?.children?.[0]?.type==="element"&&r?.children?.[0]?.tagName==="input";return e.jsx("li",{className:`leading-7 ${i?"list-none -ml-6 flex items-start gap-2":""}`,children:s})},blockquote:({children:s})=>e.jsx("blockquote",{className:"border-l-4 border-blue-300 bg-blue-50/40 pl-4 pr-3 py-2 my-4 text-[var(--fg-secondary)] rounded-r-lg [&>p]:mb-2 [&>p:last-child]:mb-0",children:s}),a:({href:s,children:a})=>s?.startsWith("#")?e.jsx("a",{href:s,className:"text-blue-600 hover:text-blue-700 hover:underline underline-offset-2 decoration-blue-300/70 transition-colors",children:a}):e.jsx("a",{href:s,className:"text-blue-600 hover:text-blue-700 hover:underline underline-offset-2 decoration-blue-300/70 transition-colors",target:"_blank",rel:"noopener noreferrer",children:a}),img:({src:s,alt:a})=>e.jsx("img",{src:s,alt:a||"",className:"max-w-full h-auto rounded-lg border border-[var(--border-default)] my-4",loading:"lazy"}),table:({children:s})=>e.jsx("div",{className:"my-5 overflow-x-auto rounded-lg border border-[var(--border-default)]",children:e.jsx("table",{className:"w-full border-collapse text-sm",children:s})}),thead:({children:s})=>e.jsx("thead",{className:"bg-[var(--bg-subtle)] border-b border-[var(--border-default)]",children:s}),tbody:({children:s})=>e.jsx("tbody",{className:"divide-y divide-[var(--border-default)]",children:s}),tr:({children:s})=>e.jsx("tr",{className:"hover:bg-[var(--bg-subtle)] transition-colors",children:s}),th:({children:s})=>e.jsx("th",{className:"px-4 py-2.5 text-left text-xs font-semibold text-[var(--fg-secondary)] uppercase tracking-wider",children:s}),td:({children:s})=>e.jsx("td",{className:"px-4 py-2.5 text-[var(--fg-primary)] align-top",children:s}),input:({checked:s})=>e.jsx("input",{type:"checkbox",checked:s,readOnly:!0,className:"mt-1 w-4 h-4 rounded border-[var(--border-default)] text-blue-600 cursor-default"})}),Ct=({content:t,className:s="",showLineNumbers:a=!1,stripFrontmatter:r=!1})=>{const i=n.useMemo(()=>El(a),[a]),o=n.useMemo(()=>{let u=r?ia(t):t;return u=Dl(u),u=Rl(u),Tl(u)},[t,r]);return e.jsx("div",{className:`markdown-body text-[var(--fg-primary)] ${s}`,children:o.map((u,p)=>u.type==="mermaid"?e.jsx(Nr,{code:u.content},`mermaid-${p}`):e.jsx(en,{remarkPlugins:[tn],components:i,children:u.content},`md-${p}`))})},kr="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 _l(){try{const t=localStorage.getItem(kr);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s:[]}catch{return[]}}function Fl(t){try{const s=t.slice(0,Pl);localStorage.setItem(kr,JSON.stringify(s))}catch(s){console.warn("[ChatTopics] localStorage save failed:",s)}}function Cr(){const[t,s]=n.useState(()=>_l()),[a,r]=n.useState(null),i=n.useRef(t);n.useEffect(()=>{i.current=t},[t]);const o=n.useCallback(d=>{s(l=>{const f=typeof d=="function"?d(l):d;return Fl(f),f})},[]),u=n.useCallback(d=>{const l=Ll(),f={id:l,title:d||"新话题",messages:[],createdAt:Date.now(),updatedAt:Date.now()};return o(y=>[f,...y]),r(l),l},[o]),p=n.useCallback(d=>{o(l=>l.filter(f=>f.id!==d)),r(l=>l===d?null:l)},[o]),c=n.useCallback((d,l)=>{o(f=>{const y=f.findIndex(z=>z.id===d);if(y<0)return f;const D={...f[y],messages:l,updatedAt:Date.now()},S=Ml(l);S!=="新话题"&&(D.title=S);const T=[...f];return T[y]=D,T.splice(y,1),T.unshift(D),T})},[o]),x=n.useCallback(d=>i.current.find(l=>l.id===d),[]),h=n.useCallback(d=>{r(d)},[]),g=t.find(d=>d.id===a)??null;return{topics:t,activeTopicId:a,activeTopic:g,createTopic:u,deleteTopic:p,saveTopic:c,getTopic:x,switchTopic:h,setActiveTopicId:r}}function zl(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 i=String(r).split("/").pop()||r,o=Array.isArray(a.filePaths)&&a.filePaths.length>1?t("chatStream.andNFiles",{n:a.filePaths.length}):"";return`${i}${o}`}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 Sa(t,s,a){const r=zl(t,s),i=Bl(t,s,a);return i?`${r}: ${i}`:r}function Sr(t,s,a){const r=[],i=[];let o="";function u(c){s(x=>x.map(h=>h.id===t?{...h,content:c}:h))}function p(c){switch(c.type){case"step:start":{const x=c.phase==="user"?"":` [${c.phase}]`,h=a("chatStream.stepProgress",{step:c.step,maxSteps:c.maxSteps})+x+"...",g=r.length>0?r.join(`
60
+ `)+`
61
+
62
+ `+h:h;u(g);break}case"tool:start":{r.push(`🔧 ${Sa(a,c.tool,c.args)}...`),i.push({tool:c.tool,args:c.args}),u(r.join(`
63
+ `));break}case"tool:end":{const x=r.length-1;if(x>=0){const h=i[x]||{tool:c.tool},g=Sa(a,h.tool,h.args);if(c.status==="error"||c.error)r[x]=`❌ ${g} ${a("chatStream.toolFailed")} (${c.duration}ms)`;else{const d=c.resultSize>1e3?`${(c.resultSize/1024).toFixed(1)}KB`:a("chatStream.toolResultChars",{size:c.resultSize});r[x]=`✅ ${g} → ${d} (${c.duration}ms)`}u(r.join(`
64
+ `))}break}case"text:start":{o="";break}case"text:delta":{o+=c.delta||"";const x=r.length>0?r.join(`
65
+ `)+`
66
+
67
+ ---
68
+
69
+ `:"";u(x+o);break}}}return{onEvent:p,getState:()=>({answerText:o,toolLogs:r})}}const Ar=n.createContext({openChat:()=>{},openRefine:()=>{},close:()=>{},toggle:()=>{},newTopic:()=>{},isOpen:!1}),ns=()=>n.useContext(Ar),Gt=()=>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 i of Gl){const o=i.format||(c=>String(c??"")),u=o(t[i.key]),p=o(s[i.key]);p&&p!==u&&r.push({field:i.key,label:a(i.labelKey),before:u,after:p})}return r}function Aa(t){return{title:t.title||"",description:t.description||"",pattern:t.content?.pattern||"",markdown:t.content?.markdown||"",rationale:t.content?.rationale||"",tags:t.tags||[],confidence:t.reasoning?.confidence??.6,relations:t.relations||{},aiInsight:t.aiInsight||null,agentNotes:t.agentNotes||null}}const Hl=({diff:t,excludedFields:s=[],onToggleField:a})=>{const{t:r}=Ae();return t.length===0?e.jsx("p",{className:"text-xs text-[var(--fg-muted)] italic py-2",children:r("globalChat.diff.noChanges")}):e.jsx("div",{className:"space-y-2 mt-2",children:t.map(i=>{const o=s.includes(i.field);return e.jsxs("div",{className:`border rounded-lg overflow-hidden transition-opacity ${o?"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(dr,{size:10,className:o?"text-[var(--fg-muted)]":"text-emerald-500"}),e.jsx("span",{className:`text-[10px] font-bold flex-1 ${o?"text-[var(--fg-muted)] line-through":"text-[var(--fg-secondary)]"}`,children:i.label}),a&&(o?e.jsx("button",{onClick:()=>a(i.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(i.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(Ue,{size:10,className:"opacity-60 group-hover:opacity-100"}),r("globalChat.diff.exclude")]}))]}),!o&&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:i.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:i.after})]})]})]},i.field)})})},Dr=n.createContext(null),Ol=({children:t})=>{const{t:s}=Ae(),[a,r]=n.useState(!1),[i,o]=n.useState([]),[u,p]=n.useState(!1),[c,x]=n.useState(!1),[h,g]=n.useState(null),[d,l]=n.useState(new Set),[f,y]=n.useState(""),D=n.useRef([]),S=!!h,T=h?h.candidateIds[h.currentIdx]:null,z=h?h.candidates.find(K=>K.id===T):void 0,O=h?h.candidateIds.length>1:!1;n.useEffect(()=>{h&&z&&(o(K=>[...K,{id:Gt(),role:"system",content:s("globalChat.system.refinePrefix",{title:z.title,description:z.description||s("globalChat.system.noDescription")}),timestamp:Date.now()}]),y(""))},[h?.currentIdx]);const G=n.useCallback(()=>{g(null),r(!0)},[]),le=n.useCallback(K=>{g({...K,currentIdx:0}),l(new Set),o([]),D.current=[],r(!0)},[]),w=n.useCallback(()=>r(!1),[]),k=n.useCallback(()=>r(K=>!K),[]),I=n.useCallback(()=>{o([]),D.current=[],y(""),g(null),l(new Set)},[]),q={openChat:G,openRefine:le,close:w,toggle:k,newTopic:I,isOpen:a},W={messages:i,setMessages:o,loading:u,setLoading:p,applying:c,setApplying:x,refineCtx:h,setRefineCtx:g,applied:d,setApplied:l,lastPrompt:f,setLastPrompt:y,chatHistoryRef:D,isRefineMode:S,currentRefineId:T,currentRefineCandidate:z,isBatchRefine:O,close:w};return e.jsx(Ar.Provider,{value:q,children:e.jsx(Dr.Provider,{value:W,children:t})})},Kl=()=>{const{t,lang:s}=Ae(),a=n.useContext(Dr),{messages:r,setMessages:i,loading:o,setLoading:u,applying:p,setApplying:c,refineCtx:x,setRefineCtx:h,applied:g,setApplied:d,lastPrompt:l,setLastPrompt:f,chatHistoryRef:y,isRefineMode:D,currentRefineId:S,currentRefineCandidate:T,isBatchRefine:z,close:O}=a,G=n.useRef(null),le=n.useRef(null),[w,k]=n.useState(""),I=Cr(),q=n.useRef(null),W=n.useRef(!1);n.useEffect(()=>{if(D&&T){W.current=!0;const j=I.createTopic(t("globalChat.refineTopicPrefix",{title:T.title||t("globalChat.untitled")}));q.current=j,setTimeout(()=>{W.current=!1},50)}},[x]),n.useEffect(()=>{W.current||q.current&&r.length>0&&I.saveTopic(q.current,r)},[r]);const K=n.useCallback(()=>{if(!q.current){W.current=!0;const j=I.createTopic();q.current=j,setTimeout(()=>{W.current=!1},50)}},[I]);n.useEffect(()=>{G.current?.scrollIntoView({behavior:"smooth"})},[r,o]),n.useEffect(()=>{setTimeout(()=>le.current?.focus(),200)},[]);const C=D&&S&&r.some(j=>{if(j.role!=="assistant"||!j.diff||j.diff.length===0)return!1;const N=j.excludedFields||[];return j.diff.some(P=>!N.includes(P.field))})&&!g.has(S),v=n.useCallback((j,N)=>{i(P=>P.map(V=>{if(V.id!==j)return V;const ne=V.excludedFields||[],ue=ne.includes(N)?ne.filter(pe=>pe!==N):[...ne,N];return{...V,excludedFields:ue}}))},[]),_=n.useRef(null),ae=n.useCallback(async()=>{const j=w.trim();if(!(!j||o)){if(D||K(),k(""),i(N=>[...N,{id:Gt(),role:"user",content:j,timestamp:Date.now()}]),u(!0),D&&S){f(j);const N=Gt();i(V=>[...V,{id:N,role:"assistant",content:t("globalChat.system.refining"),timestamp:Date.now()}]);const P=new AbortController;_.current=P;try{const V=await ee.refinePreviewStream(S,j,pe=>{if(pe.type==="data:progress"){const Ne=pe.message||pe.stage||t("globalChat.system.processing");i(De=>De.map(ke=>ke.id===N?{...ke,content:`🔄 ${Ne}`}:ke))}},P.signal),ne=V.before||(T?Aa(T):{}),ue=$l(ne,V.after||{},t);i(pe=>pe.map(Ne=>Ne.id===N?{...Ne,content:ue.length>0?t("globalChat.previewGenerated",{count:ue.length}):t("globalChat.noChangeHint"),diff:ue.length>0?ue:void 0,preview:ue.length>0?V.preview??void 0:void 0,excludedFields:[]}:Ne))}catch(V){Cs(V)?i(ne=>ne.map(ue=>ue.id===N?{...ue,content:t("globalChat.system.cancelled")}:ue)):i(ne=>ne.map(ue=>ue.id===N?{...ue,content:t("globalChat.refinePreviewFailed",{error:ve(V)})}:ue))}finally{_.current=null}}else{y.current.push({role:"user",content:j});const N=Gt();i(pe=>[...pe,{id:N,role:"assistant",content:t("globalChat.system.thinking"),timestamp:Date.now()}]);const P=new AbortController;_.current=P;const{onEvent:V,getState:ne}=Sr(N,i,t);let ue="";try{const Ne=(await ee.chatStream(j,y.current,De=>{V(De),ue=ne().answerText},P.signal,s)).text||ue;y.current.push({role:"model",content:Ne}),i(De=>De.map(ke=>ke.id===N?{...ke,content:Ne}:ke))}catch(pe){if(Cs(pe)){const{answerText:Ne,toolLogs:De}=ne(),ke=Ne||(De.length>0?De.join(`
71
+ `)+`
72
+
73
+ `+t("globalChat.system.cancelled"):t("globalChat.system.cancelled"));Ne&&y.current.push({role:"model",content:Ne}),i(Me=>Me.map(M=>M.id===N?{...M,content:ke}:M))}else i(Ne=>Ne.map(De=>De.id===N?{...De,content:t("globalChat.requestFailed",{error:ve(pe)})}:De))}finally{_.current=null}}u(!1)}},[w,o,D,S,T,K]),Q=n.useCallback(async()=>{if(!(p||!S||!x)){c(!0);try{const j=[...r].reverse().find(P=>P.role==="assistant"&&P.preview);let N=j?.preview;if(N&&j?.excludedFields?.length&&j.diff){N={...N};const P=T?Aa(T):{};for(const V of j.excludedFields)V in P&&(N[V]=P[V])}await ee.refineApply(S,l,N),d(P=>new Set(P).add(S)),x.onCandidateUpdated?.(S),i(P=>[...P,{id:Gt(),role:"system",content:t("globalChat.system.changesApplied"),timestamp:Date.now()}]),Z(t("globalChat.applySuccess"),{title:t("globalChat.applySuccessTitle")})}catch(j){Z(ve(j),{title:t("globalChat.applyFailed"),type:"error"})}finally{c(!1)}}},[p,S,l,x]),me=n.useCallback(()=>{!x||x.currentIdx>=x.candidateIds.length-1||h(j=>j?{...j,currentIdx:j.currentIdx+1}:null)},[x]),Se=n.useCallback(()=>{q.current=null,h(null),i(j=>[...j,{id:Gt(),role:"system",content:t("globalChat.system.exitedRefine"),timestamp:Date.now()}])},[]),ye=n.useCallback(j=>{j.key==="Enter"&&!j.shiftKey&&(j.preventDefault(),ae())},[ae]);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:D?e.jsx(He,{className:"text-emerald-500",size:16}):e.jsx(wt,{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(D?"globalChat.refineTitle":"globalChat.chatTitle"),D&&z&&e.jsxs("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-emerald-50 text-emerald-600 font-medium",children:[(x?.currentIdx??0)+1,"/",x?.candidateIds.length]})]}),e.jsx("p",{className:"text-[10px] text-[var(--fg-muted)] truncate max-w-[250px]",children:D?T?.title||t("globalChat.refineSubtitle"):t("globalChat.chatSubtitle")})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[D&&e.jsx("button",{onClick:Se,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")}),!D&&r.length>0&&e.jsx("button",{onClick:()=>{q.current=null,i([]),y.current=[],f("")},className:"p-1.5 hover:bg-[var(--bg-subtle)] rounded-lg transition-colors",title:t("globalChat.newTopic"),children:e.jsx(gt,{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(Ue,{size:16,className:"text-[var(--fg-muted)]"})})]})]}),D&&T&&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:T.title}),T.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:T.language})]})}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-3 min-h-0 scrollbar-light",children:[r.length===0&&!D&&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(wt,{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(j=>e.jsx("button",{onClick:()=>{k(j),le.current?.focus()},className:"text-[10px] px-2.5 py-1 rounded-md bg-[var(--bg-subtle)] text-[var(--fg-secondary)] hover:bg-blue-50 hover:text-blue-700 transition-colors",children:j},j))})]}),D&&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(j=>e.jsx("button",{onClick:()=>{k(j),le.current?.focus()},className:"text-[10px] px-2.5 py-1 rounded-md bg-emerald-50 text-emerald-700 border border-emerald-200 hover:bg-emerald-100 transition-colors",children:j},j))}),r.map(j=>e.jsx("div",{className:`flex ${j.role==="user"?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[95%] ${j.role==="user"?"bg-blue-600 text-white rounded-2xl rounded-tr-md px-3.5 py-2":j.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:[j.role==="assistant"&&e.jsxs("div",{className:"flex items-center gap-1.5 mb-1.5",children:[e.jsx(qt,{size:12,className:D?"text-emerald-500":"text-blue-500"}),e.jsx("span",{className:`text-[10px] font-bold ${D?"text-emerald-600":"text-blue-600"}`,children:t(D?"globalChat.assistantRefine":"globalChat.assistantChat")})]}),j.role==="assistant"&&!j.diff?e.jsx(Ct,{content:j.content,className:"text-xs text-[var(--fg-primary)]"}):e.jsx("p",{className:`text-xs leading-relaxed whitespace-pre-wrap ${j.role==="user"?"":j.role==="system"?"text-[var(--fg-secondary)]":"text-[var(--fg-primary)]"}`,children:j.content}),j.diff&&j.diff.length>0&&e.jsx(Hl,{diff:j.diff,excludedFields:j.excludedFields,onToggleField:D&&!g.has(S)?N=>v(j.id,N):void 0})]})},j.id)),o&&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(Ce,{size:12,className:`animate-spin ${D?"text-emerald-500":"text-blue-500"}`}),e.jsx("span",{className:"text-xs text-[var(--fg-secondary)]",children:t(D?"globalChat.loading.analyzing":"globalChat.loading.thinking")}),_.current&&e.jsx("button",{onClick:()=>_.current?.abort(),className:"ml-1 px-1.5 py-0.5 text-[10px] font-bold text-red-500 border border-red-200 rounded hover:bg-red-50 transition-colors",children:t("globalChat.stopBtn")})]})})}),e.jsx("div",{ref:G})]}),D&&C&&!o&&(()=>{const j=[...r].reverse().find(ne=>ne.role==="assistant"&&ne.diff&&ne.diff.length>0),N=j?.diff?.length||0,P=j?.excludedFields?.length||0,V=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:Q,disabled:p,className:"flex items-center gap-1 px-3 py-1.5 text-[11px] font-bold text-white bg-gradient-to-r from-emerald-500 to-teal-600 hover:from-emerald-600 hover:to-teal-700 rounded-lg shadow-sm disabled:opacity-50",children:[p?e.jsx(Ce,{size:11,className:"animate-spin"}):e.jsx(pt,{size:11}),p?t("globalChat.applyingBtn"):P>0?t("globalChat.confirmApplyN",{i:V,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(cr,{size:11})," ",t("globalChat.continueAdjust")]}),z&&g.has(S)&&x.currentIdx<x.candidateIds.length-1&&e.jsxs("button",{onClick:me,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(Qe,{size:11})]})]})})(),D&&!C&&!o&&z&&g.has(S)&&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:me,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?.currentIdx??0)+2,"/",x?.candidateIds.length,") ",e.jsx(Qe,{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:le,value:w,onChange:j=>k(j.target.value),onKeyDown:ye,placeholder:t(D?"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 ${D?"focus:ring-emerald-200 focus:border-emerald-400":"focus:ring-blue-200 focus:border-blue-400"} resize-none placeholder:text-[var(--fg-muted)]`,disabled:o||p}),e.jsx("button",{onClick:ae,disabled:!w.trim()||o||p,className:`self-stretch w-9 flex items-center justify-center rounded-xl bg-gradient-to-r ${D?"from-emerald-500 to-teal-600 hover:from-emerald-600 hover:to-teal-700":"from-blue-500 to-indigo-600 hover:from-blue-600 hover:to-indigo-700"} text-white disabled:opacity-40 disabled:cursor-not-allowed transition-all shadow-sm shrink-0`,children:e.jsx(Zs,{size:14})})]}),e.jsx("p",{className:"text-[9px] text-[var(--fg-muted)] mt-1",children:t(D?"globalChat.inputHintRefine":"globalChat.inputHintChat")})]})]})},ql=Ka("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"}}),Ge=n.forwardRef(({className:t,variant:s,size:a,loading:r,disabled:i,children:o,style:u,...p},c)=>{const x=s==="accent"?{background:"var(--accent-gradient)",...u}:u;return e.jsxs("button",{ref:c,className:he(ql({variant:s,size:a,className:t})),disabled:i||r,style:x,...p,children:[r&&e.jsxs("svg",{className:"h-4 w-4 animate-spin",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),o]})});Ge.displayName="Button";const Rr=an,Ir=rn,Ul=n.forwardRef(({className:t,inset:s,children:a,...r},i)=>e.jsxs(qa,{ref:i,className:he("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(Qe,{className:"ml-auto h-4 w-4"})]}));Ul.displayName=qa.displayName;const Wl=n.forwardRef(({className:t,...s},a)=>e.jsx(Ua,{ref:a,className:he("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=Ua.displayName;const ca=n.forwardRef(({className:t,sideOffset:s=4,...a},r)=>e.jsx(sn,{children:e.jsx(Wa,{ref:r,sideOffset:s,className:he("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})}));ca.displayName=Wa.displayName;const Mt=n.forwardRef(({className:t,inset:s,...a},r)=>e.jsx(Va,{ref:r,className:he("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}));Mt.displayName=Va.displayName;const Vl=n.forwardRef(({className:t,children:s,checked:a,...r},i)=>e.jsxs(Ja,{ref:i,className:he("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(Ya,{children:e.jsx(pt,{className:"h-4 w-4"})})}),s]}));Vl.displayName=Ja.displayName;const Jl=n.forwardRef(({className:t,children:s,...a},r)=>e.jsxs(Qa,{ref:r,className:he("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(Ya,{children:e.jsx(Nn,{className:"h-2 w-2 fill-current"})})}),s]}));Jl.displayName=Qa.displayName;const Tr=n.forwardRef(({className:t,inset:s,...a},r)=>e.jsx(Xa,{ref:r,className:he("px-2 py-1.5 text-xs font-medium text-[var(--fg-subtle)]",s&&"pl-8",t),...a}));Tr.displayName=Xa.displayName;const Ss=n.forwardRef(({className:t,...s},a)=>e.jsx(Za,{ref:a,className:he("-mx-1 my-1 h-px bg-[var(--border-muted)]",t),...s}));Ss.displayName=Za.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:i,onBeforeAiSwitch:o,onAiConfigChange:u,activeTab:p,onOpenCommandPalette:c,projectName:x,candidateCount:h=0})=>{const{toggle:g,isOpen:d}=ns(),{t:l}=Ae(),[f,y]=n.useState([]),[D,S]=n.useState(!1),[T,z]=n.useState(null),O=n.useCallback(()=>{ee.getTokenUsage7Days().then(k=>z(k.summary)).catch(()=>{})},[]);n.useEffect(()=>{O();const k=la(),I=()=>O();return k.on("candidate-created",I),k.on("bootstrap:all-completed",I),k.on("token-usage-updated",I),()=>{k.off("candidate-created",I),k.off("bootstrap:all-completed",I),k.off("token-usage-updated",I)}},[O]);const G=async k=>{S(!0);try{o?.(),await ee.setAiConfig(k.id,k.defaultModel),u&&u()}catch(I){console.error("AI config update failed",I)}finally{S(!1)}},le=()=>{f.length===0&&ee.getAiProviders().then(y).catch(()=>{})},w=p?l(Xl[p],{count:h}):"";return e.jsx(wr,{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(Qe,{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:he("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(ht,{size:14}),e.jsx("span",{children:l("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(Ge,{variant:"ghost",size:"sm",onClick:i,className:"text-[var(--warning)] animate-pulse",children:[e.jsx(Ns,{size:14}),e.jsx("span",{className:"text-xs",children:l("header.configureLlm")})]}),r&&a&&e.jsxs(Rr,{onOpenChange:k=>k&&le(),children:[e.jsx(Ir,{asChild:!0,children:e.jsxs(Ge,{variant:"ghost",size:"sm",className:"gap-1.5 focus-visible:ring-0 focus-visible:ring-offset-0",children:[e.jsx(as,{size:14,className:"shrink-0"}),e.jsx("span",{className:"text-xs",title:`${a.provider}/${a.model}`,children:Ql(a.model,28)}),T&&T.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(Ke,{size:9,className:"text-amber-500/70"}),Yl(T.total_tokens)]}),e.jsx(Nt,{size:12,className:"shrink-0"})]})}),e.jsxs(ca,{align:"end",className:"w-56",children:[e.jsx(Tr,{children:l("header.switchAi")}),e.jsx(Ss,{}),f.length===0?e.jsx(Mt,{disabled:!0,children:l("common.loading")}):f.map(k=>e.jsxs(Mt,{onClick:()=>G(k),disabled:D,className:he(a.provider===k.id&&"bg-[var(--accent-subtle)] text-[var(--accent)] font-medium",k.hasKey===!1&&"opacity-50"),children:[e.jsxs("span",{className:"flex items-center gap-2 flex-1",children:[e.jsx("span",{className:he("inline-block w-1.5 h-1.5 rounded-full shrink-0",k.hasKey!==!1?"bg-emerald-500":"bg-[var(--fg-subtle)]")}),k.label]}),a.provider===k.id&&e.jsx("span",{className:"text-xs",children:"✓"})]},k.id)),e.jsx(Ss,{}),e.jsxs(Mt,{onClick:i,children:[e.jsx(Ns,{size:14}),e.jsx("span",{children:l("header.editEnvConfig")})]})]})]}),e.jsxs(Pt,{children:[e.jsx(Lt,{asChild:!0,children:e.jsx(Ge,{variant:"ghost",size:"icon-sm",onClick:()=>t(!0),children:e.jsx(gt,{size:16})})}),e.jsx(yt,{children:l("header.newRecipe")})]}),e.jsxs(Pt,{children:[e.jsx(Lt,{asChild:!0,children:e.jsx(Ge,{variant:"ghost",size:"icon-sm",onClick:s,children:e.jsx(mt,{size:16})})}),e.jsx(yt,{children:l("header.syncSnippets")})]}),e.jsxs(Pt,{children:[e.jsx(Lt,{asChild:!0,children:e.jsx(Ge,{variant:d?"accent":"ghost",size:"icon-sm",onClick:g,children:e.jsx(wt,{size:16})})}),e.jsx(yt,{children:l(d?"header.closeAiChat":"header.openAiChat")})]})," "]})]})})},eo=on,to=nn,Er=n.forwardRef(({className:t,...s},a)=>e.jsx(er,{ref:a,className:he("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}));Er.displayName=er.displayName;const Pr=n.forwardRef(({className:t,children:s,size:a="md",hideClose:r=!1,...i},o)=>e.jsxs(to,{children:[e.jsx(Er,{}),e.jsxs(tr,{ref:o,className:he("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),...i,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(Ue,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Pr.displayName=tr.displayName;const so=n.forwardRef(({className:t,...s},a)=>e.jsx(sr,{ref:a,className:he("text-lg font-semibold text-[var(--fg-default)]",t),...s}));so.displayName=sr.displayName;const ao=n.forwardRef(({className:t,...s},a)=>e.jsx(ar,{ref:a,className:he("text-sm text-[var(--fg-muted)]",t),...s}));ao.displayName=ar.displayName;const Lr=n.forwardRef(({className:t,...s},a)=>e.jsx(st,{ref:a,className:he("flex h-full w-full flex-col overflow-hidden rounded-[var(--radius-xl)] text-[var(--fg-default)]",t),...s}));Lr.displayName=st.displayName;const Mr=n.forwardRef(({className:t,...s},a)=>e.jsxs("div",{className:"flex items-center border-b border-[var(--border-muted)] px-3",children:[e.jsx(ht,{className:"mr-2 h-4 w-4 shrink-0 text-[var(--fg-subtle)]"}),e.jsx(st.Input,{ref:a,className:he("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})]}));Mr.displayName=st.Input.displayName;const _r=n.forwardRef(({className:t,...s},a)=>e.jsx(st.List,{ref:a,className:he("max-h-[300px] overflow-y-auto overflow-x-hidden p-1",t),...s}));_r.displayName=st.List.displayName;const Fr=n.forwardRef((t,s)=>e.jsx(st.Empty,{ref:s,className:"py-6 text-center text-sm text-[var(--fg-subtle)]",...t}));Fr.displayName=st.Empty.displayName;const vs=n.forwardRef(({className:t,...s},a)=>e.jsx(st.Group,{ref:a,className:he("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}));vs.displayName=st.Group.displayName;const Js=n.forwardRef(({className:t,...s},a)=>e.jsx(st.Separator,{ref:a,className:he("-mx-1 h-px bg-[var(--border-muted)]",t),...s}));Js.displayName=st.Separator.displayName;const Dt=n.forwardRef(({className:t,...s},a)=>e.jsx(st.Item,{ref:a,className:he("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}));Dt.displayName=st.Item.displayName;function zs({className:t,...s}){return e.jsx("span",{className:he("ml-auto text-xs tracking-widest text-[var(--fg-subtle)]",t),...s})}const ro={recipes:lr,spm:jt,candidates:tt,knowledge:Qs,depgraph:Ds,knowledgegraph:ws,guard:at,skills:qe,wiki:ct,ai:wt,help:or},Bs={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:i,onSemanticSearch:o,searchQuery:u,setSearchQuery:p,onOpenLlmConfig:c,candidateCount:x=0})=>{const{t:h}=Ae(),[g,d]=n.useState([]);n.useEffect(()=>{t&&g.length===0&&ee.fetchData().then(y=>{const D=y?.recipes||[];d(D.slice(0,5).map(S=>({name:S.name||S.title,title:S.title||S.name})))}).catch(()=>{})},[t]),n.useEffect(()=>{const y=D=>{(D.metaKey||D.ctrlKey)&&D.key==="k"&&(D.preventDefault(),s(!t))};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[t,s]);const l=n.useCallback(y=>{y(),s(!1)},[s]),f=Object.keys(Bs);return e.jsx(eo,{open:t,onOpenChange:s,children:e.jsx(Pr,{size:"md",hideClose:!0,className:"!p-0 !top-[15vh] !translate-y-0 overflow-hidden",style:{backgroundColor:"var(--bg-root)"},children:e.jsxs(Lr,{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(Mr,{placeholder:h("commandPalette.searchPlaceholder")||"搜索知识、命令、页面...",value:u,onValueChange:p}),e.jsxs(_r,{className:"max-h-[360px]",children:[e.jsx(Fr,{children:h("commandPalette.noResults")||"没有找到结果"}),g.length>0&&e.jsx(vs,{heading:h("commandPalette.recent")||"最近",children:g.map(y=>e.jsxs(Dt,{value:y.title,onSelect:()=>l(()=>{a("recipes"),p(y.title)}),children:[e.jsx(ct,{className:"mr-2 h-4 w-4 text-[var(--fg-subtle)]"}),e.jsx("span",{children:y.title})]},y.name))}),e.jsx(Js,{}),e.jsx(vs,{heading:h("commandPalette.pages")||"页面",children:f.map(y=>{const D=ro[y],S=y==="candidates"?{count:x}:void 0;return e.jsxs(Dt,{value:h(Bs[y],S),onSelect:()=>l(()=>a(y)),children:[e.jsx(D,{className:"mr-2 h-4 w-4 text-[var(--fg-subtle)]"}),e.jsx("span",{children:h(Bs[y],S)})]},y)})}),e.jsx(Js,{}),e.jsxs(vs,{heading:h("commandPalette.commands")||"命令",children:[e.jsxs(Dt,{value:"new recipe",onSelect:()=>l(()=>r(!0)),children:[e.jsx(gt,{className:"mr-2 h-4 w-4 text-[var(--fg-subtle)]"}),e.jsx("span",{children:h("header.newRecipe")}),e.jsx(zs,{children:"⌘N"})]}),e.jsxs(Dt,{value:"sync snippets",onSelect:()=>l(i),children:[e.jsx(mt,{className:"mr-2 h-4 w-4 text-[var(--fg-subtle)]"}),e.jsx("span",{children:h("header.syncSnippets")}),e.jsx(zs,{children:"⌘S"})]}),o&&e.jsxs(Dt,{value:"semantic search",onSelect:()=>l(()=>o(u)),children:[e.jsx(kn,{className:"mr-2 h-4 w-4 text-[var(--fg-subtle)]"}),e.jsx("span",{children:h("header.semanticSearch")}),e.jsx(zs,{children:"⌘⇧F"})]}),c&&e.jsxs(Dt,{value:"llm config",onSelect:()=>l(()=>c()),children:[e.jsx(Ns,{className:"mr-2 h-4 w-4 text-[var(--fg-subtle)]"}),e.jsx("span",{children:h("header.configureLlm")})]})]})]})]})})})},zr="asd-drawer-wide";function lo(){try{return localStorage.getItem(zr)==="1"}catch{return!1}}function da(){const[t,s]=n.useState(lo),a=n.useCallback(()=>{s(r=>{const i=!r;try{localStorage.setItem(zr,i?"1":"0")}catch{}return i})},[]);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"},Ze=({value:t,onChange:s,options:a,className:r,contentClassName:i,placeholder:o="—",disabled:u=!1,size:p="sm",minWidth:c,direction:x="auto",id:h,name:g})=>{const[d,l]=n.useState(!1),[f,y]=n.useState(-1),[D,S]=n.useState(!1),T=n.useRef(null),z=n.useRef(null),O=a.find(I=>I.value===t),G=n.useCallback(()=>{if(x==="up")return!0;if(x==="down"||!T.current)return!1;const I=T.current.getBoundingClientRect(),q=window.innerHeight-I.bottom,W=Math.min(a.length*28+8,248);return q<W&&I.top>W},[x,a.length]),le=n.useCallback(()=>{S(G()),l(!0),y(a.findIndex(I=>I.value===t))},[G,a,t]);n.useEffect(()=>{if(!d)return;const I=q=>{T.current?.contains(q.target)||z.current?.contains(q.target)||l(!1)};return document.addEventListener("mousedown",I),()=>document.removeEventListener("mousedown",I)},[d]);const w=n.useCallback(I=>{if(u)return;const q=a.filter(W=>!W.disabled);I.key==="Enter"||I.key===" "?(I.preventDefault(),d?f>=0&&f<q.length&&(s(q[f].value),l(!1)):le()):I.key==="Escape"?l(!1):I.key==="ArrowDown"?(I.preventDefault(),d?y(W=>Math.min(W+1,q.length-1)):le()):I.key==="ArrowUp"&&(I.preventDefault(),y(W=>Math.max(W-1,0)))},[u,d,f,a,t,s,le]);n.useEffect(()=>{if(!d||f<0||!z.current)return;z.current.querySelectorAll("[data-select-item]")[f]?.scrollIntoView({block:"nearest"})},[f,d]);const k=I=>{s(I),l(!1),T.current?.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:T,id:h,type:"button",role:"combobox","aria-expanded":d,"aria-haspopup":"listbox",disabled:u,onClick:()=>{u||(d?l(!1):le())},onKeyDown:w,className:he("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[p],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]}):o}),e.jsx(Nt,{size:p==="xs"?10:p==="sm"?12:14,className:he("shrink-0 text-[var(--fg-muted)] transition-transform",d&&"rotate-180")})]}),d&&e.jsx("div",{ref:z,role:"listbox",className:he("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",D?"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",i),children:a.map((I,q)=>{const W=I.value===t,K=q===f;return e.jsxs("div",{"data-select-item":!0,role:"option","aria-selected":W,onClick:()=>!I.disabled&&k(I.value),onMouseEnter:()=>!I.disabled&&y(q),className:he("flex items-center justify-between cursor-pointer rounded-[var(--radius-sm)] transition-colors",io[p],I.disabled&&"opacity-40 pointer-events-none",K&&"bg-[var(--bg-subtle)]",W&&"text-[var(--accent)] font-semibold"),children:[e.jsxs("span",{className:"flex items-center gap-1.5 truncate",children:[I.icon&&e.jsx("span",{children:I.icon}),I.label]}),W&&e.jsx(pt,{size:p==="xs"?10:12,className:"shrink-0 text-[var(--accent)]"})]},I.value)})})]})},ua=({currentPage:t,totalPages:s,totalItems:a,pageSize:r,onPageChange:i,onPageSizeChange:o,pageSizeOptions:u=[12,24,48,96]})=>{if(s<=1&&a<=u[0])return null;const{t:p}=Ae(),c=(t-1)*r+1,x=Math.min(t*r,a),h=()=>{const g=[];if(s<=7)for(let l=1;l<=s;l++)g.push(l);else if(t<=3){for(let l=1;l<=5;l++)g.push(l);g.push("..."),g.push(s)}else if(t>=s-2){g.push(1),g.push("...");for(let l=s-5+1;l<=s;l++)g.push(l)}else{g.push(1),g.push("...");for(let l=t-1;l<=t+1;l++)g.push(l);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:p("pagination.showing",{start:c,end:x,total:a})}),o&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-[var(--fg-secondary)]",children:p("pagination.perPage")}),e.jsx(Ze,{value:String(r),onChange:g=>o(Number(g)),options:u.map(g=>({value:String(g),label:String(g)})),size:"sm"}),e.jsx("span",{className:"text-sm text-[var(--fg-secondary)]",children:p("pagination.unit")})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{onClick:()=>i(1),disabled:t===1,className:"p-1.5 rounded-md hover:bg-[var(--bg-subtle)] disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:p("pagination.firstPage"),children:e.jsx(Cn,{size:H.md,className:"text-[var(--fg-secondary)]"})}),e.jsx("button",{onClick:()=>i(t-1),disabled:t===1,className:"p-1.5 rounded-md hover:bg-[var(--bg-subtle)] disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:p("pagination.prevPage"),children:e.jsx(ea,{size:H.md,className:"text-[var(--fg-secondary)]"})}),e.jsx("div",{className:"flex items-center gap-1 mx-2",children:h().map((g,d)=>typeof g=="number"?e.jsx("button",{onClick:()=>i(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},d):e.jsx("span",{className:"px-1 text-[var(--fg-muted)]",children:g},d))}),e.jsx("button",{onClick:()=>i(t+1),disabled:t===s,className:"p-1.5 rounded-md hover:bg-[var(--bg-subtle)] disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:p("pagination.nextPage"),children:e.jsx(Qe,{size:H.md,className:"text-[var(--fg-secondary)]"})}),e.jsx("button",{onClick:()=>i(s),disabled:t===s,className:"p-1.5 rounded-md hover:bg-[var(--bg-subtle)] disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:p("pagination.lastPage"),children:e.jsx(Sn,{size:H.md,className:"text-[var(--fg-secondary)]"})})]})]})},co=St.memo(({code:t,lang:s,editorStyles:a})=>e.jsx($a,{language:s,style:Ha,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})()})),is=19.5,uo=St.memo(({totalLines:t,scrollTop:s,viewportHeight:a,fontSize:r,lineHeight:i,fontFamily:o})=>{const p=Math.max(0,Math.floor(s/is)-10),c=Math.ceil(a/is)+20,x=Math.min(t,p+c),h=p*is,g=Math.max(0,(t-x)*is),d=[];for(let l=p;l<x;l++)d.push(e.jsx("div",{children:l+1},l));return e.jsx("div",{style:{paddingTop:h,paddingBottom:g,fontSize:r,lineHeight:i,fontFamily:o},children:d})}),As=({value:t,onChange:s,onCursorChange:a,language:r="javascript",height:i="400px",className:o="",placeholder:u="",rows:p,showLineNumbers:c=!0})=>{const x=n.useRef(null),h=n.useRef(null),g=n.useRef(null),d=n.useRef(null),[l,f]=n.useState(t),y=n.useRef(void 0);n.useEffect(()=>{const I=t.length>5e3?200:t.length>1e3?80:0;if(I===0){f(t);return}return y.current=setTimeout(()=>f(t),I),()=>clearTimeout(y.current)},[t]);const[D,S]=n.useState({top:0,height:400}),z={objectivec:"objectivec","objective-c":"objectivec","obj-c":"objectivec",objc:"objectivec",swift:"swift",javascript:"javascript",js:"javascript",typescript:"typescript",ts:"typescript",python:"python",py:"python",bash:"bash",shell:"bash",markdown:"markdown",md:"markdown",json:"json",text:"text"}[r?.toLowerCase()]||r?.toLowerCase()||"text",O=n.useMemo(()=>({padding:"1rem 1.25rem",fontSize:"0.8125rem",lineHeight:1.5,fontFamily:"ui-monospace, monospace",minHeight:"200px"}),[]),G=n.useCallback(I=>{const q=I.currentTarget;g.current&&(g.current.scrollTop=q.scrollTop,g.current.scrollLeft=q.scrollLeft),d.current&&(d.current.scrollTop=q.scrollTop),S({top:q.scrollTop,height:q.clientHeight})},[]),le=n.useCallback(I=>{s(I.target.value),a&&a(I.target.selectionStart||0)},[s,a]),w=n.useCallback(I=>{a&&a(I.currentTarget.selectionStart||0)},[a]),k=n.useMemo(()=>(t||"").split(`
75
+ `).length,[t]);return n.useEffect(()=>{h.current&&S(I=>({...I,height:h.current.clientHeight}))},[]),e.jsxs("div",{ref:x,className:`relative overflow-hidden ${o}`,style:{height:p?"auto":i,minHeight:O.minHeight,display:"flex",borderRadius:"0",backgroundColor:"#282c34"},children:[c&&e.jsx("div",{ref:d,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:k,scrollTop:D.top,viewportHeight:D.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:l||u,lang:z,editorStyles:O})}),e.jsx("textarea",{ref:h,value:t,onChange:le,onSelect:w,onKeyUp:w,onClick:w,onScroll:G,rows:p,placeholder:u,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"}})]})]})},pa=({badges:t,metadata:s,tags:a,maxTags:r,id:i,sourceFile:o,sourceFileLabel:u="源文件"})=>{const p=r&&a?a.slice(0,r):a;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)] space-y-3",children:[t.length>0&&e.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:t.map((c,x)=>{const h=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:[h&&e.jsx(h,{size:10}),c.label]},x)})}),(s.length>0||i||o)&&e.jsxs("div",{className:"flex flex-wrap gap-x-5 gap-y-2 text-xs",children:[s.map((c,x)=>{const h=c.icon;return e.jsxs("div",{className:`flex items-center gap-1.5${c.fullWidth?" basis-full mt-0.5":""}`,children:[e.jsx(h,{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)}),i&&e.jsxs("div",{className:"flex items-center gap-1.5 basis-full mt-0.5",children:[e.jsx(Xs,{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:i})]}),o&&e.jsxs("div",{className:"flex items-center gap-1.5 basis-full",children:[e.jsx(jt,{size:11,className:"text-[var(--fg-muted)] shrink-0"}),e.jsx("span",{className:"text-[var(--fg-muted)]",children:u}),e.jsx("code",{className:"font-mono text-[11px] text-[var(--fg-secondary)] break-all",title:o,children:o})]})]})]}),p&&p.length>0&&e.jsxs("div",{className:"px-6 py-3 border-b border-[var(--border-default)] flex flex-wrap items-center gap-1.5",children:[e.jsx(ur,{size:11,className:"text-[var(--fg-muted)] mr-0.5"}),p.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,i=r.whyStandard&&(!a||!/^Submitted via /i.test(r.whyStandard));return i||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(Ft,{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:[i&&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((u,p)=>e.jsx("code",{className:"text-[10px] px-2 py-0.5 bg-[var(--bg-surface)] border border-amber-200 rounded text-amber-700 font-mono",children:u},p))]}),r.confidence!=null&&r.confidence>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] font-bold",children:s.confidence}),e.jsx("div",{className:"flex-1 max-w-[160px] h-1.5 bg-[var(--border-default)] rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-amber-400 rounded-full",style:{width:`${Math.round((r.confidence??0)*100)}%`}})}),e.jsxs("span",{className:"text-[10px] font-bold text-amber-600",children:[Math.round((r.confidence??0)*100),"%"]})]}),r.alternatives&&r.alternatives.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 pt-1",children:[e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] font-bold",children:s.alternatives}),r.alternatives.map((u,p)=>e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded text-[var(--fg-secondary)]",children:u},p))]})]})]}):null},xo=({quality:t,labels:s,formatFixed:a=!1})=>{if(!t?.grade||t.grade==="F")return null;const r=i=>a?i.toFixed(2):String(i);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(ct,{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(Ct,{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(kt,{size:11,className:"text-emerald-500"})," ",t]}),e.jsx(ft,{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 i=typeof a.title=="string"?a.title:"",o=typeof a.description=="string"?a.description:"",u=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}),i&&e.jsx("span",{className:"text-xs font-bold text-[var(--fg-primary)]",children:i})]}),o&&e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] ml-7 leading-relaxed",children:o}),u&&e.jsx("pre",{className:"text-[11px] font-mono bg-slate-800 text-green-300 p-2.5 rounded-md mt-1.5 ml-7 overflow-x-auto whitespace-pre-wrap",children:u})]},r)})})]}),yo=({label:t,constraints:s})=>{if(!s)return null;const a=s,r=(a.guards?.length||0)+(a.boundaries?.length||0)+(a.preconditions?.length||0)+(a.sideEffects?.length||0);return r?e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(at,{size:11,className:"text-amber-500"})," ",t," ",e.jsx("span",{className:"text-amber-500 font-mono",children:r})]}),e.jsxs("div",{className:"space-y-1.5 text-xs text-[var(--fg-secondary)]",children:[a.guards?.map((i,o)=>e.jsxs("div",{className:"flex gap-1.5 items-start",children:[e.jsx("span",{className:`text-xs mt-0.5 ${i.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:i.pattern}),i.message&&e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)]",children:["— ",i.message]})]},o)),a.boundaries?.map((i,o)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("span",{className:"text-[var(--status-warning)]",children:"●"}),i]},o)),a.preconditions?.map((i,o)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("span",{className:"text-[var(--accent)]",children:"◆"}),i]},o)),a.sideEffects?.map((i,o)=>e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("span",{className:"text-pink-400",children:"⚡"}),i]},o))]})]}):null},jo=({delivery:t,language:s})=>{if(!t)return null;const{topicHint:a,whenClause:r,doClause:i,dontClause:o,coreCode:u}=t;if(!i&&!r&&!o&&!a&&!u)return null;const p=s==="objectivec"||s==="objc"||s==="objective-c"?"objectivec":s||"text";return e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block flex items-center gap-1.5",children:[e.jsx(rt,{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})]}),i&&e.jsxs("div",{children:[e.jsx("span",{className:"text-emerald-400 font-medium",children:"Do:"}),e.jsx("span",{className:"text-[var(--fg-primary)]",children:i})]}),o&&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:o})]}),u&&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(ft,{code:u,language:p})})]})]})]})},Fe={Description:po,Reasoning:mo,Quality:xo,MarkdownSection:go,CodePattern:ho,Headers:fo,Rationale:bo,Steps:vo,Constraints:yo,Delivery:jo},wo=Ka("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"}}),Ys=n.forwardRef(({className:t,variant:s,style:a,...r},i)=>{const o=s==="gradient"?{background:"var(--accent-gradient)",...a}:a;return e.jsx("span",{ref:i,className:he(wo({variant:s,className:t})),style:o,...r})});Ys.displayName="Badge";const No=420,ko=({className:t="bg-black/20 backdrop-blur-[1px]"})=>e.jsx("div",{className:`absolute inset-0 ${t}`}),Ve=({children:t,onClick:s,className:a="",style:r})=>{const{isOpen:i}=ns();return e.jsx("div",{className:`fixed inset-0 overflow-hidden ${a}`,style:{right:i?No:0,...r},onClick:s,children:t})};Ve.Backdrop=ko;const Co=n.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,className:he("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=n.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,className:he("flex items-center justify-between p-5 pb-0",t),...s}));So.displayName="CardHeader";const Ao=n.forwardRef(({className:t,...s},a)=>e.jsx("h3",{ref:a,className:he("text-sm font-semibold text-[var(--fg-default)] leading-tight tracking-tight",t),...s}));Ao.displayName="CardTitle";const Do=n.forwardRef(({className:t,...s},a)=>e.jsx("p",{ref:a,className:he("text-sm text-[var(--fg-muted)] leading-relaxed",t),...s}));Do.displayName="CardDescription";const Ro=n.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,className:he("p-5",t),...s}));Ro.displayName="CardContent";const Io=n.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,className:he("flex items-center px-5 pb-5 pt-0",t),...s}));Io.displayName="CardFooter";const To=n.forwardRef(({className:t,...s},a)=>e.jsx(cn,{ref:a,className:he("border-b border-[var(--border-muted)]",t),...s}));To.displayName="AccordionItem";const Eo=n.forwardRef(({className:t,children:s,...a},r)=>e.jsx(dn,{className:"flex",children:e.jsxs(rr,{ref:r,className:he("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(Nt,{className:"h-4 w-4 shrink-0 text-[var(--fg-subtle)] transition-transform duration-200"})]})}));Eo.displayName=rr.displayName;const Po=n.forwardRef(({className:t,children:s,...a},r)=>e.jsx(nr,{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:he("pb-4 pt-0",t),children:s})}));Po.displayName=nr.displayName;function ot({className:t,...s}){return e.jsx("div",{className:he("rounded-[var(--radius-md)] animate-shimmer",t),...s})}const Br={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:he("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:i,hasNext:o}){const u=i!==void 0?!i:t<=0,p=o!==void 0?!o:t>=s-1;return e.jsxs(e.Fragment,{children:[e.jsx(Ge,{variant:"ghost",size:"icon-sm",onClick:a,disabled:u,children:e.jsx(ea,{size:16})}),e.jsxs("span",{className:"text-xs text-[var(--fg-muted)] tabular-nums",children:[t+1,"/",s]}),e.jsx(Ge,{variant:"ghost",size:"icon-sm",onClick:r,disabled:p,children:e.jsx(Qe,{size:16})})]})}function _o({isWide:t,onToggle:s,title:a}){return e.jsx(Ge,{variant:"ghost",size:"icon-sm",onClick:s,title:a,children:t?e.jsx(An,{size:16}):e.jsx(pr,{size:16})})}function Fo({children:t}){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-px h-5 bg-[var(--border-default)] mx-1"}),t]})}function zo({onClose:t}){return e.jsx(Ge,{variant:"ghost",size:"icon-sm",onClick:t,children:e.jsx(Ue,{size:16})})}function Bo({className:t,padded:s=!1,children:a}){return e.jsx("div",{className:he("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:he("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:i}){return e.jsx("div",{className:he("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||Br[s],r),style:{animation:`slideInRight ${a} ease-out`},onClick:o=>o.stopPropagation(),children:i})}function we({open:t,onClose:s,size:a="md",className:r,animationDuration:i="0.25s",children:o}){return t?e.jsxs(Ve,{className:"z-30 flex justify-end",onClick:s,children:[e.jsx(Ve.Backdrop,{className:"bg-black/20 dark:bg-black/40 backdrop-blur-sm"}),e.jsx("div",{className:he("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)]",Br[a],r),style:{animation:`slideInRight ${i} ease-out`},onClick:u=>u.stopPropagation(),children:o})]}):null}we.Header=Lo;we.Nav=Mo;we.WidthToggle=_o;we.HeaderActions=Fo;we.CloseButton=zo;we.Body=Bo;we.Footer=Go;we.Panel=$o;const Gs={rule:{label:"Rule",color:"text-red-700",bg:"bg-red-50",border:"border-red-200",icon:at},pattern:{label:"Pattern",color:"text-violet-700",bg:"bg-violet-50",border:"border-violet-200",icon:Ft},fact:{label:"Fact",color:"text-cyan-700",bg:"bg-cyan-50",border:"border-cyan-200",icon:qe}},cs={"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 Ye(t){return(t.name||t.title||"Untitled").replace(/\.md$/i,"")}function Ho(t){return t.content?.pattern||""}function Oo(t){const s=(t.language||"").toLowerCase();return["objectivec","objc","objective-c","obj-c"].includes(s)?"objectivec":t.language||"text"}function Gr(t){if(t==null)return!1;const s=typeof t=="string"?new Date(t).getTime():t;return!isNaN(s)&&s>9466848e5}function Da(t){return Gr(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:i,onPageChange:o,pageSize:u,onPageSizeChange:p})=>{const{t:c}=Ae(),[x,h]=n.useState("default"),[g,d]=n.useState("desc"),l=[{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,y]=n.useState(1),[D,S]=n.useState(12),T=i??f,z=u??D,O=o??y,G=p?m=>p(m):m=>{S(m),y(1)},{isWide:le,toggle:w}=da(),[k,I]=n.useState(null),[q,W]=n.useState("view"),[K,C]=n.useState({title:"",description:"",markdown:"",codePattern:"",rationale:"",tags:[],tagInput:""}),[v,_]=n.useState(!1),ae=n.useRef(!0),[Q,me]=n.useState(!1),[Se,ye]=n.useState("related"),[j,N]=n.useState("");n.useEffect(()=>()=>{ae.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:"⊃"}],V=m=>{I(m),W("view"),C({title:m.name?.replace(/\.md$/,"")||"",description:m.description||"",markdown:m.content?.markdown||"",codePattern:m.content?.pattern||"",rationale:m.content?.rationale||"",tags:m.tags||[],tagInput:""}),me(!1),N("")},ne=()=>{I(null),W("view"),me(!1),N("")},ue=async()=>{if(!(!k||v)){_(!0);try{const m=k.id||k.name;await ee.knowledgeUpdate(m,{title:K.title,description:K.description,tags:K.tags,content:{...k.content||{},pattern:K.codePattern,markdown:K.markdown,rationale:K.rationale}}),ae.current&&(W("view"),a?.())}catch(m){Z(ve(m,c("common.saveFailed")),{title:c("common.operationFailed"),type:"error"})}finally{ae.current&&_(!1)}}},pe=async m=>{if(k)try{await ee.setRecipeAuthority(k.id||k.name,m),a?.()}catch(b){Z(ve(b,c("common.operationFailed")),{title:c("common.operationFailed"),type:"error"})}},Ne=m=>{const b=m.replace(/\.md$/i,"").toLowerCase();return t.find(B=>Ye(B).toLowerCase()===b)},De=n.useMemo(()=>{const m=new Map;if(r)for(const[b,B]of Object.entries(r))m.set(b,B);for(const b of t)b.id&&m.set(b.id,Ye(b)),b.name&&m.set(b.name,Ye(b));return m},[t,r]),[ke,Me]=n.useState(!1),M=async(m,b)=>{if(!k||ke)return;const B={};if(k.relations)for(const[te,fe]of Object.entries(k.relations))B[te]=[...fe];const F=B[m]||[],$=b.replace(/\.md$/i,"");if(F.some(te=>(typeof te=="string"?te:te.target||te.id||te.title||"").replace(/\.md$/i,"").toLowerCase()===$.toLowerCase()))return;B[m]=[...F,$];const E=k;I({...k,relations:B}),me(!1),N(""),Me(!0);try{await ee.updateRecipeRelations(k.id||k.name,B)}catch(te){I(E),Z(ve(te,c("common.operationFailed")),{title:c("common.operationFailed"),type:"error"})}finally{Me(!1)}},A=async(m,b)=>{if(!k||ke)return;const B={};if(k.relations)for(const[E,te]of Object.entries(k.relations))B[E]=[...te];const F=B[m]||[];B[m]=F.filter(E=>(typeof E=="string"?E:E.target||E.id||E.title||"").replace(/\.md$/i,"").toLowerCase()!==b.replace(/\.md$/i,"").toLowerCase()),B[m].length===0&&delete B[m];const $=k;I({...k,relations:B}),Me(!0);try{await ee.updateRecipeRelations(k.id||k.name,B)}catch(E){I($),Z(ve(E,c("common.operationFailed")),{title:c("common.operationFailed"),type:"error"})}finally{Me(!1)}};n.useEffect(()=>{k&&!t.find(m=>Ye(m)===Ye(k))&&ne()},[t,k]),n.useEffect(()=>{i==null&&y(1)},[t.length,i]);const L=St.useMemo(()=>{if(x==="default")return t;const m=[...t],b=g==="asc"?1:-1;return m.sort((B,F)=>{let $=0,E=0;switch(x){case"name":return $=Ye(B).toLowerCase(),E=Ye(F).toLowerCase(),b*($<E?-1:$>E?1:0);case"authorityScore":$=B.stats?.authorityScore??-1,E=F.stats?.authorityScore??-1;break;case"authority":$=B.stats?.authority??-1,E=F.stats?.authority??-1;break;case"totalUsage":$=(B.stats?.guardUsageCount??0)+(B.stats?.humanUsageCount??0)+(B.stats?.aiUsageCount??0),E=(F.stats?.guardUsageCount??0)+(F.stats?.humanUsageCount??0)+(F.stats?.aiUsageCount??0);break;case"lastUsed":{const te=B.stats?.lastUsedAt?new Date(B.stats.lastUsedAt).getTime():0,fe=F.stats?.lastUsedAt?new Date(F.stats.lastUsedAt).getTime():0;$=isNaN(te)?0:te,E=isNaN(fe)?0:fe;break}case"category":return $=(B.category||"").toLowerCase(),E=(F.category||"").toLowerCase(),b*($<E?-1:$>E?1:0)}return b*($-E)}),m},[t,x,g]),oe=Math.ceil(L.length/z),be=(T-1)*z,Te=L.slice(be,be+z),ce=m=>{O(m),window.scrollTo({top:0,behavior:"smooth"})},ge=k?L.findIndex(m=>Ye(m)===Ye(k)):-1,Ee=()=>{ge>0&&V(L[ge-1])},J=()=>{ge<L.length-1&&V(L[ge+1])},U=({recipe:m})=>{const b=m.kind?Gs[m.kind]:null,B=m.category||"Utility",F=m.knowledgeType,$=[];return b&&$.push(b.label),$.push(B),F&&cs[F]&&$.push(c(cs[F])),m.language&&$.push(m.language.toUpperCase()),m.trigger&&$.push(m.trigger),e.jsx("span",{className:"text-[11px] text-[var(--fg-muted)] truncate",children:$.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:[l.map(m=>{const b=x===m.key;return e.jsxs("button",{onClick:()=>{b?d(B=>B==="asc"?"desc":"asc"):(h(m.key),d(m.defaultDir)),O(1)},className:he("px-4 py-1.5 rounded-md text-xs font-medium transition-colors flex items-center gap-1",b?"bg-[var(--accent-subtle)] text-[var(--accent)] border border-[var(--accent-emphasis)]":"text-[var(--fg-muted)] hover:bg-[var(--bg-subtle)] border border-transparent"),children:[m.label,b&&x!=="default"&&(g==="asc"?e.jsx(Rn,{size:12}):e.jsx(In,{size:12}))]},m.key)}),e.jsx("span",{className:"ml-auto text-xs text-[var(--fg-muted)]",children:c("recipes.totalCount",{count:t.length})})]}),e.jsx("div",{children:Te.map(m=>{const b=Ye(m),B=m.description||m.usageGuide||"",F=k&&Ye(k)===b,$=m.kind?Gs[m.kind]:null;return e.jsx("div",{onClick:()=>V(m),className:he("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",F&&"bg-[var(--accent-subtle)]"),children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] text-sm break-words leading-snug truncate",children:b}),$&&e.jsx(Ys,{variant:$.label==="Rule"?"red":$.label==="Pattern"?"blue":"default",className:"text-[9px] uppercase shrink-0",children:$.label}),m.stats?.authority!=null&&m.stats.authority>=4&&e.jsxs("span",{className:"text-amber-500 text-[11px] shrink-0",children:["★ ",m.stats.authority]})]}),B&&e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] line-clamp-1 leading-relaxed mb-1.5",children:B.replace(/^#+\s*/gm,"").replace(/\*\*/g,"")}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(U,{recipe:m,compact:!0}),m.tags&&m.tags.length>0&&e.jsxs("span",{className:"text-[11px] text-[var(--fg-muted)]",children:[m.tags.slice(0,3).join(", "),m.tags.length>3&&` +${m.tags.length-3}`]})]})]}),e.jsx("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity shrink-0",children:e.jsxs(Rr,{children:[e.jsx(Ir,{asChild:!0,children:e.jsx(Ge,{variant:"ghost",size:"icon-sm",onClick:E=>E.stopPropagation(),children:e.jsx(Tn,{size:14})})}),e.jsxs(ca,{align:"end",children:[e.jsxs(Mt,{onClick:E=>{E.stopPropagation(),V(m)},children:[e.jsx(ks,{size:14,className:"mr-2"})," ",c("common.preview")]}),e.jsxs(Mt,{onClick:E=>{E.stopPropagation(),V(m),W("edit")},children:[e.jsx(Et,{size:14,className:"mr-2"})," ",c("common.edit")]}),e.jsx(Ss,{}),e.jsxs(Mt,{className:"text-[var(--status-error)]",onClick:E=>{E.stopPropagation(),s(m.name||m.id||"")},children:[e.jsx(et,{size:14,className:"mr-2"})," ",c("recipes.deleteRecipe")]})]})]})})]})},m.id||b)})})]}),t.length>0&&e.jsx(ua,{currentPage:T,totalPages:oe,totalItems:L.length,pageSize:z,onPageChange:ce,onPageSizeChange:G}),k&&(()=>{const m=k,b=Ye(m),B=Ho(m),F=Oo(m),$=m.content;return e.jsxs(we,{open:!!k,onClose:ne,size:le?"lg":"md",children:[e.jsxs(we.Header,{title:b,children:[e.jsx(we.Nav,{currentIndex:ge,total:L.length,onPrev:Ee,onNext:J}),e.jsxs(we.HeaderActions,{children:[e.jsxs("div",{className:"flex bg-[var(--bg-subtle)] p-0.5 rounded-lg mr-1",children:[e.jsxs("button",{onClick:()=>W("view"),className:he("px-2.5 py-1 rounded-md text-xs font-bold transition-all flex items-center gap-1",q==="view"?"bg-[var(--bg-surface)] shadow-sm text-[var(--accent)]":"text-[var(--fg-muted)] hover:text-[var(--fg-secondary)]"),children:[e.jsx(ks,{size:H.sm})," ",c("common.preview")]}),e.jsxs("button",{onClick:()=>{W("edit")},className:he("px-2.5 py-1 rounded-md text-xs font-bold transition-all flex items-center gap-1",q==="edit"?"bg-[var(--bg-surface)] shadow-sm text-[var(--accent)]":"text-[var(--fg-muted)] hover:text-[var(--fg-secondary)]"),children:[e.jsx(Et,{size:H.sm})," ",c("common.edit")]})]}),e.jsx(we.WidthToggle,{isWide:le,onToggle:w}),e.jsx(Ge,{variant:"danger",size:"icon-sm",onClick:()=>{s(m.name||m.id||""),ne()},children:e.jsx(et,{size:16})}),e.jsx(we.CloseButton,{onClose:ne})]})]}),q==="edit"?e.jsxs(e.Fragment,{children:[e.jsxs(we.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:K.title,onChange:E=>C(te=>({...te,title:E.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:K.description,onChange:E=>C(te=>({...te,description:E.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:K.tags.map((E,te)=>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:[E,e.jsx("button",{onClick:()=>C(fe=>({...fe,tags:fe.tags.filter((je,Pe)=>Pe!==te)})),className:"text-[var(--fg-muted)] hover:text-[var(--status-error)]",children:e.jsx(Ue,{size:10})})]},te))}),e.jsx("div",{className:"flex gap-2",children:e.jsx("input",{type:"text",value:K.tagInput,onChange:E=>C(te=>({...te,tagInput:E.target.value})),onKeyDown:E=>{E.key==="Enter"&&K.tagInput.trim()&&(E.preventDefault(),C(te=>({...te,tags:[...te.tags,te.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(ct,{size:11,className:"text-[var(--accent)]"})," ",c("recipes.markdown")]}),e.jsx("textarea",{value:K.markdown,onChange:E=>C(te=>({...te,markdown:E.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(Ht,{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(As,{value:K.codePattern,onChange:E=>C(te=>({...te,codePattern:E})),language:F,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:K.rationale,onChange:E=>C(te=>({...te,rationale:E.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(we.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(Ze,{value:String(m.stats?.authority??3),onChange:E=>pe(parseInt(E)),options:[1,2,3,4,5].map(E=>({value:String(E),label:`${"⭐".repeat(E)} ${E}`})),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(Ge,{variant:"ghost",onClick:()=>W("view"),disabled:v,children:c("common.cancel")}),e.jsxs(Ge,{variant:"primary",onClick:ue,disabled:v,loading:v,children:[!v&&e.jsx(Rs,{size:H.sm}),c(v?"common.saving":"common.save")]})]})]})]}):e.jsxs(we.Body,{children:[e.jsx(pa,{badges:(()=>{const E=m.kind?Gs[m.kind]:null,te=m.category||"Utility",fe=it[te]||it.All,je=[];return E&&je.push({label:E.label,className:`${E.bg} ${E.color} ${E.border}`,icon:E.icon}),je.push({label:te,className:`font-bold uppercase ${fe?.bg||"bg-[var(--bg-subtle)]"} ${fe?.color||"text-[var(--fg-muted)]"} ${fe?.border||"border-[var(--border-default)]"}`}),m.knowledgeType&&je.push({label:cs[m.knowledgeType]?c(cs[m.knowledgeType]):m.knowledgeType,className:"bg-purple-50 text-purple-700 border-purple-200"}),m.language&&je.push({label:m.language,className:"uppercase font-bold text-[var(--fg-secondary)] bg-[var(--bg-subtle)] border-[var(--border-default)]"}),m.trigger&&je.push({label:m.trigger,className:"font-mono font-bold bg-amber-50 text-amber-700 border-amber-200"}),m.source&&m.source!=="unknown"&&je.push({label:m.source,className:"bg-[var(--bg-subtle)] text-[var(--fg-secondary)] border-[var(--border-default)]"}),je})(),metadata:(()=>{const E=[];return m.scope&&E.push({icon:_t,iconClass:"text-teal-400",label:c("candidates.path"),value:m.scope==="universal"?c("common.all"):m.scope==="project-specific"?c("candidates.category"):m.scope}),m.complexity&&E.push({icon:rt,iconClass:"text-orange-400",label:c("candidates.category"),value:m.complexity==="advanced"?c("candidates.confidenceHigh"):m.complexity==="intermediate"?c("candidates.confidenceMedium"):m.complexity==="basic"?c("candidates.confidenceLow"):m.complexity}),m.source&&m.source!=="unknown"&&E.push({icon:_t,iconClass:"text-violet-400",label:c("recipes.sourceLabel"),value:m.source==="bootstrap-scan"?c("recipes.sourceBootstrap"):m.source==="agent"?c("recipes.sourceAiScan"):m.source}),m.updatedAt&&Gr(m.updatedAt)&&E.push({icon:tt,iconClass:"text-[var(--fg-muted)]",label:c("candidates.updatedAt"),value:Da(m.updatedAt)}),E})(),tags:m.tags,id:m.id,sourceFile:m.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(ta,{size:12,className:he("text-purple-400",ke&&"animate-spin")}),e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase",children:c("recipes.relations")}),(()=>{const E=m.relations?Object.values(m.relations).flat().length:0;return E>0?e.jsx(Ys,{variant:"blue",className:"text-[9px]",children:E}):null})()]}),e.jsx(Ge,{variant:Q?"secondary":"primary",size:"sm",onClick:()=>{me(!Q),N("")},children:Q?e.jsxs(e.Fragment,{children:[e.jsx(Ue,{size:10})," ",c("common.cancel")]}):e.jsxs(e.Fragment,{children:[e.jsx(gt,{size:10})," ",c("recipes.editBtn")]})})]}),Q&&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(Ze,{value:Se,onChange:E=>ye(E),options:P.map(E=>({value:E.key,label:`${E.icon} ${E.label}`})),size:"xs",className:"font-bold"}),e.jsxs("div",{className:"flex-1 relative",children:[e.jsx(ht,{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:j,onChange:E=>N(E.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})]})]}),j.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 E=t.filter(te=>Ye(te)===b?!1:Ye(te).toLowerCase().includes(j.toLowerCase())).slice(0,10);return E.length?E.map(te=>{const fe=Ye(te),je=m.relations&&Object.values(m.relations).flat().some(Pe=>(typeof Pe=="string"?Pe:Pe.target||Pe.id||Pe.title||"").replace(/\.md$/i,"").toLowerCase()===fe.toLowerCase());return e.jsxs("div",{className:he("flex items-center justify-between px-3 py-1.5 text-xs",je||ke?"bg-[var(--bg-subtle)] text-[var(--fg-muted)]":"hover:bg-[var(--bg-subtle)] cursor-pointer"),onClick:()=>!je&&!ke&&M(Se,fe),children:[e.jsx("span",{className:"font-medium truncate mr-2",children:fe}),je?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")]})]},fe)}):e.jsx("div",{className:"text-xs text-[var(--fg-muted)] py-3 text-center",children:c("recipes.noResults")})})()})]}),m.relations&&Object.entries(m.relations).some(([,E])=>Array.isArray(E)&&E.length>0)?e.jsx("div",{className:"space-y-1.5",children:P.map(({key:E,label:te,icon:fe})=>{const je=m.relations?.[E];return!je||!Array.isArray(je)||je.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:[fe," ",te]}),e.jsx("div",{className:"flex flex-wrap gap-1",children:je.map((Pe,Le)=>{const de=typeof Pe=="string"?Pe:Pe.target||Pe.id||Pe.title||JSON.stringify(Pe),Oe=Ne(de)||(De.has(de)?Ne(De.get(de)):void 0),Be=Oe?Ye(Oe):De.get(de)||de;return e.jsxs("span",{className:he("group/rel inline-flex items-center gap-1 px-1.5 py-0.5 border rounded text-[10px] font-mono transition-colors",Oe?"bg-[var(--accent-subtle)] border-[var(--accent-emphasis)] text-[var(--accent)] cursor-pointer hover:brightness-95":"bg-[var(--bg-root)] border-[var(--border-default)] text-[var(--fg-secondary)]"),onClick:()=>Oe&&V(Oe),title:Oe?c("candidates.viewDetail"):Be,children:[Be.replace(/\.md$/i,""),e.jsx("button",{onClick:Y=>{Y.stopPropagation(),!ke&&window.confirm(`${c("common.delete")}: ${Be.replace(/\.md$/i,"")}?`)&&A(E,de)},disabled:ke,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(Ue,{size:10})})]},Le)})})]},E)})}):!Q&&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:m.stats?.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:m.stats?.authorityScore!=null?m.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:m.stats?m.stats.guardUsageCount+m.stats.humanUsageCount+m.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:Da(m.stats?.lastUsedAt)||c("recipes.noContent")}),e.jsx("div",{className:"text-[10px] text-[var(--fg-muted)] font-medium",children:c("recipes.qualityGood")})]})]}),m.stats!=null&&(m.stats.guardUsageCount>0||m.stats.humanUsageCount>0||m.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: ",m.stats.guardUsageCount]}),e.jsxs("span",{children:["Human: ",m.stats.humanUsageCount]}),e.jsxs("span",{children:["AI: ",m.stats.aiUsageCount]})]})]}),e.jsx(Fe.Reasoning,{reasoning:m.reasoning,labels:{section:c("recipes.reasoning"),source:c("recipes.sourceColon"),confidence:c("recipes.confidenceColon"),alternatives:c("recipes.alternativesLabel")}}),e.jsx(Fe.Quality,{quality:m.quality,labels:{section:c("recipes.qualityGrade"),completeness:c("recipes.qualityCompleteness"),adaptation:c("recipes.qualityAdaptation"),documentation:c("recipes.qualityDocumentation")}}),e.jsx(Fe.Description,{label:c("recipes.description"),text:m.description}),e.jsx(Fe.MarkdownSection,{label:c("recipes.markdown"),content:$?.markdown}),e.jsx(Fe.Headers,{label:c("recipes.headers"),headers:m.headers}),e.jsx(Fe.CodePattern,{label:c("recipes.code"),code:B,language:F}),e.jsx(Fe.Rationale,{label:c("recipes.designRationale"),text:$?.rationale}),e.jsx(Fe.Steps,{label:c("recipes.steps"),steps:$?.steps}),$?.codeChanges&&$.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:$.codeChanges.map((E,te)=>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(kt,{size:11,className:"text-[var(--accent)]"}),e.jsx("code",{className:"text-[10px] font-mono text-[var(--fg-secondary)]",children:E.file})]}),E.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:E.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:E.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:E.after})]})]},te))})]}),$?.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:[$.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")})," ",$.verification.method]}),$.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")})," ",$.verification.expectedResult]}),$.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:$.verification.testCode})]})]}),e.jsx(Fe.Constraints,{label:c("recipes.constraints"),constraints:m.constraints})]})]})})()]})};function At(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 i=new Date;i.setDate(i.getDate()-r);const o=i.toISOString().slice(0,10);a.push(s.get(o)||{date:o,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}=Ae(),[s,a]=n.useState([]),[r,i]=n.useState([]),[o,u]=n.useState({input_tokens:0,output_tokens:0,total_tokens:0,call_count:0,avg_per_call:0}),[p,c]=n.useState(!0),[x,h]=n.useState(null);n.useEffect(()=>{let f=!1;return(async()=>{try{const y=await ee.getTokenUsage7Days();if(f)return;a(y.daily||[]),i(y.bySource||[]),u(y.summary||{input_tokens:0,output_tokens:0,total_tokens:0,call_count:0,avg_per_call:0})}catch(y){f||h(ve(y,t("tokenUsageChart.loadFailed")))}finally{f||c(!1)}})(),()=>{f=!0}},[]);const g=n.useMemo(()=>qo(s),[s]),d=n.useMemo(()=>Math.max(...g.map(f=>f.total_tokens),1),[g]);if(p)return e.jsxs("div",{className:"flex items-center justify-center py-10",children:[e.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-2 border-blue-500 border-t-transparent"}),e.jsx("span",{className:"ml-2 text-slate-500 text-sm",children:t("tokenUsageChart.loading")})]});if(x)return e.jsx("p",{className:"text-red-500 text-sm py-4 text-center",children:x});const l=o.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(ds,{label:t("tokenUsageChart.totalToken"),value:At(o.total_tokens),sub:t("tokenUsageChart.totalSub"),color:"blue"}),e.jsx(ds,{label:t("tokenUsageChart.input"),value:At(o.input_tokens),sub:"Prompt",color:"green"}),e.jsx(ds,{label:t("tokenUsageChart.output"),value:At(o.output_tokens),sub:"Completion",color:"purple"}),e.jsx(ds,{label:t("tokenUsageChart.calls"),value:String(o.call_count),sub:t("tokenUsageChart.avgPerCall",{avg:At(o.avg_per_call)}),color:"amber"})]}),l?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 y=f.input_tokens/d*100,D=f.output_tokens/d*100,S=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:At(f.input_tokens),output:At(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:`${y}%`,minHeight:f.input_tokens>0?"2px":"0"}}),e.jsx("div",{className:"bg-purple-400 rounded-b-sm w-full transition-all",style:{height:`${D}%`,minHeight:f.output_tokens>0?"2px":"0"}})]}),e.jsx("span",{className:"text-[10px] text-slate-400",children:S})]},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 y=o.total_tokens>0?f.total_tokens/o.total_tokens*100:0,D=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:`${D} h-full rounded-full transition-all`,style:{width:`${y}%`,minWidth:y>0?"4px":"0"}})}),e.jsx("span",{className:"w-16 text-xs text-slate-500 text-right",children:At(f.total_tokens)}),e.jsxs("span",{className:"w-12 text-xs text-slate-400 text-right",children:[y.toFixed(0),"%"]})]},f.source)})})]})]})]})};function ds({label:t,value:s,sub:a,color:r}){const i={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"},o=i[r]||i.blue;return e.jsxs("div",{className:`rounded-lg border p-3 ${o}`,children:[e.jsx("p",{className:"text-xs opacity-70",children:t}),e.jsx("p",{className:"text-xl font-bold",children:s}),e.jsx("p",{className:"text-[10px] opacity-60",children:a})]})}const vt=({id:t,title:s,icon:a,isExpanded:r,onToggle:i,children:o})=>e.jsxs("section",{className:"border border-[var(--border-default)] rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>i(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(Nt,{size:H.lg}):e.jsx(Qe,{size:H.lg})]}),r&&e.jsx("div",{className:"p-4 bg-[var(--bg-surface)]",children:o})]}),Vo=()=>{const{t}=Ae(),[s,a]=n.useState(new Set(["quick-start"])),r=i=>{const o=new Set(s);o.has(i)?o.delete(i):o.add(i),a(o)};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:H.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(vt,{id:"token-usage",title:t("help.tokenUsageLast7Days"),icon:e.jsx(mr,{size:H.xl,className:"text-blue-600"}),isExpanded:s.has("token-usage"),onToggle:r,children:e.jsx(Wo,{})}),e.jsx(vt,{id:"quick-start",title:t("help.quickStart"),icon:e.jsx(Zt,{size:H.xl,className:"text-blue-600"}),isExpanded:s.has("quick-start"),onToggle:r,children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"bg-blue-50 rounded-lg p-4 border border-blue-200",children:[e.jsx("div",{className:"bg-blue-600 text-white rounded-full w-8 h-8 flex items-center justify-center mb-3 font-bold",children:"1"}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:t("help.step1Title")}),e.jsx("pre",{className:"bg-blue-100/70 text-blue-900 px-3 py-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-all",children:e.jsxs("code",{children:["npm install -g autosnippet",`
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("pre",{className:"bg-amber-100/70 text-amber-900 px-3 py-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-all mb-2",children:e.jsx("code",{children:"asd coldstart"})}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.step4Desc1")}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.step4Desc2")})]})]})}),e.jsxs(vt,{id:"concepts",title:t("help.coreConcepts"),icon:e.jsx(Os,{size:H.xl,className:"text-blue-600"}),isExpanded:s.has("concepts"),onToggle:r,children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h3",{className:"text-lg font-semibold text-[var(--fg-primary)] mb-3",children:t("help.threeRoles")}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full border border-[var(--border-default)] rounded-lg text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-[var(--bg-subtle)]",children:[e.jsx("th",{className:"px-4 py-3 border-b text-left font-semibold",children:t("help.roleColumn")}),e.jsx("th",{className:"px-4 py-3 border-b text-left font-semibold",children:t("help.responsibilityColumn")}),e.jsx("th",{className:"px-4 py-3 border-b text-left font-semibold",children:t("help.capabilityColumn")})]})}),e.jsxs("tbody",{children:[e.jsxs("tr",{className:"hover:bg-[var(--bg-subtle)]",children:[e.jsx("td",{className:"px-4 py-3 border-b font-medium text-blue-700",children:t("help.roleDeveloper")}),e.jsx("td",{className:"px-4 py-3 border-b",children:t("help.developerResp")}),e.jsx("td",{className:"px-4 py-3 border-b text-xs",dangerouslySetInnerHTML:{__html:t("help.developerCap")}})]}),e.jsxs("tr",{className:"hover:bg-[var(--bg-subtle)]",children:[e.jsx("td",{className:"px-4 py-3 border-b font-medium text-green-700",children:t("help.roleCursorAgent")}),e.jsx("td",{className:"px-4 py-3 border-b",children:t("help.cursorAgentResp")}),e.jsx("td",{className:"px-4 py-3 border-b text-xs",dangerouslySetInnerHTML:{__html:t("help.cursorAgentCap")}})]}),e.jsxs("tr",{className:"hover:bg-[var(--bg-subtle)]",children:[e.jsx("td",{className:"px-4 py-3 font-medium text-purple-700",children:t("help.roleChatAgent")}),e.jsx("td",{className:"px-4 py-3",children:t("help.chatAgentResp")}),e.jsx("td",{className:"px-4 py-3 text-xs",dangerouslySetInnerHTML:{__html:t("help.chatAgentCap")}})]})]})]})})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-[var(--fg-primary)] mb-3",children:t("help.coreComponents")}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 [&_li]:break-words",children:[e.jsxs("div",{className:"bg-green-50 rounded-lg p-4 border border-green-200",children:[e.jsxs("h4",{className:"font-semibold text-green-900 mb-2 flex items-center gap-2",children:[e.jsx(Ke,{size:H.lg}),t("help.bootstrapLabel")]}),e.jsx("p",{className:"text-green-800 text-sm mb-3",children:t("help.bootstrapDesc")}),e.jsxs("ul",{className:"text-green-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.bootstrapBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.bootstrapBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.bootstrapBullet3")}})]})]}),e.jsxs("div",{className:"bg-purple-50 rounded-lg p-4 border border-purple-200",children:[e.jsxs("h4",{className:"font-semibold text-purple-900 mb-2 flex items-center gap-2",children:[e.jsx(En,{size:H.lg}),t("help.candidatesLabel")]}),e.jsx("p",{className:"text-purple-800 text-sm mb-3",children:t("help.candidatesDesc")}),e.jsxs("ul",{className:"text-purple-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.candidatesBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.candidatesBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.candidatesBullet3")}})]})]}),e.jsxs("div",{className:"bg-blue-50 rounded-lg p-4 border border-blue-200",children:[e.jsxs("h4",{className:"font-semibold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(kt,{size:H.lg}),t("help.recipeLabel")]}),e.jsx("p",{className:"text-blue-800 text-sm mb-3",children:t("help.recipeDesc")}),e.jsxs("ul",{className:"text-blue-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.recipeBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.recipeBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.recipeBullet3")}})]})]}),e.jsxs("div",{className:"bg-indigo-50 rounded-lg p-4 border border-indigo-200",children:[e.jsxs("h4",{className:"font-semibold text-indigo-900 mb-2 flex items-center gap-2",children:[e.jsx(ma,{size:H.lg}),t("help.chatAgentLabel")]}),e.jsx("p",{className:"text-indigo-800 text-sm mb-3",children:t("help.chatAgentDesc")}),e.jsxs("ul",{className:"text-indigo-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.chatAgentCompBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.chatAgentCompBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.chatAgentCompBullet3")}})]})]}),e.jsxs("div",{className:"bg-amber-50 rounded-lg p-4 border border-amber-200",children:[e.jsxs("h4",{className:"font-semibold text-amber-900 mb-2 flex items-center gap-2",children:[e.jsx(ht,{size:H.lg}),t("help.searchPipelineLabel")]}),e.jsx("p",{className:"text-amber-800 text-sm mb-3",children:t("help.searchPipelineDesc")}),e.jsxs("ul",{className:"text-amber-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.searchPipelineBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.searchPipelineBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.searchPipelineBullet3")}})]})]}),e.jsxs("div",{className:"bg-cyan-50 rounded-lg p-4 border border-cyan-200",children:[e.jsxs("h4",{className:"font-semibold text-cyan-900 mb-2 flex items-center gap-2",children:[e.jsx(xa,{size:H.lg}),t("help.taskGraphLabel")]}),e.jsx("p",{className:"text-cyan-800 text-sm mb-3",children:t("help.taskGraphDesc")}),e.jsxs("ul",{className:"text-cyan-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.taskGraphBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.taskGraphBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.taskGraphBullet3")}})]})]}),e.jsxs("div",{className:"bg-rose-50 rounded-lg p-4 border border-rose-200",children:[e.jsxs("h4",{className:"font-semibold text-rose-900 mb-2 flex items-center gap-2",children:[e.jsx(at,{size:H.lg}),t("help.guardLabel")]}),e.jsx("p",{className:"text-rose-800 text-sm mb-3",children:t("help.guardDesc")}),e.jsxs("ul",{className:"text-rose-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.guardCompBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.guardCompBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.guardCompBullet3")}})]})]}),e.jsxs("div",{className:"bg-teal-50 rounded-lg p-4 border border-teal-200",children:[e.jsxs("h4",{className:"font-semibold text-teal-900 mb-2 flex items-center gap-2",children:[e.jsx(ga,{size:H.lg}),t("help.ideIntegrationLabel")]}),e.jsx("p",{className:"text-teal-800 text-sm mb-3",children:t("help.ideIntegrationDesc")}),e.jsxs("ul",{className:"text-teal-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.ideIntegrationBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.ideIntegrationBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.ideIntegrationBullet3")}})]})]}),e.jsxs("div",{className:"bg-orange-50 rounded-lg p-4 border border-orange-200",children:[e.jsxs("h4",{className:"font-semibold text-orange-900 mb-2 flex items-center gap-2",children:[e.jsx(Pn,{size:H.lg}),t("help.securityLabel")]}),e.jsx("p",{className:"text-orange-800 text-sm mb-3",children:t("help.securityDesc")}),e.jsxs("ul",{className:"text-orange-700 text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.securityBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.securityBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.securityBullet3")}})]})]})]})]}),e.jsxs("div",{className:"mt-6 mb-6 p-4 bg-[var(--bg-subtle)] rounded-lg border border-[var(--border-default)]",children:[e.jsx("h3",{className:"text-lg font-semibold text-[var(--fg-primary)] mb-3",children:t("help.archOverviewLabel")}),e.jsxs("div",{className:"flex items-center justify-between gap-1 text-xs overflow-x-auto pb-2",children:[e.jsx("div",{className:"bg-indigo-100 text-indigo-700 px-3 py-2 rounded-lg font-medium text-center shrink-0",children:t("help.archOverviewBootstrap")}),e.jsx("span",{className:"text-[var(--fg-muted)] shrink-0",children:"→"}),e.jsx("div",{className:"bg-blue-100 text-blue-700 px-3 py-2 rounded-lg font-medium text-center shrink-0",children:t("help.archOverviewKB")}),e.jsx("span",{className:"text-[var(--fg-muted)] shrink-0",children:"→"}),e.jsx("div",{className:"bg-blue-100 text-blue-700 px-3 py-2 rounded-lg font-medium text-center shrink-0",children:t("help.archOverviewPipeline")}),e.jsx("span",{className:"text-[var(--fg-muted)] shrink-0",children:"→"}),e.jsx("div",{className:"bg-emerald-100 text-emerald-700 px-3 py-2 rounded-lg font-medium text-center shrink-0",children:t("help.archOverviewAgent")}),e.jsx("span",{className:"text-[var(--fg-muted)] shrink-0",children:"→"}),e.jsx("div",{className:"bg-amber-100 text-amber-700 px-3 py-2 rounded-lg font-medium text-center shrink-0",children:t("help.archOverviewTask")}),e.jsx("span",{className:"text-[var(--fg-muted)] shrink-0",children:"→"}),e.jsx("div",{className:"bg-emerald-100 text-emerald-700 px-3 py-2 rounded-lg font-medium text-center shrink-0",children:t("help.archOverviewOutput")})]}),e.jsxs("div",{className:"mt-2 flex items-center justify-center gap-3 text-xs",children:[e.jsxs("span",{className:"bg-rose-100 text-rose-700 px-3 py-1.5 rounded-lg font-medium",children:["↕ ",t("help.archOverviewSecurity")," ↕"]}),e.jsxs("span",{className:"bg-teal-100 text-teal-700 px-3 py-1.5 rounded-lg font-medium",children:["↕ ",t("help.archOverviewIDE")," ↕"]})]})]}),e.jsxs("div",{className:"mt-6 rounded-lg p-5 border border-[var(--border-default)] bg-[var(--bg-subtle)]",children:[e.jsx("h3",{className:"text-lg font-semibold text-[var(--fg-primary)] mb-5",children:t("help.knowledgeLoop")}),e.jsx("div",{className:"flex items-start justify-between gap-0 overflow-x-auto pb-2",children:[{step:1,color:"blue",key:"loopStep1",subKey:"loopStep1Sub"},{step:2,color:"green",key:"loopStep2",subKey:"loopStep2Sub"},{step:3,color:"purple",key:"loopStep3",subKey:"loopStep3Sub"},{step:4,color:"amber",key:"loopStep4",subKey:"loopStep4Sub"},{step:5,color:"rose",key:"loopStep5",subKey:"loopStep5Sub"}].map((i,o)=>e.jsxs(St.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-${i.color}-500`,children:i.step}),e.jsx("p",{className:"text-[var(--fg-primary)] font-semibold text-sm leading-tight",children:t(`help.${i.key}`)}),e.jsx("p",{className:"text-[var(--fg-muted)] text-xs mt-1 font-mono",children:t(`help.${i.subKey}`)})]}),o<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)]"})]})]},i.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(vt,{id:"agent-arch",title:t("help.agentArchTitle"),icon:e.jsx(qt,{size:H.xl,className:"text-blue-600"}),isExpanded:s.has("agent-arch"),onToggle:r,children:[e.jsx("p",{className:"text-[var(--fg-secondary)] text-sm mb-5",children:t("help.agentArchDesc")}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5",children:[e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-indigo-100 flex items-center justify-center shrink-0",children:e.jsx(rt,{size:H.lg,className:"text-indigo-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.agentArchPresetTitle")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.agentArchPresetDesc")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchPresetChat")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchPresetInsight")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchPresetLark")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchPresetRemoteExec")}})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-emerald-100 flex items-center justify-center shrink-0",children:e.jsx(Ds,{size:H.lg,className:"text-emerald-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.agentArchStrategyTitle")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.agentArchStrategyDesc")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchStrategySingle")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchStrategyPipeline")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchStrategyFanOut")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchStrategyAdaptive")}})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-blue-100 flex items-center justify-center shrink-0",children:e.jsx(Ke,{size:H.lg,className:"text-blue-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.agentArchCapTitle")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.agentArchCapDesc")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchCapConversation")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchCapCodeAnalysis")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchCapKnowledgeProd")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchCapScanProd")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchCapSystem")}})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-purple-100 flex items-center justify-center shrink-0",children:e.jsx(Os,{size:H.lg,className:"text-purple-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.agentArchMemoryTitle")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.agentArchMemoryDesc")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchMemoryWorking")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchMemorySession")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchMemoryPersistent")}})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-amber-100 flex items-center justify-center shrink-0",children:e.jsx(ma,{size:H.lg,className:"text-amber-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.agentArchContextTitle")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.agentArchContextDesc")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchContextWindow")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchContextTracker")}})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-rose-100 flex items-center justify-center shrink-0",children:e.jsx(Ps,{size:H.lg,className:"text-rose-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.agentArchToolsTitle")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.agentArchToolsDesc")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchToolsInternal")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.agentArchToolsMcp")}})]}),e.jsxs("div",{className:"mt-3 pt-3 border-t border-[var(--border-default)]",children:[e.jsx("p",{className:"text-xs font-semibold text-[var(--fg-primary)] mb-1",children:t("help.agentArchRouterTitle")}),e.jsx("p",{className:"text-xs text-[var(--fg-secondary)]",children:t("help.agentArchRouterDesc")})]})]})]})]}),e.jsxs(vt,{id:"features",title:t("help.coreFeatures"),icon:e.jsx(Ke,{size:H.xl,className:"text-blue-600"}),isExpanded:s.has("features"),onToggle:r,children:[e.jsx("p",{className:"text-[var(--fg-secondary)] text-sm mb-5",children:t("help.coreFeaturesDesc")}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5",children:[e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-blue-100 flex items-center justify-center shrink-0",children:e.jsx(xr,{size:H.lg,className:"text-blue-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.knowledgeBuild")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.kbBuildDesc")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.kbBuildBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.kbBuildBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.kbBuildBullet3")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.kbBuildBullet4")}})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-emerald-100 flex items-center justify-center shrink-0",children:e.jsx(ht,{size:H.lg,className:"text-emerald-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.semanticSearchLabel")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.semSearchDescShort")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.semSearchBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.semSearchBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.semSearchBullet3")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.semSearchBullet4")}})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-purple-100 flex items-center justify-center shrink-0",children:e.jsx(at,{size:H.lg,className:"text-purple-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.guardCompliance")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.guardComplianceDesc")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditFeatureBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditFeatureBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditFeatureBullet3")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditFeatureBullet4")}})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-amber-100 flex items-center justify-center shrink-0",children:e.jsx(xa,{size:H.lg,className:"text-amber-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.featureTaskGraphTitle")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.featureTaskGraphDesc")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.featureTaskGraphBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.featureTaskGraphBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.featureTaskGraphBullet3")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.featureTaskGraphBullet4")}})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-rose-100 flex items-center justify-center shrink-0",children:e.jsx(kt,{size:H.lg,className:"text-rose-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.wikiDocGen")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.wikiDocGenDesc")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.wikiDocBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.wikiDocBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.wikiDocBullet3")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.wikiDocBullet4")}})]})]}),e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg p-5 hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-teal-100 flex items-center justify-center shrink-0",children:e.jsx(mt,{size:H.lg,className:"text-teal-600"})}),e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)]",children:t("help.dataSync")})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs mb-3",children:t("help.syncDescShort")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-sm space-y-2 list-disc list-inside",children:[e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.syncBullet1")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.syncBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.syncBullet3")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.syncBullet4")}})]})]})]})]}),e.jsxs(vt,{id:"editor-directives",title:t("help.editorDirectives"),icon:e.jsx(Ps,{size:H.xl,className:"text-blue-600"}),isExpanded:s.has("editor-directives"),onToggle:r,children:[e.jsx("p",{className:"text-[var(--fg-secondary)] text-sm mb-4",children:t("help.editorDirectivesNote")}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-lg p-4 border border-[var(--border-default)]",children:[e.jsxs("h4",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:[e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"// as:create"})," · ",e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"asc"})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-sm mb-2",children:t("help.createDirective")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.createDirBullet1")}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.createDirBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.createDirBullet3")}})]})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-lg p-4 border border-[var(--border-default)]",children:[e.jsxs("h4",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:[e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"// as:search"})," · ",e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"ass"})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-sm mb-2",children:t("help.searchDirective")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.searchDirBullet1")}),e.jsx("li",{children:t("help.searchDirBullet2")}),e.jsx("li",{children:t("help.searchDirBullet3")})]})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-lg p-4 border border-[var(--border-default)]",children:[e.jsxs("h4",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:[e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"// as:audit"})," · ",e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"asa"})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-sm mb-2",children:t("help.auditDirective")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.auditDirBullet1")}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditDirBullet2")}}),e.jsx("li",{dangerouslySetInnerHTML:{__html:t("help.auditDirBullet3")}})]})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-lg p-4 border border-[var(--border-default)]",children:[e.jsxs("h4",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:[e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"// as:include"})," · ",e.jsx("code",{className:"bg-slate-200 px-2 py-1 rounded",children:"// as:import"})]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-sm mb-2",children:t("help.includeDirective")}),e.jsxs("ul",{className:"text-[var(--fg-secondary)] text-xs space-y-1 list-disc list-inside",children:[e.jsx("li",{children:t("help.includeDirBullet1")}),e.jsx("li",{children:t("help.includeDirBullet2")})]})]})]})]}),e.jsxs(vt,{id:"cursor-integration",title:t("help.cursorIntegration"),icon:e.jsx(wt,{size:H.xl,className:"text-blue-600"}),isExpanded:s.has("cursor-integration"),onToggle:r,children:[e.jsxs("div",{className:"mb-5",children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-3",children:t("help.skills10")}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-2",children:[{name:"intent",descKey:"help.skillIntent"},{name:"concepts",descKey:"help.skillConcepts"},{name:"candidates",descKey:"help.skillCandidates"},{name:"recipes",descKey:"help.skillRecipes"},{name:"guard",descKey:"help.skillGuard"},{name:"structure",descKey:"help.skillStructure"},{name:"analysis",descKey:"help.skillAnalysis"},{name:"coldstart",descKey:"help.skillColdstart"},{name:"create",descKey:"help.skillCreate"},{name:"lifecycle",descKey:"help.skillLifecycle"},{name:"devdocs",descKey:"help.skillDevdocs"}].map(i=>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:i.name}),e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] mt-0.5",children:t(i.descKey)})]},i.name))})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-3",children:t("help.mcp16")}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full border border-[var(--border-default)] rounded-lg text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-[var(--bg-subtle)]",children:[e.jsx("th",{className:"px-3 py-2 border-b text-left",children:t("help.mcpLayerHeader")}),e.jsx("th",{className:"px-3 py-2 border-b text-left",children:t("help.mcpToolHeader")}),e.jsx("th",{className:"px-3 py-2 border-b text-left",children:t("help.mcpDescHeader")})]})}),e.jsxs("tbody",{children:[e.jsx("tr",{className:"bg-blue-50/30",children:e.jsx("td",{colSpan:3,className:"px-3 py-1.5 border-b font-semibold text-blue-700 text-xs",children:t("help.mcpAgentLayerHeader")})}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"health"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpHealthDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"capabilities"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpCapabilitiesDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"search"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpSearchDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"knowledge"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpKnowledgeDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"structure"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpStructureDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"graph"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpGraphDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"call_context"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpCallContextDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"guard"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpGuardDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsxs("td",{className:"px-3 py-2 border-b",children:[e.jsx("code",{children:"submit_knowledge"})," / ",e.jsx("code",{children:"submit_knowledge_batch"})," / ",e.jsx("code",{children:"save_document"})]}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpSubmitDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"skill"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpSkillDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"bootstrap"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpBootstrapDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"dimension_complete"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpDimensionCompleteDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsxs("td",{className:"px-3 py-2 border-b",children:[e.jsx("code",{children:"wiki_plan"})," / ",e.jsx("code",{children:"wiki_finalize"})]}),e.jsxs("td",{className:"px-3 py-2 border-b",children:[t("help.mcpWikiPlanDesc")," · ",t("help.mcpWikiFinalizeDesc")]})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"agent"}),e.jsx("td",{className:"px-3 py-2 border-b",children:e.jsx("code",{children:"task"})}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpTaskDesc")})]}),e.jsx("tr",{className:"bg-amber-50/30",children:e.jsx("td",{colSpan:3,className:"px-3 py-1.5 border-b font-semibold text-amber-700 text-xs",children:t("help.mcpAdminLayerHeader")})}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 border-b font-medium",children:"admin"}),e.jsxs("td",{className:"px-3 py-2 border-b",children:[e.jsx("code",{children:"enrich_candidates"})," / ",e.jsx("code",{children:"validate_candidate"})," / ",e.jsx("code",{children:"check_duplicate"})]}),e.jsx("td",{className:"px-3 py-2 border-b",children:t("help.mcpEnrichDesc")})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-3 py-2 font-medium",children:"admin"}),e.jsx("td",{className:"px-3 py-2",children:e.jsx("code",{children:"knowledge_lifecycle"})}),e.jsx("td",{className:"px-3 py-2",children:t("help.mcpLifecycleDesc")})]})]})]})}),e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] mt-2",children:t("help.mcpWriteNote")})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-3",children:t("help.usageExamples")}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"bg-blue-50 rounded p-3 border border-blue-200",children:[e.jsx("p",{className:"font-medium text-blue-900 text-sm mb-1",children:t("help.exampleSearchKB")}),e.jsx("p",{className:"text-blue-800 text-xs",children:t("help.exampleSearchKBDesc")})]}),e.jsxs("div",{className:"bg-green-50 rounded p-3 border border-green-200",children:[e.jsx("p",{className:"font-medium text-green-900 text-sm mb-1",children:t("help.exampleBatchScan")}),e.jsx("p",{className:"text-green-800 text-xs",children:t("help.exampleBatchScanDesc")})]}),e.jsxs("div",{className:"bg-purple-50 rounded p-3 border border-purple-200",children:[e.jsx("p",{className:"font-medium text-purple-900 text-sm mb-1",children:t("help.exampleSubmitCode")}),e.jsx("p",{className:"text-purple-800 text-xs",children:t("help.exampleSubmitCodeDesc")})]})]})]}),e.jsxs("div",{className:"mt-5",children:[e.jsxs("h3",{className:"font-semibold text-[var(--fg-primary)] mb-3 flex items-center gap-2",children:[e.jsx(ga,{size:H.lg,className:"text-blue-600"}),t("help.vscodeExtension")]}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-sm mb-3",children:t("help.vscodeExtDesc")}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3 mb-3",children:[e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-lg p-3",children:[e.jsx("h4",{className:"font-semibold text-[var(--fg-primary)] text-sm mb-1",children:t("help.vscodeExtTaskTool")}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.vscodeExtTaskToolDesc")})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-lg p-3",children:[e.jsx("h4",{className:"font-semibold text-[var(--fg-primary)] text-sm mb-1",children:t("help.vscodeExtGuardDiag")}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.vscodeExtGuardDiagDesc")})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-lg p-3",children:[e.jsx("h4",{className:"font-semibold text-[var(--fg-primary)] text-sm mb-1",children:t("help.vscodeExtCodeLens")}),e.jsx("p",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.vscodeExtCodeLensDesc")})]})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-lg p-3",children:[e.jsx("h4",{className:"font-semibold text-[var(--fg-primary)] text-sm mb-2",children:"Commands"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-1 text-xs text-[var(--fg-secondary)]",children:[e.jsx("p",{children:t("help.vscodeExtCmd1")}),e.jsx("p",{children:t("help.vscodeExtCmd2")}),e.jsx("p",{children:t("help.vscodeExtCmd3")}),e.jsx("p",{children:t("help.vscodeExtCmd4")}),e.jsx("p",{children:t("help.vscodeExtCmd5")})]})]})]})]}),e.jsx(vt,{id:"cli-reference",title:t("help.cliReference"),icon:e.jsx(Ps,{size:H.xl,className:"text-blue-600"}),isExpanded:s.has("cli-reference"),onToggle:r,children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:t("help.initAndEnv")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd setup"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliSetupDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd status"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliStatusDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd ui"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliUiDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd upgrade"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliUpgradeDesc")})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:t("help.kbManagement")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd sync"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliSyncDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd ais [Target]"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliAisDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd watch"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliWatchDesc")})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:t("help.cliColdstartAndScan")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd coldstart"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliColdstartDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd cursor-rules"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliCursorRulesDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd mirror"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliMirrorDesc")})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:t("help.searchAndAudit")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd search <query>"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliSearchDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd guard <file>"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliGuardDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd guard:ci"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliGuardCiDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd guard:staged"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliGuardStagedDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd server"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliServerDesc")})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:t("help.cliTaskManagement")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd task list"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliTaskListDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd task ready"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliTaskReadyDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd task prime"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliTaskPrimeDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd task stats"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliTaskStatsDesc")})]})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-[var(--fg-primary)] mb-2",children:t("help.maintenanceUpgrade")}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd upgrade"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliUpgradeMcpDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd sync --force"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliSyncForceDesc")})]}),e.jsxs("div",{className:"flex justify-between bg-[var(--bg-subtle)] px-3 py-2 rounded",children:[e.jsx("code",{children:"asd sync --dry-run"}),e.jsx("span",{className:"text-[var(--fg-secondary)] text-xs",children:t("help.cliSyncDryDesc")})]})]})]})]})})]}),e.jsx("div",{className:"mt-8 p-4 bg-blue-50 border border-blue-200 rounded-lg text-center",children:e.jsx("p",{className:"text-[var(--fg-primary)] text-sm",dangerouslySetInnerHTML:{__html:t("help.footerHint",{link:`<a href="https://github.com/GxFn/AutoSnippet" target="_blank" rel="noopener noreferrer" class="text-blue-600 hover:underline font-medium">${t("help.footerGithubReadme")}</a>`,cmd:'<code class="bg-blue-100 px-1.5 py-0.5 rounded text-xs">asd status</code>'})}})})]})};function Jo(){const[t,s]=n.useState(null);n.useEffect(()=>{const o=la(),u=g=>{s({status:"running",total:g.total,current:0,progress:0,refined:0,failed:0,items:g.candidateIds.map(d=>({candidateId:d,title:"",status:"pending"}))})},p=g=>{s(d=>d&&{...d,current:g.current,progress:g.progress,items:d.items.map(l=>l.candidateId===g.candidateId?{...l,title:g.title,status:"refining"}:l)})},c=g=>{s(d=>d&&{...d,current:g.current,progress:g.progress,refined:g.refinedSoFar,items:d.items.map(l=>l.candidateId===g.candidateId?{...l,title:g.title,status:"done",refined:g.refined}:l)})},x=g=>{s(d=>d&&{...d,current:g.current,progress:g.progress,failed:d.failed+1,items:d.items.map(l=>l.candidateId===g.candidateId?{...l,title:g.title,status:"failed",error:g.error}:l)})},h=g=>{s(d=>d&&{...d,status:"completed",progress:100,refined:g.refined,failed:g.failed})};return o.on("refine:started",u),o.on("refine:item-started",p),o.on("refine:item-completed",c),o.on("refine:item-failed",x),o.on("refine:completed",h),()=>{o.off("refine:started",u),o.off("refine:item-started",p),o.off("refine:item-completed",c),o.off("refine:item-failed",x),o.off("refine:completed",h)}},[]);const a=n.useCallback(()=>s(null),[]),r=t?.status==="running",i=t?.status==="completed";return{refine:t,isRefining:r,isRefineDone:i,resetRefine:a}}const Yo=({refine:t,isRefineDone:s,onDismiss:a})=>{const{t:r}=Ae(),i=n.useRef(!1);if(n.useEffect(()=>{if(s&&t&&!i.current){i.current=!0;const p=t.failed>0?r("refineProgress.doneMsgWithFail",{refined:String(t.refined),failed:String(t.failed)}):r("refineProgress.doneMsg",{refined:String(t.refined)});Z(p,{title:r("refineProgress.doneTitle"),type:t.failed>0?"error":"success"})}},[s,t]),n.useEffect(()=>{t||(i.current=!1)},[t]),!t)return null;const o=t.items.find(p=>p.status==="refining"),u=t.items.filter(p=>p.status==="done"||p.status==="failed").length;return e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-4 mb-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`p-1.5 rounded-lg ${s?"bg-emerald-50":"bg-blue-50"}`,children:s?e.jsx(pt,{className:"w-4 h-4 text-emerald-600"}):e.jsx(He,{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(u),total:String(t.total)}),o&&!s&&e.jsxs("span",{className:"ml-2 text-blue-600",children:[e.jsx(Ce,{className:"w-3 h-3 inline animate-spin mr-1"}),o.title||o.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(Ue,{className:"w-3 h-3"}),t.items.filter(p=>p.status==="failed").map(p=>p.title||p.candidateId.slice(0,8)).join("、")]})]})},us={_watch:"silentLabels.watch",_draft:"silentLabels.draft",_cli:"silentLabels.cli",_pending:"silentLabels.pending",_recipe:"silentLabels.recipe"},ps={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(([i],[o])=>{const u=r(i),p=r(o);if(u&&!p)return 1;if(!u&&p)return-1;const c=a(i),x=a(o);if(c&&!x)return-1;if(!c&&x)return 1;const h=s(i),g=s(o);return h&&!g?1:!h&&g?-1:i.localeCompare(o)})}function Vt(t,s){if(!t)return"";const a=typeof t=="number"?t:Number(t),r=a<1e12?a*1e3:a,i=new Date(r);if(isNaN(i.getTime())||i.getFullYear()<2e3)return"";const u=new Date().getTime()-i.getTime();if(u<0)return i.toLocaleDateString();const p=Math.floor(u/6e4);if(p<1)return s("candidates.timeJustNow");if(p<60)return s("candidates.timeMinutesAgo",{n:p});const c=Math.floor(p/60);if(c<24)return s("candidates.timeHoursAgo",{n:c});const x=Math.floor(c/24);return x<7?s("candidates.timeDaysAgo",{n:x}):i.toLocaleDateString()}function Xo(t,s=4){return t?oa(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,i=t!=null?Math.max(0,Math.min(1,t)):0,o=r*(1-i),{ring:u,text:p}=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:u,strokeDasharray:r,strokeDashoffset:o,style:{transition:"stroke-dashoffset 0.5s ease"}})]}),e.jsx("span",{className:`absolute text-[9px] font-bold ${p}`,children:t!=null?`${Math.round(t*100)}`:"—"})]})},ti=({data:t,isShellTarget:s,isSilentTarget:a=()=>!1,isPendingTarget:r=()=>!1,handleDeleteCandidate:i,handleDeleteAllInTarget:o,onAuditCandidate:u,onAuditAllInTarget:p,onEditRecipe:c,onColdStart:x,isScanning:h,isBootstrapping:g,onRefresh:d})=>{const{t:l}=Ae(),[f,y]=n.useState(null),{isWide:D,toggle:S}=da(),[T,z]=n.useState(new Set),[O]=n.useState(new Set),[G,le]=n.useState(!1),[w]=n.useState(!1),k=ns(),{refine:I,isRefining:q,isRefineDone:W,resetRefine:K}=Jo(),[C,v]=n.useState({}),[_,ae]=n.useState(null),[Q,me]=n.useState({}),[Se,ye]=n.useState(null),[j,N]=n.useState({}),[P,V]=n.useState({sort:"default",onlySimilar:!1}),[ne,ue]=n.useState(null),pe=n.useRef(new Set),Ne=n.useCallback(async(J,U)=>{if(!pe.current.has(U)){pe.current.add(U),ye(U);try{const m=await ee.getCandidateSimilarityEx({targetName:J,candidateId:U});me(b=>({...b,[U]:m.similar||[]}))}catch{me(b=>({...b,[U]:[]}))}finally{ye(null)}}},[]),De=n.useCallback(async(J,U,m,b=[])=>{const B=m.replace(/\.md$/i,"");let F="";const $=t?.recipes?.find(te=>te.name===B||te.name.endsWith("/"+B));if($?.content)F=[$.content.pattern,$.content.markdown].filter(Boolean).join(`
80
+
81
+ `)||"";else try{F=(await ee.getRecipeContentByName(B)).content}catch(te){const fe=na(te),je=ve(te);fe===404?Z(`"${B}" ${l("common.operationFailed")}`,{title:l("common.operationFailed"),type:"error"}):Z(je,{title:l("common.loadFailed"),type:"error"});return}const E={[B]:F};y(J.id),ue({candidate:J,targetName:U,recipeName:B,recipeContent:F,similarList:b.slice(0,3),recipeContents:E})},[t?.recipes]),ke=t?.candidates?Object.entries(t.candidates):[],Me=Qo(ke,s,a,r),M=Me.map(([J])=>J),A=_&&M.includes(_)?_:M[0]??null;n.useEffect(()=>{M.length>0&&(!_||!M.includes(_))&&ae(M[0])},[M.join(","),_]),n.useEffect(()=>{f&&A&&Ne(A,f)},[f,A,Ne]);const L=n.useMemo(()=>{if(!A||!t?.candidates?.[A])return null;const J=t.candidates[A].items,U=J.length,m=J.reduce((F,$)=>F+($.reasoning?.confidence??0),0)/(U||1),b=J.filter(F=>F.content?.pattern&&F.content.pattern.trim().length>0||F.coreCode&&F.coreCode.trim().length>0).length,B=new Map;return J.forEach(F=>{const $=F.source||"unknown";B.set($,(B.get($)||0)+1)}),{total:U,avgConfidence:m,withCode:b,sources:B}},[A,t?.candidates]),oe=n.useMemo(()=>{const J=new Map;if(t?.idTitleMap)for(const[U,m]of Object.entries(t.idTitleMap))J.set(U,m);if(t?.candidates)for(const U of Object.values(t.candidates))for(const m of U.items)m.id&&m.title&&J.set(m.id,m.title);if(t?.recipes)for(const U of t.recipes)U.id&&U.name&&J.set(U.id,U.name.replace(/\.md$/i,""));return J},[t?.idTitleMap,t?.candidates,t?.recipes]),be=n.useCallback(async J=>{if(!T.has(J)){z(U=>new Set(U).add(J));try{const U=await ee.enrichCandidates([J]);U.enriched>0?Z(`${U.results?.[0]?.filledFields?.length||0} ${l("candidates.approveSuccess")}`,{title:l("candidates.aiRefine")}):Z(l("recipes.noContent"),{title:l("candidates.aiRefine"),type:"info"});try{const m=await ee.getCandidate(J);N(b=>({...b,[J]:m}))}catch{}}catch(U){Z(ve(U,l("common.operationFailed")),{title:l("common.operationFailed"),type:"error"})}finally{z(U=>{const m=new Set(U);return m.delete(J),m})}}},[T,d]),Te=n.useCallback(async()=>{if(G||!A||!t?.candidates?.[A])return;const J=t.candidates[A].items;if(J.length!==0){le(!0);try{let U=0;for(let m=0;m<J.length;m+=20){const b=J.slice(m,m+20).map(F=>F.id),B=await ee.enrichCandidates(b);U+=B.enriched}Z(`${U}/${J.length} ${l("candidates.batchDeleteDone",{count:U})}`,{title:l("candidates.aiRefine")}),d?.()}catch(U){Z(ve(U,l("common.operationFailed")),{title:l("common.operationFailed"),type:"error"})}finally{le(!1)}}},[G,A,t?.candidates,d]),ce=n.useCallback(async J=>{try{const U=await ee.getCandidate(J);N(m=>({...m,[J]:U}))}catch{}},[]),ge=n.useCallback(()=>{if(!A||!t?.candidates?.[A])return;const J=t.candidates[A].items,U=J.map(m=>m.id);k.openRefine({candidateIds:U,candidates:J,onCandidateUpdated:ce})},[A,t?.candidates,k,ce]),Ee=n.useCallback(J=>{if(!A||!t?.candidates?.[A])return;ue(null),y(J);const U=t.candidates[A].items;k.openRefine({candidateIds:[J],candidates:U,onCandidateUpdated:ce})},[A,t?.candidates,k,ce]);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(He,{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:l("candidates.title")})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[x&&!g&&e.jsxs("button",{onClick:x,disabled:h,className:`flex items-center gap-1.5 px-3.5 py-2 rounded-lg text-xs font-bold transition-all ${h?"text-[var(--fg-muted)] bg-[var(--bg-subtle)] cursor-not-allowed":"text-white bg-gradient-to-r from-violet-500 to-purple-600 hover:from-violet-600 hover:to-purple-700 shadow-sm hover:shadow"}`,title:l("candidates.coldStartTitle"),children:[h?e.jsx(Ce,{size:14,className:"animate-spin"}):e.jsx(Zt,{size:14}),l(h?"common.loading":"candidates.sourceBootstrap")]}),L&&L.total>0&&e.jsxs("button",{onClick:Te,disabled:G||w,className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-all ${G||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:l("candidates.enrichTitle"),children:[G?e.jsx(Ce,{size:14,className:"animate-spin"}):e.jsx(gs,{size:14}),l(G?"common.loading":"candidates.aiEnrich")]}),L&&L.total>0&&e.jsxs("button",{onClick:ge,disabled:w||G||q,className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-bold transition-all ${w||G||q?"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:l("candidates.refineTitle"),children:[w||q?e.jsx(Ce,{size:14,className:"animate-spin"}):e.jsx(He,{size:14}),l(w||q?"common.loading":"candidates.aiRefine")]}),L&&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(mr,{size:14,className:"text-[var(--fg-muted)]"}),e.jsx("span",{className:"text-[var(--fg-secondary)]",children:l("candidates.totalCount",{count:L.total})}),L.withCode<L.total&&e.jsx("span",{className:"text-[var(--fg-muted)] ml-1",children:l("candidates.withCode",{count:L.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:l("candidates.confidence")}),e.jsxs("strong",{className:"text-emerald-700",children:[Math.round(L.avgConfidence*100),"%"]})]})]})]})]}),I&&e.jsx(Yo,{refine:I,isRefineDone:W,onDismiss:()=>{K(),d?.()}}),ke.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:M.map(J=>{const U=a(J),m=us[J]?l(us[J]):void 0,B=t?.candidates[J]?.items?.length??0,F=A===J,$=it[J]||it.All;return e.jsxs("button",{onClick:()=>ae(J),className:`flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-bold whitespace-nowrap transition-all border
82
+ ${F?`${$?.bg||"bg-blue-50"} ${$?.color||"text-blue-700"} ${$?.border||"border-blue-200"} shadow-sm ring-1 ring-inset ${$?.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 E=$?.icon||js;return e.jsx(E,{size:H.sm,className:F?"":"text-[var(--fg-muted)]"})})(),e.jsx("span",{children:ps[J]?l(ps[J]):J}),U&&m&&e.jsx("span",{className:"text-[9px] text-amber-600 border border-amber-200 px-1 rounded",children:m}),e.jsx("span",{className:`text-[10px] font-normal rounded-full px-1.5 ${F?"bg-white/60":"bg-[var(--bg-subtle)] text-[var(--fg-muted)]"}`,children:B})]},J)})})}),e.jsxs("div",{className:"flex-1 overflow-y-auto pr-1 pb-6",children:[(!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(Ks,{size:32,className:"text-[var(--fg-muted)]"})}),e.jsx("p",{className:"text-sm font-medium text-[var(--fg-secondary)]",children:l("candidates.noResults")}),e.jsx("p",{className:"mt-2 text-xs max-w-sm text-center leading-relaxed text-[var(--fg-muted)]",children:l("candidates.emptyHint")}),x&&e.jsxs("button",{onClick:x,disabled:h,className:`mt-4 flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-bold transition-all ${h?"text-[var(--fg-muted)] bg-[var(--bg-subtle)] cursor-not-allowed":"text-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:[h?e.jsx(Ce,{size:16,className:"animate-spin"}):e.jsx(Zt,{size:16}),l(h?"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"})," ",l("candidates.fullScanBtn"),e.jsx("code",{className:"text-blue-600 bg-blue-50 px-1 rounded ml-1",children:"asd candidate"})," ",l("candidates.clipboardCreate")]})]}),(!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(Ce,{size:32,className:"text-violet-400 animate-spin"})}),e.jsx("p",{className:"text-sm font-medium text-violet-400",children:l("common.loading")}),e.jsx("p",{className:"mt-2 text-xs max-w-sm text-center leading-relaxed text-[var(--fg-muted)]",children:l("candidates.scanningHint")})]}),t&&A&&Me.filter(([J])=>J===A).map(([J,U])=>{const m=s(J),b=a(J),B=us[J]?l(us[J]):l("candidates.silent"),F=C[J]||{page:1,pageSize:12},$=F.page,E=F.pageSize,te=U.items.filter(Y=>{if(P.onlySimilar){const _e=Q[Y.id];if(!Array.isArray(_e)||_e.length===0)return!1}return!0}).sort((Y,_e)=>{if(P.sort==="default")return 0;if(P.sort==="score-desc")return(_e.quality?.overall??0)-(Y.quality?.overall??0);if(P.sort==="score-asc")return(Y.quality?.overall??0)-(_e.quality?.overall??0);if(P.sort==="confidence-desc")return(_e.reasoning?.confidence??0)-(Y.reasoning?.confidence??0);if(P.sort==="date-desc"){const dt=typeof Y.createdAt=="number"?Y.createdAt:0;return(typeof _e.createdAt=="number"?_e.createdAt:0)-dt}return 0}),fe=te.length,je=Math.ceil(fe/E),Pe=($-1)*E,Le=te.slice(Pe,Pe+E),de=Y=>{v(_e=>({..._e,[J]:{...F,page:Y}}))},Oe=Y=>{v(_e=>({..._e,[J]:{page:1,pageSize:Y}}))},Be=it[J]||it.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 Y=Be?.icon||js;return e.jsx(Y,{size:18,className:Be?.color||"text-blue-600"})})(),e.jsx("span",{className:"text-base font-bold text-[var(--fg-primary)] truncate",children:ps[J]?l(ps[J]):J}),b&&e.jsx("span",{className:"text-[10px] font-bold text-amber-600 border border-amber-200 bg-amber-50 px-1.5 py-0.5 rounded",children:B}),m&&!b&&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(tt,{size:11}),l("candidates.scannedAt",{time:Vt(U.scanTime,l)||new Date(U.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(Ln,{size:12,className:"text-[var(--fg-muted)]"}),e.jsx(Ze,{value:P.sort,onChange:Y=>V(_e=>({..._e,sort:Y})),options:[{value:"default",label:l("candidates.sortNewest")},{value:"score-desc",label:`${l("candidates.sortConfidence")} ↓`},{value:"score-asc",label:`${l("candidates.sortConfidence")} ↑`},{value:"confidence-desc",label:`${l("candidates.confidence")} ↓`},{value:"date-desc",label:l("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:Y=>V(_e=>({..._e,onlySimilar:Y.target.checked})),className:"rounded text-blue-600 w-3 h-3"}),l("candidates.similarOnly")]}),(P.sort!=="default"||P.onlySimilar)&&e.jsx("button",{onClick:()=>V({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:l("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:l("candidates.totalCount",{count:fe})}),e.jsx("button",{onClick:()=>p(Le,J),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:l("candidates.approveCurrentPage")}),e.jsx("button",{onClick:async()=>{if(!window.confirm(l("candidates.batchDeleteConfirm",{count:Le.length})))return;const _e=(await Promise.allSettled(Le.map(dt=>i(J,dt.id)))).filter(dt=>dt.status==="rejected").length;_e>0&&Z(`${_e} ${l("common.deleteFailed")}`,{title:l("common.operationFailed"),type:"error"}),d?.()},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:l("candidates.removeCurrentPage")}),e.jsx("button",{onClick:()=>o(J),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:l("candidates.deleteAll")})]})]}),e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3",children:Le.map(Y=>{const _e=f===Y.id,dt=Y.reasoning?.confidence??null,bt=(Y.quality?.overall??0)>0?Y.quality?.overall??null:null,zt=Q[Y.id]||[],Re=zt[0]||null,nt=Ra[Y.source||""]||{labelKey:Y.source||"",color:"text-[var(--fg-secondary)] bg-[var(--bg-subtle)] border-[var(--border-default)]"},Xe=it[Y.category||""]||it.All||{};return e.jsxs("div",{onClick:()=>y(_e?null:Y.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
+ ${m?"opacity-75":""}
84
+ ${_e?"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 ${Xe?.bg||"bg-[var(--bg-subtle)]"} ${Xe?.color||"text-[var(--fg-muted)]"} ${Xe?.border||"border-[var(--border-default)]"}`,children:[(()=>{const We=Xe?.icon||rt;return e.jsx(We,{size:10})})(),Y.category||"general"]}),Y.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:Y.knowledgeType}),Y.source&&Y.source!=="unknown"&&e.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border ${nt.color}`,children:nt.labelKey.startsWith("candidates.")?l(nt.labelKey):nt.labelKey}),Y.complexity&&e.jsx("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded border
85
+ ${Y.complexity==="advanced"?"bg-red-50 text-red-600 border-red-100":Y.complexity==="intermediate"?"bg-amber-50 text-amber-600 border-amber-100":"bg-emerald-50 text-emerald-600 border-emerald-100"}`,children:Y.complexity==="advanced"?l("candidates.confidenceHigh"):Y.complexity==="intermediate"?l("candidates.confidenceMedium"):l("candidates.confidenceLow")})]}),e.jsx("h3",{className:"font-bold text-sm text-[var(--fg-primary)] leading-snug mb-1 line-clamp-1",children:Y.title}),e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] line-clamp-2 leading-relaxed",children:Y.description||""})]}),e.jsxs("div",{className:"flex flex-col items-center gap-1 shrink-0",children:[e.jsx(ei,{value:dt}),e.jsx("span",{className:"text-[9px] text-[var(--fg-muted)] font-medium",children:l("candidates.confidence")})]})]})}),Y.reasoning?.whyStandard&&!/^Submitted via /i.test(Y.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(qt,{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:Y.reasoning.whyStandard})]})}),(bt!=null||Re)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 px-4 py-2 border-t border-[var(--border-default)]",children:[bt!=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(rs,{size:10}),l("candidates.overallScore",{score:(bt*100).toFixed(0)+"%"})]}),Re&&e.jsxs("button",{onClick:We=>{We.stopPropagation();const Je=String(Re.recipeName||"").trim();Je&&De(Y,J,Je,zt)},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:l("candidates.similarWith",{name:Re.recipeName,score:(Re.similarity*100).toFixed(0)}),children:[e.jsx(hs,{size:10}),l("candidates.similarPrefix")," ",Re.recipeName.replace(/\.md$/i,"")," ",(Re.similarity*100).toFixed(0),"%"]})]}),Y.content?.pattern&&e.jsxs("div",{className:"overflow-hidden border-t border-[var(--border-default)]/60",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5",style:{background:"#282c34"},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ht,{size:11,className:"text-[var(--fg-secondary)]"}),e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] font-mono uppercase tracking-wide",children:Y.language||"code"})]}),e.jsx("span",{className:"text-[10px] text-[var(--fg-secondary)] font-mono tabular-nums",children:l("candidates.linesCount",{count:Y.content.pattern.split(`
86
+ `).length})})]}),e.jsxs("div",{className:"relative max-h-[80px] overflow-hidden",children:[e.jsx(ft,{code:Xo(Y.content.pattern,3),language:Y.language==="objc"?"objectivec":Y.language,className:"!rounded-none"}),Y.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:We=>We.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap min-w-0",children:[Y.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:Y.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:Y.language}),Y.tags&&Y.tags.length>0&&Y.tags.slice(0,3).map((We,Je)=>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 We=="string"?We:String(We)},Je)),Y.tags&&Y.tags.length>3&&e.jsxs("span",{className:"text-[9px] text-[var(--fg-muted)]",children:["+",Y.tags.length-3]}),Y.createdAt&&Vt(Y.createdAt,l)&&e.jsxs("span",{className:"text-[9px] text-[var(--fg-muted)] flex items-center gap-0.5",children:[e.jsx(tt,{size:9}),Vt(Y.createdAt,l)]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[e.jsx("button",{onClick:()=>be(Y.id),disabled:T.has(Y.id),title:l("candidates.enrichTitleSingle"),className:`p-1.5 rounded-lg transition-colors flex items-center gap-1 text-[11px] font-medium ${T.has(Y.id)?"text-[var(--fg-muted)] cursor-not-allowed":"text-amber-500 hover:text-amber-600 hover:bg-amber-50"}`,children:T.has(Y.id)?e.jsx(Ce,{size:14,className:"animate-spin"}):e.jsx(gs,{size:14})}),e.jsx("button",{onClick:()=>Ee(Y.id),disabled:O.has(Y.id),title:l("candidates.refineTitleSingle"),className:`p-1.5 rounded-lg transition-colors flex items-center gap-1 text-[11px] font-medium ${O.has(Y.id)?"text-[var(--fg-muted)] cursor-not-allowed":"text-emerald-500 hover:text-emerald-600 hover:bg-emerald-50"}`,children:O.has(Y.id)?e.jsx(Ce,{size:14,className:"animate-spin"}):e.jsx(He,{size:14})}),e.jsx("button",{onClick:()=>{i(J,Y.id),f===Y.id&&(y(null),ue(null))},title:l("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(et,{size:14})}),e.jsxs("button",{onClick:()=>u(Y,J),className:"text-[11px] font-bold text-blue-600 hover:text-blue-700 px-3 py-1.5 rounded-lg bg-blue-50 hover:bg-blue-100 transition-colors flex items-center gap-1",children:[e.jsx(Et,{size:12})," ",l("candidates.approveAndSave")]}),Y.lifecycle==="pending"&&e.jsxs("button",{onClick:async()=>{try{await ee.promoteCandidateToRecipe(Y.id),Z(l("candidates.approveSuccess"),{title:l("candidates.approveSuccess")}),d?.()}catch(We){Z(ve(We,l("common.operationFailed")),{title:l("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:l("candidates.approve"),children:[e.jsx(Zt,{size:12})," ",l("candidates.approve")]})]})]})]},Y.id)})}),fe>12&&e.jsx(ua,{currentPage:$,totalPages:je,totalItems:fe,pageSize:E,onPageChange:de,onPageSizeChange:Oe})]},J)})]}),f&&A&&t?.candidates?.[A]&&(()=>{const J=t.candidates[A].items,U=J.find(de=>de.id===f);if(!U)return null;const m=j[f]||U,b=J.findIndex(de=>de.id===f),B=b>0,F=b<J.length-1,$=()=>{B&&(y(J[b-1].id),ue(null))},E=()=>{F&&(y(J[b+1].id),ue(null))},te=m.reasoning,fe=Q[m.id]||[],je=Se===m.id,Pe=it[m.category||""]||it.All||{},Le=Ra[m.source||""]||{labelKey:m.source||"",color:"text-[var(--fg-secondary)] bg-[var(--bg-subtle)] border-[var(--border-default)]"};return e.jsxs(Ve,{className:"z-30 flex justify-end",onClick:()=>{y(null),ue(null)},children:[e.jsx(Ve.Backdrop,{className:"bg-black/20 dark:bg-black/40 backdrop-blur-sm"}),ne&&(()=>{const de=ne.candidate,Oe=de.language==="objc"||de.language==="objective-c"?"objectivec":de.language||"text",Be=()=>{const Re=[];de.content?.pattern&&Re.push("## Snippet / Code Reference\n\n```"+Oe+`
88
+ `+de.content.pattern+"\n```"),de.content?.markdown?Re.push(`
89
+ ## `+l("candidates.projectProfile")+`
90
+
91
+ `+de.content.markdown):de.doClause&&Re.push(`
92
+ ## AI Context / Usage Guide
93
+
94
+ `+de.doClause),navigator.clipboard.writeText(Re.join(`
95
+ `)||"").then(()=>Z(l("common.copied"),{title:l("common.copied")})).catch(()=>{})},Y=()=>{const Re=ia(ne.recipeContent);navigator.clipboard.writeText(Re).then(()=>Z(l("common.copied"),{title:l("common.copied")})).catch(()=>{})},_e=async Re=>{if(Re===ne.recipeName)return;const nt=ne.recipeContents[Re];if(nt)ue(Xe=>Xe?{...Xe,recipeName:Re,recipeContent:nt}:null);else{let Xe="";const We=t?.recipes?.find(Je=>Je.name===Re||Je.name.endsWith("/"+Re));if(We?.content)Xe=[We.content.pattern,We.content.markdown].filter(Boolean).join(`
96
+
97
+ `)||"";else try{Xe=(await ee.getRecipeContentByName(Re)).content}catch{return}ue(Je=>Je?{...Je,recipeName:Re,recipeContent:Xe,recipeContents:{...Je.recipeContents,[Re]:Xe}}:null)}},dt=async()=>{if(window.confirm(l("common.areYouSure")))try{await i(ne.targetName,de.id),ue(null)}catch(Re){Z(ve(Re,l("common.deleteFailed")),{title:l("common.deleteFailed"),type:"error"})}},bt=()=>{u(de,ne.targetName),ue(null)},zt=()=>{const Re=t?.recipes?.find(nt=>nt.name===ne.recipeName||nt.name.endsWith("/"+ne.recipeName));c?.(Re||{name:ne.recipeName,content:{markdown:ne.recipeContent}}),ue(null)};return e.jsxs(we.Panel,{width:D?"w-[800px] max-w-[55vw]":"w-[600px] max-w-[45vw]",animationDuration:"0.2s",children:[e.jsxs(we.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(hs,{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:l("candidates.recipeCompare")}),e.jsx("span",{className:"text-[11px] text-emerald-600 truncate block",children:ne.recipeName.replace(/\.md$/i,"")})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 ml-2",children:[e.jsx(Ge,{variant:"ghost",size:"icon-sm",onClick:()=>Y(),title:l("common.copy"),className:"text-emerald-600 hover:bg-emerald-100",children:e.jsx(Ot,{size:14})}),e.jsx("button",{onClick:zt,className:"text-[11px] font-medium text-emerald-600 hover:bg-emerald-100 px-2 py-1.5 rounded-lg transition-colors",children:l("candidates.approveAndSave")}),e.jsx(we.CloseButton,{onClose:()=>ue(null)})]})]}),ne.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:ne.similarList.map(Re=>e.jsxs("button",{onClick:()=>_e(Re.recipeName),className:`text-[10px] font-bold px-2 py-1 rounded transition-colors ${ne.recipeName===Re.recipeName?"bg-emerald-200 text-emerald-800":"bg-[var(--bg-surface)] text-emerald-600 hover:bg-emerald-50 border border-emerald-100"}`,children:[Re.recipeName.replace(/\.md$/i,"")," ",(Re.similarity*100).toFixed(0),"%"]},Re.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:dt,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(et,{size:12})," ",l("common.delete")]}),e.jsxs("button",{onClick:bt,className:"text-xs font-medium text-blue-600 hover:bg-blue-50 px-2.5 py-1.5 rounded-lg transition-colors flex items-center gap-1",children:[e.jsx(Et,{size:12})," ",l("candidates.approveAndSave")]}),e.jsxs("button",{onClick:()=>Be(),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(Ot,{size:12})," ",l("common.copy")]})]}),e.jsx(we.Body,{padded:!0,children:e.jsx(Ct,{content:ne.recipeContent,stripFrontmatter:!0})})]})})(),e.jsxs(we.Panel,{size:D?"lg":"md",children:[e.jsxs(we.Header,{title:m.title,children:[e.jsx(we.Nav,{currentIndex:b,total:J.length,onPrev:$,onNext:E,hasPrev:B,hasNext:F}),e.jsxs(we.HeaderActions,{children:[e.jsx(we.WidthToggle,{isWide:D,onToggle:S,title:l(D?"common.collapse":"common.expand")}),e.jsx(Ge,{variant:"danger",size:"icon-sm",onClick:()=>{i(A,m.id),y(null),ue(null)},children:e.jsx(et,{size:16})}),e.jsx(we.CloseButton,{onClose:()=>{y(null),ue(null)}})]})]}),e.jsxs(we.Body,{children:[e.jsx(pa,{badges:(()=>{const de=[];return de.push({label:m.category||"general",className:`font-bold uppercase ${Pe?.bg||"bg-[var(--bg-subtle)]"} ${Pe?.color||"text-[var(--fg-muted)]"} ${Pe?.border||"border-[var(--border-default)]"}`}),m.knowledgeType&&de.push({label:m.knowledgeType,className:"bg-purple-50 text-purple-700 border-purple-200"}),m.language&&de.push({label:m.language,className:"uppercase font-bold text-[var(--fg-secondary)] bg-[var(--bg-subtle)] border-[var(--border-default)]"}),m.complexity&&de.push({label:m.complexity==="advanced"?l("candidates.confidenceHigh"):m.complexity==="intermediate"?l("candidates.confidenceMedium"):l("candidates.confidenceLow"),className:m.complexity==="advanced"?"bg-red-50 text-red-600 border-red-100":m.complexity==="intermediate"?"bg-amber-50 text-amber-600 border-amber-100":"bg-emerald-50 text-emerald-600 border-emerald-100"}),m.trigger&&de.push({label:m.trigger,className:"font-mono font-bold bg-amber-50 text-amber-700 border-amber-200"}),m.source&&m.source!=="unknown"&&de.push({label:Le.labelKey.startsWith("candidates.")?l(Le.labelKey):Le.labelKey,className:Le.color}),m.lifecycle&&m.lifecycle!=="pending"&&de.push({label:m.lifecycle,className:"bg-blue-50 text-blue-600 border-blue-200"}),de})(),metadata:(()=>{const de=[];return m.scope&&de.push({icon:_t,iconClass:"text-teal-400",label:l("candidates.path"),value:m.scope==="universal"?l("common.all"):m.scope==="project-specific"||m.scope==="module-level"?l("candidates.category"):m.scope}),m.source&&m.source!=="unknown"&&de.push({icon:_t,iconClass:"text-violet-400",label:l("candidates.source"),value:Le.labelKey.startsWith("candidates.")?l(Le.labelKey):Le.labelKey}),m.createdAt&&Vt(m.createdAt,l)&&de.push({icon:tt,iconClass:"text-[var(--fg-muted)]",label:l("candidates.createdAt"),value:Vt(m.createdAt,l)}),de})(),tags:m.tags,maxTags:10}),e.jsx(Fe.Description,{label:l("candidates.description"),text:m.description}),e.jsx(Fe.Reasoning,{reasoning:te,labels:{section:l("knowledge.reasoning"),source:`${l("candidates.source")}:`,confidence:`${l("candidates.confidence")}:`,alternatives:`${l("candidates.viewDetail")}:`},filterSubmitted:!0}),e.jsx(Fe.Quality,{quality:m.quality,labels:{section:l("candidates.qualityDimensions"),completeness:l("recipes.qualityCompleteness"),adaptation:l("recipes.qualityAdaptation"),documentation:l("recipes.qualityDocumentation")}}),(()=>{const de=m.relations?Object.entries(m.relations).flatMap(([Be,Y])=>Array.isArray(Y)?Y.map(_e=>({..._e,type:Be})):[]):[];return m.agentNotes||m.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(He,{size:11,className:"text-emerald-400"})," ",l("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:[m.aiInsight&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)] font-bold",children:[l("candidates.viewDetail"),":"]}),e.jsx("p",{className:"text-sm text-[var(--fg-primary)] leading-relaxed mt-0.5",children:m.aiInsight})]}),m.agentNotes&&m.agentNotes.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] font-bold",children:l("candidates.agentNotes")}),e.jsx("ul",{className:"mt-1 space-y-0.5",children:m.agentNotes.map((Be,Y)=>e.jsxs("li",{className:"flex items-start gap-1.5 text-[var(--fg-secondary)]",children:[e.jsx("span",{className:"text-emerald-400 mt-0.5",children:"•"}),Be]},Y))})]}),de.length>0&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)] font-bold",children:[l("recipes.relations"),":"]}),e.jsx("div",{className:"mt-1 space-y-1",children:de.map((Be,Y)=>e.jsxs("div",{className:"flex items-start gap-1.5 text-[var(--fg-secondary)]",children:[e.jsx("span",{className:"text-[9px] font-bold px-1 py-0.5 rounded bg-emerald-100 text-emerald-700 shrink-0 uppercase",children:Be.type}),e.jsx("span",{className:"font-medium text-[var(--fg-primary)]",children:oe.get(Be.target)||Be.target}),Be.description&&e.jsxs("span",{className:"text-[var(--fg-muted)]",children:["— ",Be.description]})]},Y))})]})]})]}):null})(),fe.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:[l("candidates.similarRecipe"),je&&e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] animate-pulse",children:l("common.loading")})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:fe.slice(0,5).map(de=>e.jsxs("button",{onClick:()=>De(m,A,de.recipeName,fe),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:l("candidates.similarWith",{name:de.recipeName,score:(de.similarity*100).toFixed(0)}),children:[e.jsx(hs,{size:10}),de.recipeName.replace(/\.md$/i,"")," ",(de.similarity*100).toFixed(0),"%"]},de.recipeName))})]}),e.jsx(Fe.CodePattern,{label:l("knowledge.codePattern"),code:m.content?.pattern,language:m.language}),e.jsx(Fe.MarkdownSection,{label:l("knowledge.markdownDoc"),content:m.content?.markdown}),e.jsx(Fe.Delivery,{delivery:{topicHint:m.topicHint,whenClause:m.whenClause,doClause:m.doClause,dontClause:m.dontClause,coreCode:m.coreCode},language:m.language}),e.jsx(Fe.Rationale,{label:l("candidates.rationale"),text:m.content?.rationale}),e.jsx(Fe.Headers,{label:l("candidates.headers"),headers:m.headers}),e.jsx(Fe.Steps,{label:l("recipes.steps"),steps:m.content?.steps})]}),e.jsxs(we.Footer,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:()=>be(m.id),disabled:T.has(m.id),title:l("candidates.enrichTitleBottom"),className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium transition-colors ${T.has(m.id)?"text-[var(--fg-muted)] cursor-not-allowed":"text-amber-600 hover:bg-amber-50 border border-amber-200"}`,children:[T.has(m.id)?e.jsx(Ce,{size:14,className:"animate-spin"}):e.jsx(gs,{size:14}),l("candidates.enrichShort")]}),e.jsxs("button",{onClick:()=>Ee(m.id),disabled:O.has(m.id),title:l("candidates.refineTitleBottom"),className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium transition-colors ${O.has(m.id)?"text-[var(--fg-muted)] cursor-not-allowed":"text-emerald-600 hover:bg-emerald-50 border border-emerald-200"}`,children:[O.has(m.id)?e.jsx(Ce,{size:14,className:"animate-spin"}):e.jsx(He,{size:14}),l("candidates.refineShort")]}),e.jsxs("button",{onClick:()=>{i(A,m.id),y(null),ue(null)},title:l("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(et,{size:14})," ",l("common.delete")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[m.lifecycle==="pending"&&e.jsxs("button",{onClick:async()=>{try{await ee.promoteCandidateToRecipe(m.id),Z(l("candidates.approveSuccess"),{title:l("candidates.approveSuccess")}),d?.()}catch(de){Z(ve(de,l("common.operationFailed")),{title:l("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(Zt,{size:14})," ",l("candidates.approve")]}),e.jsxs("button",{onClick:()=>{u(m,A),y(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(Et,{size:14})," ",l("candidates.approveAndSave")]})]})]})]})]})})()]})},si=({isOpen:t,onClose:s,currentFile:a,targetName:r,language:i="",onSelectRecipe:o})=>{const{t:u}=Ae(),[p,c]=n.useState(""),[x,h]=n.useState([]),[g,d]=n.useState(null),[l,f]=n.useState(!1),[y,D]=n.useState(null),[S,T]=n.useState(!1),[z,O]=n.useState(null),G=async()=>{if(p.trim()){f(!0);try{const w=await ee.search(p,{context:{language:i},limit:10});h((w.items||[]).map(k=>({name:(k.title||k.name||"")+".md",content:k.content?.pattern||k.content?.markdown||k.content?.code||"",similarity:k.score||0,authority:k.authorityScore||0,matchType:k.matchType||"ranked",qualityScore:k.qualityScore||0,usageCount:k.usageCount||0}))),d(null)}catch(w){console.error("Context-aware search failed:",w),alert(u("search.searchFailed"))}finally{f(!1)}}},le=w=>{w.key==="Enter"&&G()};return t?e.jsxs(Ve,{className:"z-30 flex",children:[e.jsx(Ve.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:u("search.title")}),e.jsx("button",{onClick:s,className:"p-1 hover:bg-slate-100 rounded-lg transition-colors",children:e.jsx(Ue,{size:H.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(Ke,{size:H.md,className:"text-blue-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1",children:[g.targetInfo?.targetName&&e.jsxs("div",{className:"text-blue-900 font-medium flex items-center gap-2 mb-1",children:[e.jsx(ha,{size:H.sm}),"Target: ",g.targetInfo.targetName]}),g.fileInfo?.imports&&g.fileInfo.imports.length>0&&e.jsxs("div",{className:"text-blue-800 text-xs mt-2",children:[e.jsx("strong",{children:u("search.importedFrameworks")})," ",g.fileInfo.imports.slice(0,3).join(", "),g.fileInfo.imports.length>3&&` +${g.fileInfo.imports.length-3}`]}),g.targetInfo?.suggestedApis&&g.targetInfo.suggestedApis.length>0&&e.jsxs("div",{className:"text-blue-800 text-xs mt-1",children:[e.jsx("strong",{children:u("search.relatedApis")})," ",g.targetInfo.suggestedApis.slice(0,3).join(", ")]})]})]})}),e.jsxs("div",{className:"relative",children:[e.jsx(ht,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-400",size:H.md}),e.jsx("input",{type:"text",placeholder:u("search.searchPlaceholder"),value:p,onChange:w=>c(w.target.value),onKeyDown:le,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:G,disabled:!p.trim()||l,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:[l&&e.jsx(Ce,{size:H.sm,className:"animate-spin"}),u(l?"search.searching":"search.searchBtn")]})]}),e.jsxs("div",{className:"flex-1 overflow-auto",children:[x.length===0&&!l&&e.jsx("div",{className:"flex items-center justify-center h-full text-slate-500",children:e.jsxs("div",{className:"text-center",children:[e.jsx(xr,{size:H.xxl,className:"mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:u("search.emptyHint")})]})}),x.map((w,k)=>e.jsxs("div",{className:"border-b border-slate-200 p-4 hover:bg-slate-50 transition-colors cursor-pointer",onClick:()=>{D(y===k?null:k),w.name&&o?.(w.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:w.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(Ke,{size:H.xs}),Math.round(w.similarity*100),"%"]}),w.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(ha,{size:H.xs}),u("search.contextRelevant")]}),w.matchType&&e.jsx("span",{className:"text-xs text-slate-500",children:w.matchType==="semantic"?u("search.matchSemantic"):u("search.matchKeyword")})]})]}),e.jsx("button",{onClick:I=>{I.stopPropagation(),D(y===k?null:k)},className:"p-1 hover:bg-slate-200 rounded transition-colors",children:y===k?"▼":"▶"})]}),w.stats&&e.jsxs("div",{className:"text-xs text-slate-500 mb-2 flex gap-3",children:[w.stats.authorityScore!==void 0&&e.jsxs("span",{children:[u("search.authorityScore"),": ",w.stats.authorityScore]}),w.usageCount!==void 0&&e.jsxs("span",{children:[u("search.usage"),": ",u("search.usageCount",{count:w.usageCount})]})]}),y===k&&e.jsxs("div",{className:"mt-3 pt-3 border-t border-slate-200",children:[w.recommendReason&&e.jsxs("div",{className:"text-xs text-slate-600 bg-blue-50 p-2 rounded mb-2 border border-blue-100",children:[e.jsx("p",{className:"font-medium text-blue-700 mb-0.5",children:u("search.recommendReason")}),e.jsx("p",{children:w.recommendReason})]}),e.jsxs("div",{className:"text-xs text-slate-600 max-h-[200px] overflow-auto bg-slate-50 p-3 rounded",children:[w.content.substring(0,500),"..."]}),e.jsx("button",{onClick:I=>{I.stopPropagation(),O(w),T(!0)},className:"mt-2 w-full py-1.5 bg-blue-50 text-blue-600 rounded text-xs font-medium hover:bg-blue-100 transition-colors",children:u("search.viewFullContent")})]})]},k)),l&&e.jsx("div",{className:"flex items-center justify-center h-32",children:e.jsx(Ce,{size:H.lg,className:"animate-spin text-blue-600"})}),x.length===0&&p&&!l&&e.jsx("div",{className:"flex items-center justify-center h-32",children:e.jsxs("div",{className:"text-center text-slate-500",children:[e.jsx(Kt,{size:H.xl,className:"mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:u("search.noResults")})]})})]})]}),S&&z&&e.jsxs(Ve,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx(Ve.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:z.name}),e.jsxs("div",{className:"flex items-center gap-4 mt-2",children:[e.jsxs("span",{className:"text-xs bg-blue-100 text-blue-700 px-2 py-1 rounded",children:[u("search.similarity"),": ",Math.round(z.similarity*100),"%"]}),z.isContextRelevant&&e.jsxs("span",{className:"text-xs bg-green-100 text-green-700 px-2 py-1 rounded",children:["✓ ",u("search.contextRelevant")]}),z.qualityScore!==void 0&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-blue-100 rounded text-xs text-blue-700 font-medium",children:["🤖 ",u("search.quality"),": ",(z.qualityScore*100).toFixed(0),"%"]}),z.stats?.authorityScore!==void 0&&e.jsxs("span",{className:"text-xs bg-purple-100 text-purple-700 px-2 py-1 rounded",children:[u("search.authorityScore"),": ",Math.round(z.stats.authorityScore*100)/100]})]})]}),e.jsx("button",{onClick:()=>T(!1),className:"p-1 hover:bg-slate-100 rounded transition-colors shrink-0",children:e.jsx(Ue,{size:H.lg,className:"text-slate-500"})})]}),e.jsx("div",{className:"overflow-auto flex-1 p-6",children:e.jsx("div",{className:"prose prose-sm max-w-none",children:z.content?e.jsx(ft,{code:z.content,language:"markdown"}):e.jsx("p",{className:"text-slate-500 text-sm",children:u("search.noContent")})})}),e.jsxs("div",{className:"border-t border-slate-200 p-4 bg-slate-50 flex justify-end gap-2 shrink-0",children:[e.jsx("button",{onClick:()=>T(!1),className:"px-4 py-2 text-slate-700 hover:bg-slate-200 rounded transition-colors text-sm font-medium",children:u("common.close")}),o&&e.jsxs("button",{onClick:()=>{o(z.name),T(!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(Qe,{size:H.md}),u("search.useSnippet")]})]})]})]})]}):null},Ia=t=>ra(t.language)||"text";function ai(t){const s=[],a=t.match(/#import\s+"([^"]+)"/);if(a){const u=a[1].replace(/\.h$/,"");s.push(u)}const r=t.match(/#import\s+<([^>]+)>/);if(r){const u=r[1].replace(/\.h$/,"").split("/");s.push(...u)}const i=t.match(/^import\s+(\w+)/);i&&s.push(i[1]);const o=t.match(/@import\s+(\w+)/);return o&&s.push(o[1]),[...new Set(s.filter(Boolean))]}function Jt(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=>{const s=(t.content?.pattern||"").trim();if(!s)return!1;const a=s.split(`
98
+ `).filter(i=>i.trim());return!(a.filter(i=>/^\s*(#{1,6}\s|[-*>]\s|\d+\.\s)/.test(i)).length>a.length*.3)},oi=({res:t,index:s,editingCodeIndex:a,setEditingCodeIndex:r,expandedEditIndex:i,setExpandedEditIndex:o,similarityMap:u,handleUpdateScanResult:p,handleSaveExtracted:c,handlePromoteToCandidate:x,openCompare:h,isSavingRecipe:g=!1})=>{const{t:d}=Ae(),[l,f]=n.useState(!1),y=i===s,D=t.headers||[],S=t.content?.pattern||"",T=t.content?.markdown||"",z=t.description||"",O=t.tags||[],G=li(t),le=(w,k)=>{p(s,{content:{...t.content||{},[w]:k}})};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:d("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(rt,{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(Ke,{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"?d("scanResult.lifecyclePending"):t.lifecycle==="active"?d("scanResult.lifecycleActive"):t.lifecycle==="deprecated"?d("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"?d("scanResult.aiScan"):t.source})]}),e.jsx("input",{className:"font-semibold bg-transparent border-b-2 border-transparent hover:border-slate-200 focus:border-blue-500 outline-none px-0.5 text-lg w-full text-slate-800 placeholder:text-slate-300",value:t.title||"",onChange:w=>p(s,{title:w.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(Mn,{size:H.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 ${G&&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(Ce,{size:H.md,className:"animate-spin"}):e.jsx(gr,{size:H.md}),d(g?"scanResult.saving":G?"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:d("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:d("scanResult.triggerPlaceholder"),onChange:w=>p(s,{trigger:w.target.value})})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:"Kind"}),e.jsx(Ze,{value:t.kind||"pattern",onChange:w=>p(s,{kind:w}),options:[{value:"rule",label:"Rule"},{value:"pattern",label:"Pattern"},{value:"fact",label:"Fact"}],size:"xs"})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:"Topic"}),e.jsx(Ze,{value:t.topicHint||"",onChange:w=>p(s,{topicHint:w}),options:ni.map(w=>({value:w.value,label:w.label})),size:"xs"})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:d("scanResult.category")}),e.jsx(Ze,{value:t.category||"",onChange:w=>p(s,{category:w}),options:il.filter(w=>w!=="All").map(w=>({value:w,label:w})),size:"xs"})]}),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-px h-6 bg-slate-200 self-end mb-0.5"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:d("scanResult.language")}),e.jsx(Ze,{value:ra(t.language),onChange:w=>p(s,{language:w}),options:$t.map(w=>({value:w.id,label:w.label})),size:"xs"})]})]}),t.moduleName&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-px h-6 bg-slate-200 self-end mb-0.5"}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:d("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"}),G&&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:d("scanResult.mode")}),e.jsxs("div",{className:"flex bg-white dark:bg-[#252a36] p-0.5 rounded-md border border-slate-200 dark:border-slate-600",children:[e.jsx("button",{onClick:()=>p(s,{mode:"full"}),className:`px-2.5 py-0.5 rounded text-[10px] font-bold transition-all ${t.mode==="full"?"bg-blue-100 shadow-sm text-blue-600":"text-slate-400 hover:text-slate-500"}`,children:"Snippet+Recipe"}),e.jsx("button",{onClick:()=>p(s,{mode:"preview"}),className:`px-2.5 py-0.5 rounded text-[10px] font-bold transition-all ${t.mode==="preview"?"bg-amber-100 shadow-sm text-amber-600":"text-slate-400 hover:text-slate-500"}`,children:"Recipe Only"})]})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsx("label",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider ml-0.5 mb-1",children:d("scanResult.difficulty")}),e.jsx(Ze,{value:t.difficulty||"intermediate",onChange:w=>p(s,{difficulty:w,complexity:w}),options:[{value:"beginner",label:d("scanResult.difficultyBeginner")},{value:"intermediate",label:d("scanResult.difficultyIntermediate")},{value:"advanced",label:d("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:d("scanResult.authorityScore")}),e.jsx(Ze,{value:String(t.authority??t.stats?.authority??3),onChange:w=>p(s,{authority:parseInt(w)}),options:[{value:"1",label:"⭐ 1",icon:""},{value:"2",label:"⭐⭐ 2",icon:""},{value:"3",label:"⭐⭐⭐ 3",icon:""},{value:"4",label:"⭐⭐⭐⭐ 4",icon:""},{value:"5",label:"⭐⭐⭐⭐⭐ 5",icon:""}],size:"xs",className:"font-bold text-amber-600 bg-amber-50 border-amber-100"})]})]}),e.jsx("div",{className:"mt-2.5",children:e.jsxs("div",{className:"flex flex-wrap gap-1 items-center bg-white dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 rounded-md px-1.5 py-0.5 min-h-[28px] focus-within:ring-2 focus-within:ring-blue-500/20",children:[O.map((w,k)=>e.jsxs("span",{className:"flex items-center gap-0.5 text-[10px] font-bold bg-blue-50 text-blue-700 border border-blue-200 px-1.5 py-0 rounded",children:[w,e.jsx("button",{onClick:()=>{const I=[...O];I.splice(k,1),p(s,{tags:I})},className:"text-blue-400 hover:text-red-500 transition-colors leading-none text-[10px]",title:"{t('scanResult.removeTag')}",children:"×"})]},k)),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?d("scanResult.tagsPlaceholder"):"",onKeyDown:w=>{const k=w.currentTarget,I=k.value.trim();if((w.key==="Enter"||w.key===","||w.key===",")&&I){w.preventDefault();const q=I.replace(/[,,]/g,"").trim();q&&!O.includes(q)&&p(s,{tags:[...O,q]}),k.value=""}else if(w.key==="Backspace"&&!k.value&&O.length>0){const q=[...O];q.pop(),p(s,{tags:q})}},onBlur:w=>{const k=w.currentTarget.value.trim().replace(/[,,]/g,"").trim();k&&!O.includes(k)&&p(s,{tags:[...O,k]}),w.currentTarget.value=""}})]})}),G&&D.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:d("scanResult.headers")}),e.jsxs("button",{onClick:()=>o(i===s?null:s),className:`text-[10px] font-bold px-2 py-0.5 rounded-md transition-colors border ${y?"text-blue-700 bg-blue-100 border-blue-300":"text-blue-600 bg-blue-50 border-blue-100 hover:bg-blue-100"}`,children:[d(y?"scanResult.collapseHeaders":"scanResult.editHeaders")," (",D.length,")"]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[9px] text-slate-400",children:"Snippet:"}),e.jsx("button",{onClick:()=>p(s,{includeHeaders:t.includeHeaders===!1}),className:`w-7 h-4 rounded-full relative transition-colors ${t.includeHeaders!==!1?"bg-blue-600":"bg-slate-300"}`,title:t.includeHeaders!==!1?d("scanResultCard.includeMarkOn"):d("scanResultCard.includeMarkOff"),children:e.jsx("div",{className:`absolute top-0.5 w-2.5 h-2.5 bg-white rounded-full transition-all ${t.includeHeaders!==!1?"right-0.5":"left-0.5"}`})}),e.jsx("span",{className:"text-[9px] font-bold text-slate-600",children:t.includeHeaders!==!1?"ON":"OFF"})]}),(()=>{const w=D.filter(I=>Jt(I,S)==="used").length,k=D.filter(I=>Jt(I,S)==="unused").length;return e.jsxs("span",{className:"text-[9px] text-slate-400",children:[w>0&&e.jsxs("span",{className:"text-green-600 font-bold",children:[w," ",d("scanResult.referenced")]}),w>0&&k>0&&" · ",k>0&&e.jsxs("span",{className:"text-amber-600 font-bold",children:[k," ",d("scanResult.unreferenced")]})]})})()]}),y&&e.jsxs("div",{className:"space-y-2 bg-slate-50/80 dark:bg-[#1e2028] rounded-lg p-3 border border-slate-200 dark:border-slate-700",children:[e.jsxs("div",{className:"flex items-center justify-end gap-1.5",children:[e.jsx("button",{onClick:()=>{const w=D.map(k=>ri(k));p(s,{headers:w})},className:"text-[9px] px-2 py-0.5 bg-slate-200 text-slate-600 rounded hover:bg-slate-300 font-bold",title:d("scanResultCard.formatHeaders"),children:d("scanResult.formatHeaders")}),D.some(w=>Jt(w,S)==="unused")&&e.jsx("button",{onClick:()=>{const w=D.filter(k=>Jt(k,S)!=="unused");p(s,{headers:w})},className:"text-[9px] px-2 py-0.5 bg-amber-100 text-amber-700 rounded hover:bg-amber-200 font-bold",title:d("scanResultCard.cleanUnused"),children:d("scanResult.cleanUnused")}),e.jsx("button",{onClick:()=>{const w=[...D,ya(t.language)];p(s,{headers:w})},className:"text-[9px] px-2 py-0.5 bg-green-500 text-white rounded hover:bg-green-600 font-bold",children:d("scanResult.addHeader")})]}),e.jsx("div",{className:"space-y-1",children:D.map((w,k)=>{const I=Jt(w,S);return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${I==="used"?"bg-green-500":I==="unused"?"bg-amber-400":"bg-slate-300"}`,title:d(I==="used"?"scanResult.usedInCode":I==="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 ${I==="unused"?"border-amber-300 text-amber-700 dark:border-amber-700 dark:text-amber-400":"border-slate-200 dark:border-slate-600"}`,value:w,onChange:q=>{const W=[...D];W[k]=q.target.value,p(s,{headers:W})},placeholder:ya(t.language)}),I==="unused"&&e.jsx("span",{className:"text-[8px] text-amber-500 font-bold shrink-0",children:d("scanResult.unreferenced")}),e.jsx("button",{onClick:()=>{const q=D.filter((W,K)=>K!==k);p(s,{headers:q})},className:"px-2 py-1 bg-red-500 text-white rounded hover:bg-red-600 text-[9px] font-bold shrink-0",children:d("scanResult.deleteHeader")})]},k)})})]})]})]}),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(Ke,{size:12}),d("scanResult.cursorDelivery")]}),e.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-2 items-start",children:[e.jsx("span",{className:"text-[10px] font-bold text-emerald-600 uppercase pt-1.5 select-none",children:"Do"}),e.jsx("input",{className:"text-sm text-slate-700 dark:text-slate-300 bg-white/80 dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 rounded-lg px-3 py-1.5 outline-none focus:ring-2 focus:ring-cyan-500/20",value:t.doClause||"",onChange:w=>p(s,{doClause:w.target.value}),placeholder:"English imperative ≤60 tokens, e.g. Use dispatch_once for thread-safe singleton"}),e.jsx("span",{className:"text-[10px] font-bold text-red-500 uppercase pt-1.5 select-none",children:"Don't"}),e.jsx("input",{className:"text-sm text-slate-700 dark:text-slate-300 bg-white/80 dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 rounded-lg px-3 py-1.5 outline-none focus:ring-2 focus:ring-cyan-500/20",value:t.dontClause||"",onChange:w=>p(s,{dontClause:w.target.value}),placeholder:"English constraint (omit 'Don't' prefix), e.g. use @synchronized for singleton"}),e.jsx("span",{className:"text-[10px] font-bold text-amber-600 uppercase pt-1.5 select-none",children:"When"}),e.jsx("input",{className:"text-sm text-slate-700 dark:text-slate-300 bg-white/80 dark:bg-[#252a36] border border-slate-200 dark:border-slate-600 rounded-lg px-3 py-1.5 outline-none focus:ring-2 focus:ring-cyan-500/20",value:t.whenClause||"",onChange:w=>p(s,{whenClause:w.target.value}),placeholder:"When implementing singleton pattern or global shared instance"})]})]}),t.reasoning&&(t.reasoning.confidence!=null||t.reasoning.whyStandard&&!/^Submitted via /i.test(t.reasoning.whyStandard))&&e.jsxs("div",{className:"rounded-xl border border-indigo-100 dark:border-indigo-800/40 bg-indigo-50/40 dark:bg-indigo-900/15 p-3 text-xs space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-indigo-600 font-bold text-[10px]",children:[d("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:d("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:[d("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:d("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:z,onChange:w=>p(s,{description:w.target.value,summary:w.target.value}),placeholder:d("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:d("scanResult.markdown")}),e.jsx("button",{type:"button",onClick:()=>f(!l),className:`flex items-center gap-1 text-[10px] font-bold px-2 py-1 rounded transition-colors ${l?"text-blue-600 hover:text-blue-700 bg-blue-50":"text-slate-500 hover:text-slate-700 hover:bg-slate-100"}`,children:l?e.jsxs(e.Fragment,{children:[e.jsx(pt,{size:H.xs})," ",d("scanResult.done")]}):e.jsxs(e.Fragment,{children:[e.jsx(qs,{size:H.xs})," ",d("common.edit")]})})]}),l?e.jsx("textarea",{rows:Math.max(6,(T||"").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:T,onChange:w=>le("markdown",w.target.value)}):T?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:T}):e.jsx("p",{className:"text-xs text-slate-400 italic py-2",children:d("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:d("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(pt,{size:H.xs})," ",d("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:d("common.edit"),children:[e.jsx(qs,{size:H.xs})," ",d("common.edit")]})]}),a===s?e.jsx("div",{className:"rounded-xl overflow-hidden",children:e.jsx(As,{value:S,onChange:w=>le("pattern",w),language:Ia(t),height:`${Math.min(12,S.split(`
100
+ `).length)*20+16}px`})}):S?e.jsx(ft,{code:S,language:Ia(t),showLineNumbers:!0}):e.jsx("p",{className:"text-xs text-slate-400 italic py-4",children:d("scanResult.noCode")})]}),(()=>{const w=t.candidateId??t.id??`scan-${s}`,k=u[w],I=(k||[]).filter(K=>K.similarity>=.6);if(I.length===0)return null;const q=I.filter(K=>K.similarity>=.85),W=q.length>0;return e.jsxs("div",{className:"space-y-1.5",children:[W&&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:d("scanResult.highDuplicateRisk")}),q.map(K=>e.jsxs("button",{onClick:()=>h(t,K.recipeName,k||[]),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:[K.recipeName.replace(/\.md$/i,"")," ",(K.similarity*100).toFixed(0),"%"]},K.recipeName)),e.jsx("span",{className:"text-[10px] text-red-500",children:d("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:d("scanResult.similarRecipes")}),I.slice(0,5).map(K=>e.jsxs("button",{onClick:()=>h(t,K.recipeName,k||[]),className:`text-[10px] font-bold px-2 py-1 rounded border transition-colors flex items-center gap-1 ${K.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:d("scanResultCard.similarWithClick",{name:K.recipeName,score:(K.similarity*100).toFixed(0)}),children:[e.jsx(hs,{size:H.xs}),K.recipeName.replace(/\.md$/i,"")," ",(K.similarity*100).toFixed(0),"%"]},K.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:i,handleDeleteCandidate:o,onEditRecipe:u,isSavingRecipe:p=!1})=>{const{t:c}=Ae(),x=t.candidate,h=ii(x),g=()=>{const S=[],T=x.content?.pattern||"",z=x.content?.markdown||x.doClause||"";T&&S.push("## Snippet / Code Reference\n\n```"+h+`
101
+ `+T+"\n```"),z&&S.push(`
102
+ ## AI Context / Usage Guide
103
+
104
+ `+z),navigator.clipboard.writeText(S.join(`
105
+ `)||"").then(()=>Z(c("spmCompare.candidateCopied"),{title:c("spmCompare.copied")})).catch(()=>{})},d=()=>{const S=ia(t.recipeContent);navigator.clipboard.writeText(S).then(()=>Z(c("spmCompare.recipeCopied"),{title:c("spmCompare.copied")})).catch(()=>{})},l=async S=>{if(S===t.recipeName)return;const T=t.recipeContents[S];if(T)a({...t,recipeName:S,recipeContent:T});else{let z="";const O=r?.find(G=>G.name===S||G.name.endsWith("/"+S));if(O?.content)z=[O.content.pattern,O.content.markdown].filter(Boolean).join(`
106
+
107
+ `)||"";else try{z=(await ee.getRecipeContentByName(S)).content}catch{return}a({...t,recipeName:S,recipeContent:z,recipeContents:{...t.recipeContents,[S]:z}})}},f=async()=>{if(!(!x.candidateId||!t.targetName||!o)&&window.confirm(c("spmCompare.deleteConfirm")))try{await o(t.targetName,x.candidateId),s()}catch(S){Z(ve(S,c("spmCompare.deleteFailed")),{title:c("spmCompare.deleteFailed"),type:"error"})}},y=()=>{i(x),s()},D=()=>{const S=r?.find(T=>T.name===t.recipeName||T.name.endsWith("/"+t.recipeName));u?.(S||{name:t.recipeName,content:{markdown:t.recipeContent}}),s()};return e.jsxs(we,{open:!0,onClose:s,size:"full",children:[e.jsxs(we.Header,{title:c("spmCompare.compareTitle"),children:[e.jsxs(we.HeaderActions,{children:[x.candidateId&&t.targetName&&e.jsx(Ge,{variant:"danger",size:"sm",onClick:f,children:c("spmCompare.deleteCandidate")}),e.jsxs(Ge,{variant:"ghost",size:"sm",onClick:y,disabled:p,children:[p?e.jsx(Ce,{size:H.xs,className:"animate-spin"}):null,c("spmCompare.auditCandidate")]}),e.jsx(Ge,{variant:"ghost",size:"sm",onClick:D,children:c("spmCompare.editRecipe")})]}),e.jsx(we.CloseButton,{onClose:s})]}),e.jsxs(we.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(S=>e.jsxs("button",{onClick:()=>l(S.recipeName),className:`text-[10px] font-bold px-2 py-1 rounded transition-colors ${t.recipeName===S.recipeName?"bg-emerald-200 text-emerald-800":"bg-[var(--bg-surface)] text-emerald-600 hover:bg-emerald-100 border border-emerald-200"}`,children:[S.recipeName.replace(/\.md$/i,"")," ",(S.similarity*100).toFixed(0),"%"]},S.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(Ot,{size:H.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"}),x.content?.pattern?e.jsx(ft,{code:x.content?.pattern||"",language:h,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?.markdown||x.doClause?e.jsx(Ct,{content:x.content?.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:d,className:"p-1 hover:bg-emerald-100 rounded text-emerald-500 shrink-0",title:c("spmCompare.copyRecipe"),children:e.jsx(Ot,{size:H.xs})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e.jsx(Ct,{content:t.recipeContent,stripFrontmatter:!0})})]})]})]})]})},Ta={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"},Ea={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:i,scanFileList:o,scanResults:u,guardAudit:p,handleScanTarget:c,handleScanProject:x,handleUpdateScanResult:h,handleSaveExtracted:g,handlePromoteToCandidate:d,handleDeleteCandidate:l,onEditRecipe:f,isShellTarget:y,recipes:D=[],isSavingRecipe:S=!1,handleRefreshProject:T,onAddCustomFolder:z,onRemoveCustomFolder:O})=>{const{t:G}=Ae(),[le,w]=n.useState(null),[k,I]=n.useState(null),[q,W]=n.useState({}),[,K]=n.useState(null),[C,v]=n.useState(null),[_,ae]=n.useState(!1),[Q]=n.useState(),[me]=n.useState(),Se=n.useRef(new Set),ye=n.useRef([]),[j,N]=n.useState([]),[P,V]=n.useState(!1),ne=n.useRef(!1),ue=3,[pe,Ne]=n.useState("modules"),De=n.useRef(!1),ke=n.useMemo(()=>s.filter(L=>!y(L.name)).length,[s,y]);n.useEffect(()=>{De.current||t.length!==0&&(De.current=!0,ke<ue?Ne("folders"):Ne("modules"))},[t.length,ke]),n.useEffect(()=>{pe!=="folders"||ne.current||(ne.current=!0,V(!0),ee.browseDirectories("",3).then(L=>{N(L)}).catch(()=>{N([])}).finally(()=>{V(!1)}))},[pe]);const Me=n.useCallback(L=>{const oe={name:L.name,packageName:L.name,packagePath:L.path,targetDir:L.path,path:L.path,type:"directory",language:L.language||"unknown",discovererId:"folder-scan",discovererName:G("moduleExplorer.discovererFolderScan"),info:{source:"manual-folder-scan",originalPath:L.path},isVirtual:!0};z?.(oe),c(oe),Ne("modules")},[c,z,G]),M=n.useCallback(async(L,oe)=>{if(!Se.current.has(L)){Se.current.add(L),K(L);try{const be=oe.candidateId&&oe.targetName?{targetName:oe.targetName,candidateId:oe.candidateId}:{candidate:oe.candidate||{}},Te=await ee.getCandidateSimilarityEx(be);W(ce=>({...ce,[L]:Te.similar||[]}))}catch{W(Te=>({...Te,[L]:[]}))}finally{K(null)}}},[]),A=n.useCallback(async(L,oe,be=[])=>{const Te=L.candidateTargetName||"",ce=oe.replace(/\.md$/i,"");let ge="";const Ee=D?.find(U=>U.name===ce||U.name.endsWith("/"+ce));if(Ee?.content)ge=[Ee.content.pattern,Ee.content.markdown].filter(Boolean).join(`
108
+
109
+ `)||"";else try{ge=(await ee.getRecipeContentByName(ce)).content}catch(U){const m=na(U),b=ve(U);m===404?Z(G("moduleExplorer.recipeNotExist",{name:ce}),{title:G("moduleExplorer.recipeNotExistTitle"),type:"error"}):Z(b,{title:G("moduleExplorer.loadRecipeFailed"),type:"error"});return}const J={[ce]:ge};v({candidate:L,targetName:Te,recipeName:ce,recipeContent:ge,similarList:be.slice(0,3),recipeContents:J})},[D]);return n.useEffect(()=>{const L=u.map((ce,ge)=>ce.candidateId??`scan-${ge}`),oe=ye.current;(L.length!==oe.length||L.some((ce,ge)=>ce!==oe[ge]))&&(Se.current.clear(),ye.current=L);const Te=setTimeout(()=>{u.forEach((ce,ge)=>{const Ee=ce.candidateId??ce.id??`scan-${ge}`;ce.candidateId&&ce.candidateTargetName?M(Ee,{targetName:ce.candidateTargetName,candidateId:ce.candidateId}):M(Ee,{candidate:{title:ce.title,summary:ce.description||"",code:ce.content?.pattern||"",usageGuide:ce.content?.markdown||""}})})},800);return()=>clearTimeout(Te)},[u,M]),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:()=>Ne("modules"),className:`text-[11px] px-2.5 py-1.5 rounded-md font-bold transition-all ${pe==="modules"?"bg-[var(--bg-surface)] text-blue-700 shadow-sm":"text-[var(--fg-secondary)] hover:text-[var(--fg-primary)]"}`,children:G("moduleExplorer.modulesTabLabel",{count:ke})}),e.jsx("button",{onClick:()=>Ne("folders"),className:`text-[11px] px-2.5 py-1.5 rounded-md font-bold transition-all ${pe==="folders"?"bg-[var(--bg-surface)] text-blue-700 shadow-sm":"text-[var(--fg-secondary)] hover:text-[var(--fg-primary)]"}`,children:G("moduleExplorer.foldersTabLabel")})]}),T&&e.jsx("button",{onClick:T,title:G("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(mt,{size:H.md})})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto p-2 space-y-1",children:pe==="modules"?e.jsx(e.Fragment,{children:s.map(L=>{const oe=y(L.name),be=a===L.name,Te=L.isVirtual||L.discovererId==="folder-scan",ce=L.language||"",ge=Ta[ce]||"bg-[var(--bg-subtle)] text-[var(--fg-secondary)] border-[var(--border-default)]",Ee=L.packageName&&L.packageName!==L.name?L.packageName:L.discovererName||"";return e.jsxs("button",{onClick:()=>c(L),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)]"} ${be?"bg-blue-50 border-blue-200 ring-1 ring-blue-200":"bg-[var(--bg-surface)] border-transparent"} ${oe?"opacity-90":""}`,children:[e.jsxs("div",{className:`flex flex-col max-w-[85%] ${oe?"opacity-60":""}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[!oe&&e.jsx("div",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${Te?"bg-emerald-500":"bg-blue-600"}`}),e.jsx("span",{className:`text-sm truncate ${oe?"font-medium":"font-bold"} ${be?"text-blue-700":""}`,children:L.name}),ce&&!oe&&!Te&&ce!=="unknown"&&e.jsx("span",{className:`text-[9px] font-bold px-1.5 py-0.5 rounded border shrink-0 ${ge}`,children:Ea[ce]||ce.toUpperCase()})]}),Ee&&e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] truncate pl-3",children:Ee})]}),oe?e.jsx("span",{className:"text-[9px] font-bold text-[var(--fg-muted)] border border-[var(--border-default)] px-1 rounded",children:"SHELL"}):Te&&O?e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[e.jsx(Ke,{size:H.sm,className:`${be?"text-blue-500 opacity-100":"text-blue-500 opacity-0 group-hover:opacity-100"} transition-opacity`}),e.jsx("button",{onClick:J=>{J.stopPropagation(),O(L.path||"")},title:G("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(et,{size:12})})]}):e.jsx(Ke,{size:H.sm,className:`shrink-0 ${be?"text-blue-500 opacity-100":"text-blue-500 opacity-0 group-hover:opacity-100"} transition-opacity`})]},`${L.discovererId||"default"}::${L.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(Ce,{size:H.lg,className:"animate-spin mb-3 opacity-40"}),e.jsx("p",{className:"text-xs",children:G("moduleExplorer.scanningDirs")})]}):j.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-[var(--fg-muted)]",children:[e.jsx(jt,{size:H.xl,className:"mb-3 opacity-20"}),e.jsx("p",{className:"text-xs text-center px-4 leading-relaxed",children:G("moduleExplorer.noDirs")})]}):j.map(L=>{const oe=Ta[L.language]||"bg-[var(--bg-subtle)] text-[var(--fg-secondary)] border-[var(--border-default)]";return e.jsxs("button",{onClick:()=>Me(L),disabled:r||!L.hasSourceFiles,className:`w-full text-left p-2.5 rounded-lg flex items-center gap-2.5 transition-all border border-transparent
110
+ ${L.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:`${L.depth*14+10}px`},children:[e.jsx(jt,{size:H.sm,className:L.hasSourceFiles?"text-emerald-500 shrink-0":"text-[var(--fg-muted)] shrink-0"}),e.jsx("span",{className:"text-sm font-medium flex-1 truncate",children:L.name}),L.hasSourceFiles&&L.language!=="unknown"&&e.jsx("span",{className:`text-[9px] font-bold px-1.5 py-0.5 rounded border shrink-0 ${oe}`,children:Ea[L.language]||L.language.toUpperCase()}),L.hasSourceFiles&&e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] shrink-0",children:G("moduleExplorer.sourceFileCount",{count:L.sourceFileCount})}),e.jsx(Qe,{size:12,className:"text-[var(--fg-muted)] shrink-0"})]},L.path)}),e.jsx("div",{className:"px-3 py-2 text-[10px] text-[var(--fg-muted)] text-center",children:G("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(rt,{size:H.md,className:"text-indigo-500"}),e.jsx("span",{children:G("moduleExplorer.fullProjectResults")}),u.length>0&&e.jsx("span",{className:"text-[10px] font-bold px-2 py-0.5 rounded-full bg-indigo-100 text-indigo-700 border border-indigo-200",children:"PROJECT"})]}):a?e.jsxs(e.Fragment,{children:[e.jsx(Ke,{size:H.md,className:"text-blue-500"}),e.jsx("span",{children:G("moduleExplorer.moduleLabel",{name:a})}),u.length>0&&e.jsx("span",{className:"text-[10px] font-bold px-2 py-0.5 rounded-full bg-blue-100 text-blue-700 border border-blue-200",children:"MODULE"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Et,{size:H.md,className:"text-[var(--fg-muted)]"}),e.jsx("span",{children:G("moduleExplorer.reviewResults")})]}),u.length>0&&e.jsxs("span",{className:"text-[var(--fg-muted)] font-normal text-xs ml-1",children:["(",G("moduleExplorer.resultsCount",{count:u.length}),u[0]?.trigger?G("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(as,{size:H.xxl,className:"absolute inset-0 m-auto text-blue-600 animate-pulse"})]}),e.jsx("p",{className:"font-bold text-lg animate-pulse mb-1",children:a==="__project__"?G("moduleExplorer.fullProjectScanning"):G("moduleExplorer.moduleScanLabel",{name:a||"..."})}),e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] mb-4",children:i.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(i.total?i.current/i.total*100:0,98)}%`}})}),e.jsx("p",{className:"text-xs text-[var(--fg-muted)] mt-3",children:i.total?`${Math.round(i.current/i.total*100)}%`:"0%"})]}),!r&&u.length===0&&e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-[var(--fg-muted)] text-center",children:[e.jsx(js,{size:H.xxxl,className:"mb-4 opacity-20"}),e.jsx("p",{className:"font-medium text-[var(--fg-secondary)]",children:G("moduleExplorer.knowledgeExtract")}),e.jsx("p",{className:"text-xs mt-2 max-w-sm leading-relaxed",children:G("moduleExplorer.knowledgeExtractHint")})]}),!r&&a==="__project__"&&p?.summary&&e.jsxs("div",{className:`rounded-xl border p-4 ${p.summary.totalViolations>0?"border-amber-200 bg-amber-50":"border-emerald-200 bg-emerald-50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(at,{size:H.md,className:p.summary.totalViolations>0?"text-amber-600":"text-emerald-600"}),e.jsx("span",{className:"text-sm font-bold text-[var(--fg-primary)]",children:G("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:G("moduleExplorer.auditedFiles")}),e.jsx("span",{className:"font-bold text-[var(--fg-primary)]",children:p.summary.totalFiles})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[var(--fg-secondary)]",children:G("moduleExplorer.totalViolationsLabel")}),e.jsx("span",{className:`font-bold ${p.summary.totalViolations>0?"text-amber-700":"text-emerald-700"}`,children:p.summary.totalViolations})]}),p.summary.errors>0&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(It,{size:H.sm,className:"text-red-500"}),e.jsx("span",{className:"font-bold text-red-700",children:G("moduleExplorer.errorsCount",{count:p.summary.errors})})]}),p.summary.warnings>0&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(It,{size:H.sm,className:"text-amber-500"}),e.jsx("span",{className:"font-bold text-amber-700",children:G("moduleExplorer.warningsCount",{count:p.summary.warnings})})]})]})]}),u.map((L,oe)=>e.jsx(oi,{res:L,index:oe,editingCodeIndex:le,setEditingCodeIndex:w,expandedEditIndex:k,setExpandedEditIndex:I,similarityMap:q,handleUpdateScanResult:h,handleSaveExtracted:g,handlePromoteToCandidate:d,openCompare:A,isSavingRecipe:S},oe))]})]}),C&&e.jsx(ci,{data:C,onClose:()=>v(null),onDataChange:v,recipes:D,handleSaveExtracted:g,handleDeleteCandidate:l,onEditRecipe:f,isSavingRecipe:S}),e.jsx(si,{isOpen:_,onClose:()=>ae(!1),targetName:me,currentFile:Q,language:s.find(L=>L.name===a)?.language||"unknown",onSelectRecipe:L=>{}})]})},ui=72,pi=52,ys=24,ts=40,$r=36,Tt=140,es=40,ss=8;function mi(t,s){const a=new Set(t.map(p=>p.id)),r=new Map;for(const p of s)!a.has(p.from)||!a.has(p.to)||(r.has(p.from)||r.set(p.from,[]),r.get(p.from).push(p.to));const i=new Map,o=new Set;function u(p){if(i.has(p))return i.get(p);if(o.has(p))return 0;o.add(p);const c=r.get(p);if(!c||c.length===0)return i.set(p,0),o.delete(p),0;const x=1+Math.max(...c.map(u));return i.set(p,x),o.delete(p),x}return t.forEach(p=>u(p.id)),i}function xi(t){return Math.ceil(t/ss)}function gi(t,s){const a=mi(t,s),r=new Map;for(const g of t){const d=a.get(g.id)??0;r.has(d)||r.set(d,[]),r.get(d).push(g.id)}const i=[...new Set(a.values())].sort((g,d)=>g-d),o=[...i].reverse(),u=new Map,p=new Map,c=Math.min(ss,Math.max(...i.map(g=>(r.get(g)??[]).length),1)),x=(c-1)*ys+c*Tt;let h=ts;return o.forEach(g=>{const d=r.get(g)??[],l=xi(d.length),f=h;for(let D=0;D<l;D++){const S=d.slice(D*ss,(D+1)*ss),T=(S.length-1)*ys+S.length*Tt,z=(x-T)/2;S.forEach((O,G)=>{const le=ts+$r+z+G*(Tt+ys)+Tt/2,w=h+es/2;u.set(O,{x:le,y:w})}),h+=D<l-1?pi:ui}const y=h-f;p.set(g,{y:f,h:y})}),{positions:u,tiers:a,tierOrder:i,tierYRanges:p}}const hi=()=>{const{t}=Ae(),{isDark:s}=Is(),[a,r]=n.useState(null),[i,o]=n.useState(!0),[u,p]=n.useState(null),[c,x]=n.useState(null),[h,g]=n.useState("package"),[d,l]=n.useState("all"),f=async()=>{o(!0),p(null);try{const j=await ee.getDepGraph(h);r({nodes:Array.isArray(j?.nodes)?j.nodes:[],edges:Array.isArray(j?.edges)?j.edges:[],projectRoot:j?.projectRoot??null,generatedAt:j?.generatedAt})}catch(j){p(ve(j,"Failed to load dependency graph"))}finally{o(!1)}};n.useEffect(()=>{f()},[h]);const y=Array.isArray(a?.nodes)?a.nodes:[],D=Array.isArray(a?.edges)?a.edges:[],S=y.some(j=>j.type==="internal"||j.type==="external"),T=n.useMemo(()=>!S||d==="all"?y:d==="internal"?y.filter(j=>j.type!=="external"):y.filter(j=>j.type!=="internal"),[y,d,S]),z=n.useMemo(()=>new Set(T.map(j=>j.id)),[T]),O=n.useMemo(()=>D.filter(j=>z.has(j.from)||z.has(j.to)),[D,z]),{positions:G,tiers:le,tierOrder:w,tierYRanges:k}=n.useMemo(()=>gi(T,O),[T,O]),I=n.useMemo(()=>{const j=new Map;return T.forEach(N=>{const P=le.get(N.id)??0;j.has(P)||j.set(P,[]),j.get(P).push(N.id)}),j},[T,le]),q=n.useMemo(()=>[...w].reverse(),[w]),{dependsOn:W,dependedBy:K}=n.useMemo(()=>{const j=new Map,N=new Map;return O.forEach(P=>{j.has(P.from)||j.set(P.from,[]),j.get(P.from).push(P.to),N.has(P.to)||N.set(P.to,[]),N.get(P.to).push(P.from)}),{dependsOn:j,dependedBy:N}},[O]),C=Math.min(ss,Math.max(...w.map(j=>(I.get(j)??[]).length),1)),_=(C-1)*ys+C*Tt+$r*2,ae=Math.max(600,ts*2+_),Q=Math.max(...[...G.values()].map(j=>j.y),0),me=Math.max(420,Q+es/2+ts+20),Se=s?[{bg:"rgba(59, 130, 246, 0.14)",border:"rgba(59, 130, 246, 0.40)",text:"rgb(147 197 253)"},{bg:"rgba(34, 197, 94, 0.14)",border:"rgba(34, 197, 94, 0.40)",text:"rgb(134 239 172)"},{bg:"rgba(234, 179, 8, 0.14)",border:"rgba(234, 179, 8, 0.40)",text:"rgb(253 224 71)"},{bg:"rgba(249, 115, 22, 0.14)",border:"rgba(249, 115, 22, 0.40)",text:"rgb(253 186 116)"},{bg:"rgba(139, 92, 246, 0.14)",border:"rgba(139, 92, 246, 0.40)",text:"rgb(196 181 253)"}]:[{bg:"rgb(239 246 255)",border:"rgb(147 197 253)",text:"rgb(30 64 175)"},{bg:"rgb(240 253 244)",border:"rgb(134 239 172)",text:"rgb(22 101 52)"},{bg:"rgb(254 249 195)",border:"rgb(253 224 71)",text:"rgb(113 63 18)"},{bg:"rgb(254 243 199)",border:"rgb(253 186 116)",text:"rgb(154 52 18)"},{bg:"rgb(243 232 255)",border:"rgb(216 180 254)",text:"rgb(91 33 182)"}],ye=j=>Se[Math.min(j,Se.length-1)]??Se[0];return i?e.jsx("div",{className:"flex items-center justify-center min-h-[320px]",children:e.jsx("div",{className:"animate-spin rounded-full h-10 w-10 border-2 border-blue-600 border-t-transparent"})}):u?e.jsxs("div",{className:"rounded-xl border border-red-200 bg-red-50 p-6 text-red-700 shadow-sm",children:[e.jsx("p",{children:u}),e.jsx("button",{type:"button",onClick: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||y.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(rt,{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:[S&&e.jsx("div",{className:"flex items-center border border-[var(--border-default)] rounded-lg overflow-hidden text-xs",children:["all","internal","external"].map(j=>e.jsx("button",{type:"button",onClick:()=>l(j),className:`px-3 py-1.5 font-medium transition-colors ${d===j?"bg-blue-600 text-white":"bg-[var(--bg-surface)] text-[var(--fg-secondary)] hover:bg-[var(--bg-subtle)]"}`,children:t(j==="all"?"depGraph.filterAll":j==="internal"?"depGraph.filterInternal":"depGraph.filterExternal")},j))}),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(mt,{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(rt,{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:T.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:[S&&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:me,viewBox:`0 0 ${ae} ${me}`,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"})})}),q.map((j,N)=>{const P=ye(N),V=k.get(j);return V?e.jsx("rect",{x:ts,y:V.y-es/2-4,width:_,height:V.h+8,rx:8,fill:P.bg,stroke:P.border,strokeWidth:s?1.5:1,opacity:s?1:.6},j):null}),T.map(j=>{const N=G.get(j.id);if(!N)return null;const P=le.get(j.id)??0,V=ye(q.indexOf(P)),ne=j.label.length>14?j.label.slice(0,13)+"…":j.label,ue=c===j.id,pe=c?(W.get(c)??[]).includes(j.id):!1,Ne=c?(K.get(c)??[]).includes(j.id):!1,De=c&&!ue&&!pe&&!Ne,ke=j.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"}:j.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:V.border,text:V.text,badge:""}:{fill:"white",stroke:V.border,text:V.text,badge:""},Me=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}:pe?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}:Ne?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:ke.fill,stroke:ke.stroke,text:ke.text,strokeWidth:2,opacity:j.indirect?.55:1};return e.jsxs("g",{style:{cursor:"pointer",opacity:Me.opacity},onClick:()=>x(ue?null:j.id),children:[e.jsx("rect",{x:N.x-Tt/2,y:N.y-es/2,width:Tt,height:es,rx:10,ry:10,fill:Me.fill,stroke:Me.stroke,strokeWidth:Me.strokeWidth,filter:De?void 0:"url(#nodeShadow)",strokeDasharray:j.type==="external"?"4 2":void 0}),e.jsx("text",{x:N.x,y:N.y+(ke.badge?-2:0),textAnchor:"middle",dominantBaseline:"middle",fontSize:"12",fontWeight:"600",fill:Me.text,pointerEvents:"none",children:ne}),ke.badge&&e.jsx("text",{x:N.x,y:N.y+12,textAnchor:"middle",dominantBaseline:"middle",fontSize:"8",fontWeight:"500",fill:ke.text,opacity:.6,pointerEvents:"none",children:ke.badge})]},j.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:(W.get(c)??[]).length===0?e.jsx("li",{className:"text-[var(--fg-muted)]",children:t("depGraph.none")}):(W.get(c)??[]).map(j=>e.jsxs("li",{children:["→ ",j]},j))})]}),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:(K.get(c)??[]).length===0?e.jsx("li",{className:"text-[var(--fg-muted)]",children:t("depGraph.none")}):(K.get(c)??[]).map(j=>e.jsxs("li",{children:["← ",j]},j))})]})]})]})]}),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")," (",T.length,")"]}),e.jsx("ul",{className:"text-sm space-y-3 max-h-[280px] overflow-y-auto pr-1",children:T.map(j=>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:j.label||j.id}),j.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")}),j.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")}),j.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")}),j.packageDir&&e.jsxs("span",{className:"text-[var(--fg-secondary)] text-xs",children:["· ",j.packageDir]})]}),j.fullPath&&e.jsx("div",{className:"mt-1 text-[var(--fg-muted)] text-xs truncate",children:j.fullPath}),j.targets&&j.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:j.targets.join(", ")})]})]},j.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((j,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:j.from}),e.jsx("span",{className:"text-[var(--fg-muted)] shrink-0",children:"→"}),e.jsx("span",{className:"font-semibold text-[var(--fg-primary)]",children:j.to})]},`${j.from}-${j.to}-${N}`))})]}),h==="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}=Ae(),[a,r]=n.useState({}),[i,o]=n.useState([]),[u,p]=n.useState([]),[c,x]=n.useState(null),[h,g]=n.useState(!0),[d,l]=n.useState(!1),[f,y]=n.useState({ruleId:"",message:"",severity:"warning",pattern:"",languages:[],note:"",dimension:""}),[D,S]=n.useState(!1),[T,z]=n.useState(""),O=async()=>{try{const[N,P]=await Promise.all([ee.getGuardRules(),ee.getGuardViolations()]);r(N?.rules||{}),p(N?.projectLanguages||[]),o(P?.runs||[])}catch{r({}),o([])}finally{g(!1)}};n.useEffect(()=>{O()},[]);const G=async()=>{if(window.confirm(s("guard.clearConfirm")))try{await ee.clearViolations(),O(),t?.()}catch(N){Z(ve(N,s("common.operationFailed")),{title:s("common.operationFailed"),type:"error"})}},le=N=>{y(P=>({...P,languages:P.languages.includes(N)?P.languages.filter(V=>V!==N):[...P.languages,N]}))},w=async N=>{if(N.preventDefault(),z(""),!f.ruleId.trim()||!f.message.trim()||!f.pattern.trim()||f.languages.length===0){z(s("guard.addRuleValidation"));return}S(!0);try{await ee.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}:{}}),y({ruleId:"",message:"",severity:"warning",pattern:"",languages:[],note:"",dimension:""}),l(!1),O(),t?.()}catch(P){z(ve(P,s("common.saveFailed")))}finally{S(!1)}},I=n.useMemo(()=>{const N=Object.entries(a);return u.length===0?N:N.filter(([,P])=>!P.languages||P.languages.length===0?!0:P.languages.some(V=>u.includes(V)))},[a,u]),q=i.reduce((N,P)=>N+P.violations.length,0),[W,K]=n.useState("all"),[C,v]=n.useState("all"),_=n.useMemo(()=>{const N=new Set;for(const[,V]of I)(V.languages||[]).forEach(ne=>N.add(ne));const P=$t.filter(V=>N.has(V.id)).map(V=>V.id);for(const V of N)P.includes(V)||P.push(V);return P},[I]),ae=N=>$t.find(P=>P.id===N)?.label||N,Q=n.useMemo(()=>{const N={error:0,warning:0,info:0};for(const[,P]of I){const V=P.severity;N[V]!==void 0&&N[V]++}return N},[I]),me=N=>{const P={safety:s("guard.categorySafety"),correctness:s("guard.categoryCorrectness"),performance:s("guard.categoryPerformance"),style:s("guard.categoryStyle")};return N?P[N]||N:"—"},Se=(N,P)=>{const V=`guardRuleMessages.${N}`,ne=s(V);return ne!==V?ne:P},ye=(N,P)=>{if(!P)return P;const V=`guardRuleFixSuggestions.${N}`,ne=s(V);return ne!==V?ne:P},j=n.useMemo(()=>I.filter(([,N])=>!(W!=="all"&&!(N.languages||[]).includes(W)||C!=="all"&&N.severity!==C)),[I,W,C]);return h?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(at,{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"),u.length>0&&e.jsxs("span",{className:"ml-1.5",children:["· ",s("guard.currentProject"),":",u.map(N=>ae(N)).join(" / ")]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("a",{href:dl,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(_n,{size:14})," ",s("guard.reportIssue")]}),e.jsxs("button",{type:"button",onClick:()=>l(!d),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:[d?e.jsx(Nt,{size:14}):e.jsx(Qe,{size:14}),s("guard.addRule")]}),i.length>0&&e.jsxs("button",{type:"button",onClick:G,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(et,{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(at,{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:I.length})]})]}),q>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(It,{size:14,className:"text-amber-400"}),e.jsx("span",{className:"text-amber-600",children:s("guard.totalViolations",{count:q})})]})]})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto pr-1 pb-6",children:[d&&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=>y(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(Ze,{id:"rule-severity",name:"severity",value:f.severity,onChange:N=>y(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=>y(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=>y(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:(u.length>0?$t.filter(N=>u.includes(N.id)):$t.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:()=>le(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(Ze,{id:"rule-dimension",name:"dimension",value:f.dimension,onChange:N=>y(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=>y(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:D,className:"px-4 py-2 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700 disabled:opacity-50",children:s(D?"common.saving":"common.confirm")}),e.jsx("button",{type:"button",onClick:()=>l(!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(hr,{size:14,className:"text-[var(--fg-muted)]"}),s("guard.tableHeaders.rule"),e.jsxs("span",{className:"text-[var(--fg-muted)] font-normal",children:["(",j.length,"/",I.length,")"]})]}),e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:e.jsxs("div",{className:"flex items-center gap-1 text-xs",children:[e.jsx("button",{onClick:()=>v("all"),className:`px-2 py-1 rounded-md border transition-all ${C==="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:()=>v("error"),className:`px-2 py-1 rounded-md border transition-all flex items-center gap-1 ${C==="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(Kt,{size:12})," error ",e.jsxs("span",{className:"opacity-70",children:["(",Q.error,")"]})]}),e.jsxs("button",{onClick:()=>v("warning"),className:`px-2 py-1 rounded-md border transition-all flex items-center gap-1 ${C==="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(It,{size:12})," warning ",e.jsxs("span",{className:"opacity-70",children:["(",Q.warning,")"]})]}),e.jsxs("button",{onClick:()=>v("info"),className:`px-2 py-1 rounded-md border transition-all flex items-center gap-1 ${C==="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(Us,{size:12})," info ",e.jsxs("span",{className:"opacity-70",children:["(",Q.info,")"]})]})]})})]}),e.jsxs("div",{className:"flex items-center gap-1.5 mb-3 flex-wrap",children:[e.jsx("button",{onClick:()=>K("all"),className:`px-2.5 py-1 rounded-full text-xs font-medium border transition-all ${W==="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")}),_.map(N=>{const P=I.filter(([,V])=>(V.languages||[]).includes(N)).length;return e.jsxs("button",{onClick:()=>K(W===N?"all":N),className:`px-2.5 py-1 rounded-full text-xs font-medium border transition-all ${W===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:[ae(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(Us,{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:j.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:5,className:"py-4 px-4 text-[var(--fg-secondary)] text-center",children:I.length===0?s("common.noData"):s("guard.noMatchingRules")})}):j.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:[Se(N,P.message),P.fixSuggestion&&e.jsx("span",{className:"ml-1.5 text-xs text-emerald-600",title:ye(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(V=>e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-indigo-50 text-indigo-600 border border-indigo-100 font-medium",children:ae(V)},V))})}),e.jsx("td",{className:"py-2 px-4 text-xs text-[var(--fg-secondary)]",children:me(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:i.length,count:q})}),i.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:i.map(N=>{const P=c===N.id,V=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(Nt,{size:H.md}):e.jsx(Qe,{size:H.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()}),V?e.jsxs("span",{className:"ml-auto flex items-center gap-1 text-amber-600 text-xs font-medium",children:[e.jsx(It,{size:H.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((ne,ue)=>{const pe=a[ne.ruleId];return e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[ne.severity==="error"?e.jsx(Kt,{size:H.md,className:"text-red-500 shrink-0 mt-0.5"}):e.jsx(It,{size:H.md,className:"text-amber-500 shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsxs("div",{children:[e.jsxs("span",{className:"font-mono text-xs text-[var(--fg-secondary)]",children:["[",ne.ruleId,"] ",ne.filePath?`${ne.filePath}:${ne.line}`:`L${ne.line}`]}),ne.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:ne.dimension==="file"?s("guard.dimFile"):ne.dimension==="target"?s("guard.dimTarget"):s("guard.dimProject")}),e.jsx("span",{className:"text-[var(--fg-primary)] ml-2",children:Se(ne.ruleId,ne.message)})]}),ne.snippet&&e.jsx("pre",{className:"text-xs text-[var(--fg-secondary)] bg-[var(--bg-subtle)] p-2 rounded overflow-x-auto",children:ne.snippet}),pe&&(pe.rationale||pe.fixSuggestions?.length||pe.sourceRecipe||pe.note)&&e.jsxs("div",{className:"mt-1 rounded-lg border border-blue-100 bg-blue-50/50 p-2.5 text-xs space-y-1.5",children:[pe.rationale&&e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx(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:pe.rationale})]})]}),pe.fixSuggestions&&pe.fixSuggestions.length>0&&e.jsxs("div",{className:"flex items-start gap-1.5",children:[e.jsx(fr,{size:12,className:"text-emerald-500 shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsxs("span",{className:"font-bold text-emerald-700",children:[s("guard.fixSuggestion"),":"]}),e.jsx("ul",{className:"mt-0.5 space-y-0.5 text-[var(--fg-secondary)]",children:pe.fixSuggestions.map((Ne,De)=>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:Ne}),e.jsx("button",{className:"ml-1 text-blue-500 hover:text-blue-700",title:s("guard.copyFixSuggestion"),onClick:()=>navigator.clipboard.writeText(Ne).catch(()=>{}),children:"⎘"})]},De))})]})]}),pe.sourceRecipe&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ta,{size:12,className:"text-indigo-500 shrink-0"}),e.jsxs("span",{className:"font-bold text-indigo-700",children:[s("guard.sourceRecipe"),":"]}),e.jsx("span",{className:"text-indigo-600 font-mono",children:pe.sourceRecipe})]}),!pe.rationale&&pe.note&&e.jsxs("div",{className:"text-[var(--fg-secondary)] italic",children:[s("guard.noteLabel"),":",pe.note]})]})]})]},ue)})})})]},N.id)})})]})]})]})},Pa=()=>Math.random().toString(36).substring(2,10),bi=({d:t})=>{const{t:s}=Ae();return e.jsxs("div",{className:"border border-[var(--border-default)] rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-2.5 py-1 bg-[var(--bg-subtle)] border-b border-[var(--border-default)] flex items-center gap-1.5",children:[e.jsx(dr,{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),i=new Date().getTime()-a.getTime(),o=Math.floor(i/6e4);if(o<1)return s("aiChat.timeJustNow");if(o<60)return s("aiChat.timeMinutesAgo",{n:o});const u=Math.floor(o/60);if(u<24)return s("aiChat.timeHoursAgo",{n:u});const p=Math.floor(u/24);return p<7?s("aiChat.timeDaysAgo",{n:p}):a.toLocaleDateString("zh-CN",{month:"short",day:"numeric"})}const yi=()=>{const{t,lang:s}=Ae(),{close:a,isOpen:r}=ns(),[i,o]=n.useState([]),[u,p]=n.useState(!1),c=n.useRef([]),x=n.useRef(null),h=Cr(),{topics:g,activeTopicId:d,activeTopic:l,createTopic:f,deleteTopic:y,saveTopic:D,switchTopic:S}=h,T=n.useRef(null),z=n.useRef(null),[O,G]=n.useState(""),[le,w]=n.useState(!1),k=n.useRef(!1);n.useEffect(()=>{r&&a()},[]),n.useEffect(()=>{T.current?.scrollIntoView({behavior:"smooth"})},[i,u]),n.useEffect(()=>{setTimeout(()=>z.current?.focus(),200)},[]),n.useEffect(()=>{k.current||d&&i.length>0&&D(d,i)},[i,d,D]);const I=n.useCallback(()=>{k.current=!0,f(),o([]),c.current=[],setTimeout(()=>{k.current=!1},50)},[f,o,c]),q=n.useCallback(v=>{if(v===d)return;k.current=!0,S(v);const _=h.getTopic(v);_?(o(_.messages),c.current=_.messages.filter(ae=>ae.role==="user"||ae.role==="assistant").map(ae=>({role:ae.role==="assistant"?"model":ae.role,content:ae.content}))):(o([]),c.current=[]),setTimeout(()=>{k.current=!1},50)},[d,S,h,o,c]),W=n.useCallback((v,_)=>{v.stopPropagation(),y(_),_===d&&(k.current=!0,o([]),c.current=[],setTimeout(()=>{k.current=!1},50))},[y,d,o,c]),K=n.useCallback(async()=>{const v=O.trim();if(!v||u)return;let _=d;_||(k.current=!0,_=f(),setTimeout(()=>{k.current=!1},50)),G(""),o(me=>[...me,{id:Pa(),role:"user",content:v,timestamp:Date.now()}]),p(!0);const ae=Pa();o(me=>[...me,{id:ae,role:"assistant",content:`🔄 ${t("aiChat.thinking")}`,timestamp:Date.now()}]),c.current.push({role:"user",content:v});const Q=new AbortController;x.current=Q;try{const{onEvent:me,getState:Se}=Sr(ae,o,t),j=(await ee.chatStream(v,c.current,N=>{me(N)},Q.signal,s)).text||Se().answerText;c.current.push({role:"model",content:j}),o(N=>N.map(P=>P.id===ae?{...P,content:j}:P))}catch(me){if(Cs(me)){const Se=t("aiChat.cancelled");o(ye=>ye.map(j=>j.id===ae?{...j,content:Se}:j))}else o(Se=>Se.map(ye=>ye.id===ae?{...ye,content:t("aiChat.requestFailed",{error:ve(me)})}:ye))}finally{x.current=null}p(!1)},[O,u,d,f,t,s]),C=n.useCallback(v=>{v.key==="Enter"&&!v.shiftKey&&(v.preventDefault(),K())},[K]);return e.jsxs("div",{className:"flex-1 flex h-full bg-[var(--bg-subtle)]",children:[e.jsx("div",{className:`${le?"w-10":"w-64"} shrink-0 bg-[var(--bg-surface)] border-r border-[var(--border-default)] flex flex-col transition-all duration-200`,children:le?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(Qe,{size:16})}),e.jsx("button",{onClick:I,className:"p-1.5 hover:bg-[var(--accent-subtle)] rounded-lg transition-colors text-blue-500",title:t("aiChat.newTopic"),children:e.jsx(gt,{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:I,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(gt,{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(ea,{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(wt,{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(v=>{const _=v.id===d,ae=v.messages.filter(Q=>Q.role==="user").length;return e.jsx("div",{onClick:()=>q(v.id),className:`group mx-1.5 mb-0.5 px-3 py-2 rounded-lg cursor-pointer transition-colors ${_?"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 ${_?"text-blue-700":"text-[var(--fg-primary)]"}`,children:v.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(tt,{size:9}),vi(v.updatedAt,t)]}),ae>0&&e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)]",children:t("aiChat.messageCount",{n:ae})})]})]}),e.jsx("button",{onClick:Q=>W(Q,v.id),className:`p-1 rounded transition-colors shrink-0 ${_?"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(et,{size:12})})]})},v.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(wt,{className:"text-blue-600",size:18})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm font-bold text-[var(--fg-primary)]",children:l?l.title:"AI Chat"}),e.jsx("p",{className:"text-[11px] text-[var(--fg-muted)]",children:t("aiChat.askAnything")})]})]}),i.length>0&&e.jsxs("button",{onClick:I,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(gt,{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:[i.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(He,{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(v=>e.jsx("button",{onClick:()=>{G(v.label),z.current?.focus()},className:"text-xs px-3.5 py-2 rounded-lg bg-[var(--bg-surface)] border border-[var(--border-default)] text-[var(--fg-secondary)] hover:bg-[var(--accent-subtle)] hover:text-blue-700 hover:border-blue-200 transition-colors shadow-sm",children:v.label},v.key))})]}),i.map(v=>e.jsx("div",{className:`flex ${v.role==="user"?"justify-end":"justify-start"}`,children:e.jsxs("div",{className:`max-w-[80%] ${v.role==="user"?"bg-[var(--accent-subtle)] text-[var(--fg-primary)] rounded-2xl rounded-tr-md px-4 py-2.5":v.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:[v.role==="assistant"&&e.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[e.jsx(qt,{size:13,className:"text-blue-500"}),e.jsx("span",{className:"text-[11px] font-bold text-blue-600",children:t("aiChat.aiAssistant")})]}),v.role==="assistant"&&!v.diff?e.jsx(Ct,{content:v.content,className:"text-sm text-[var(--fg-primary)]"}):e.jsx("p",{className:`text-sm leading-relaxed whitespace-pre-wrap ${v.role==="user"?"":"text-[var(--fg-secondary)]"}`,children:v.content}),v.diff&&v.diff.length>0&&e.jsx("div",{className:"space-y-2 mt-2",children:v.diff.map(_=>e.jsx(bi,{d:_},_.field))})]})},v.id)),u&&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(Ce,{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:()=>x.current?.abort(),className:"ml-1 px-1.5 py-0.5 text-[10px] font-bold text-red-500 border border-red-200 rounded hover:bg-red-50 transition-colors",children:t("common.stop")})]})})}),e.jsx("div",{ref:T})]})}),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:z,value:O,onChange:v=>G(v.target.value),onKeyDown:C,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:u}),e.jsx("button",{onClick:K,disabled:!O.trim()||u,className:"self-stretch w-10 flex items-center justify-center rounded-xl bg-gradient-to-r from-blue-500 to-indigo-600 hover:from-blue-600 hover:to-indigo-700 text-white disabled:opacity-40 disabled:cursor-not-allowed transition-all shadow-sm shrink-0",children:e.jsx(Zs,{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,xt={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:"解决"},$s=[{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 Rt(t){return Math.min(Ni,Math.max(wi,ji+t*2))}function La(t,s){return t.length<=s?t:t.substring(0,s-1)+"…"}function Di(t,s,a,r){const i=new Map;for(const h of t)i.set(h.fromId,(i.get(h.fromId)||0)+1),i.set(h.toId,(i.get(h.toId)||0)+1);const o=[...i.keys()],u=[...new Set(o.map(h=>r[h]||"general"))].sort(),p=new Map,c=Math.ceil(Math.sqrt(u.length)),x=400;return u.forEach((h,g)=>{const d=g%c,l=Math.floor(g/c);p.set(h,{x:450+(d-(c-1)/2)*x,y:350+(l-(Math.ceil(u.length/c)-1)/2)*x})}),o.map(h=>{const g=r[h]||"general",d=p.get(g)||{x:450,y:350},l=Math.random()*2*Math.PI,f=40+Math.random()*80;return{id:h,label:s[h]||h,type:a[h]||"recipe",group:g,x:d.x+f*Math.cos(l),y:d.y+f*Math.sin(l),vx:0,vy:0,degree:i.get(h)||1}})}function Ri(t,s,a=200){const r=t.map(u=>({...u})),i=new Map(r.map(u=>[u.id,u]));function o(){const u=new Map;for(const p of r){const c=u.get(p.group);c?(c.x+=p.x,c.y+=p.y,c.count++):u.set(p.group,{x:p.x,y:p.y,count:1})}for(const[,p]of u)p.x/=p.count,p.y/=p.count;return u}for(let u=0;u<a;u++){const p=1-u/a,c=18e3*p,x=.015,h=.8,g=o();for(let l=0;l<r.length;l++)for(let f=l+1;f<r.length;f++){const y=r[l],D=r[f];let S=D.x-y.x,T=D.y-y.y,z=Math.sqrt(S*S+T*T)||1;const O=Rt(y.degree)+Rt(D.degree)+60,G=Math.max(z,1),le=y.group===D.group?.6:1.4,w=c*le/(G*G),k=z<O?(O-z)*.5:0,I=w+k,q=S/G*I,W=T/G*I;y.vx-=q,y.vy-=W,D.vx+=q,D.vy+=W}for(const l of s){const f=i.get(l.fromId),y=i.get(l.toId);if(!f||!y)continue;let D=y.x-f.x,S=y.y-f.y,T=Math.sqrt(D*D+S*S)||1;const z=f.group===y.group?140:280,O=x*(T-z),G=D/T*O,le=S/T*O;f.vx+=G,f.vy+=le,y.vx-=G,y.vy-=le}const d=.008*p;for(const l of r){const f=g.get(l.group);f&&(l.vx+=(f.x-l.x)*d,l.vy+=(f.y-l.y)*d)}for(const l of r)l.vx*=h,l.vy*=h,l.x+=l.vx,l.y+=l.vy}return r}function Ii(t,s,a,r,i,o,u=0){const p=a-t,c=r-s,x=Math.sqrt(p*p+c*c)||1,h=p/x,g=c/x,d=t+h*i,l=s+g*i,f=a-h*o,y=r-g*o;if(u===0)return`M${d},${l}L${f},${y}`;const D=(d+f)/2+-g*u,S=(l+y)/2+h*u;return`M${d},${l}Q${D},${S},${f},${y}`}const Ti=()=>{const{t}=Ae(),{isDark:s}=Is(),a=s?Ai:$s,r=b=>{const B={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 B[b]?t(B[b]):Si[b]||b},[i,o]=n.useState([]),[u,p]=n.useState({}),[c,x]=n.useState({}),[h,g]=n.useState({}),[d,l]=n.useState(null),[f,y]=n.useState(!0),[D,S]=n.useState(null),[T,z]=n.useState(null),[O,G]=n.useState(null),[le,w]=n.useState(null),[k,I]=n.useState(!1),[q,W]=n.useState(null),[K,C]=n.useState(!1),[v,_]=n.useState(1),[ae,Q]=n.useState({x:0,y:0}),me=n.useRef(null),Se=n.useRef(null),ye=n.useRef(!1),j=n.useRef({x:0,y:0}),N=async()=>{y(!0),S(null);try{const[b,B]=await Promise.all([ee.getKnowledgeGraph(),ee.getGraphStats()]);o(b.edges||[]),p(b.nodeLabels||{}),x(b.nodeTypes||{}),g(b.nodeCategories||{}),l(B)}catch(b){S(ve(b,t("knowledgeGraph.loadFailed")))}finally{y(!1)}};n.useEffect(()=>{N()},[]),n.useEffect(()=>{ee.getDiscoverRelationsStatus().then(b=>{b.status==="running"&&(I(!0),W(t("knowledgeGraph.discoverAnalyzing",{elapsed:b.elapsed??0})))}).catch(()=>{})},[]),n.useEffect(()=>{if(!k)return;let b=0;const B=240,F=setInterval(async()=>{if(b++,b>B){clearInterval(F),I(!1),C(!0),W(t("knowledgeGraph.discoverPollTimeout"));return}try{const $=await ee.getDiscoverRelationsStatus();if($.status==="done"){I(!1);const E=$.discovered??0,te=$.totalPairs??0,fe=$.batchErrors??0;if(E===0&&fe===0)C(!1),W(t("knowledgeGraph.discoverNoResults",{pairs:te}));else if(E===0&&fe>0)C(!0),W(t("knowledgeGraph.discoverBatchErrors",{errors:fe}));else{C(!1);const je=fe>0?t("knowledgeGraph.discoverBatchFailed",{count:fe}):"";W(t("knowledgeGraph.discoverSuccess",{count:E,pairs:te,failMsg:je}))}N()}else if($.status==="error"){I(!1),C(!0);const E=$.error||t("knowledgeGraph.unknownError");E.includes("AI Provider")||E.includes("API Key")?W(t("knowledgeGraph.discoverAiNotConfigured",{error:E})):E.includes("超时")||E.includes("timeout")?W(t("knowledgeGraph.discoverTimeout",{error:E})):W(t("knowledgeGraph.discoverFailed",{error:E}))}else $.status==="running"&&W(t("knowledgeGraph.discoverAnalyzing",{elapsed:$.elapsed??0}))}catch{}},3e3);return()=>clearInterval(F)},[k]);const P=n.useCallback(async()=>{W(null),C(!1);try{const b=await ee.discoverRelations();if(b.status==="empty"){W(b.message||t("knowledgeGraph.discoverInsufficientRecipes"));return}if(b.status==="timeout"){C(!0),W(b.error||t("knowledgeGraph.discoverPreviousTimeout"));return}if(b.status==="running"){I(!0),W(t("knowledgeGraph.discoverRunning"));return}I(!0),W(t("knowledgeGraph.discoverStarted"))}catch(b){C(!0);const B=ve(b,t("knowledgeGraph.unknownError"));B.includes("ChatAgent")||B.includes("AI Provider")?W(t("knowledgeGraph.discoverAiUnavailable",{error:B})):W(t("knowledgeGraph.discoverStartFailed",{error:B}))}},[t]),V=n.useMemo(()=>{if(i.length===0)return[];const b=Di(i,u,c,h);return Ri(b,i)},[i,u,c,h]),ne=n.useMemo(()=>{const b=new Map;for(const $ of V){const E=b.get($.group)||[];E.push($),b.set($.group,E)}const B=[],F=[...b.keys()].sort();for(const $ of F){const E=b.get($);if(E.length===0)continue;let te=0,fe=0;for(const Le of E)te+=Le.x,fe+=Le.y;te/=E.length,fe/=E.length;let je=0,Pe=0;for(const Le of E){const de=Rt(Le.degree);je=Math.max(je,Math.abs(Le.x-te)+de+35),Pe=Math.max(Pe,Math.abs(Le.y-fe)+de+35)}B.push({group:$,cx:te,cy:fe,rx:Math.max(je,60),ry:Math.max(Pe,60),count:E.length})}return B},[V]),ue=n.useMemo(()=>{const b=[...new Set(V.map(F=>F.group))].sort(),B={};return b.forEach((F,$)=>{B[F]=a[$%a.length]}),B},[V,a]),pe=n.useMemo(()=>{if(V.length===0)return{x:0,y:0,w:900,h:700};let b=1/0,B=1/0,F=-1/0,$=-1/0;for(const E of V){const te=Rt(E.degree);b=Math.min(b,E.x-te-80),B=Math.min(B,E.y-te-40),F=Math.max(F,E.x+te+80),$=Math.max($,E.y+te+40)}return{x:b,y:B,w:F-b,h:$-B}},[V]),Ne=n.useMemo(()=>new Map(V.map(b=>[b.id,b])),[V]),{connectedEdgeIds:De,connectedNodeIds:ke}=n.useMemo(()=>{const b=T||O;if(!b)return{connectedEdgeIds:new Set,connectedNodeIds:new Set};const B=new Set,F=new Set([b]);for(const $ of i)($.fromId===b||$.toId===b)&&(B.add($.id),F.add($.fromId),F.add($.toId));return{connectedEdgeIds:B,connectedNodeIds:F}},[T,O,i]),Me=n.useMemo(()=>{const b=new Map,B=new Map;for(const $ of i){const E=[$.fromId,$.toId].sort().join("|"),te=b.get(E)||0;B.set($.id,te),b.set(E,te+1)}const F=new Map;for(const $ of i){const E=[$.fromId,$.toId].sort().join("|"),te=b.get(E)||1;if(te<=1){F.set($.id,0);continue}const fe=B.get($.id)||0;F.set($.id,(fe-(te-1)/2)*40)}return F},[i]),[M,A]=n.useState(new Set);n.useEffect(()=>{A(new Set(i.map(b=>b.relation)))},[i]);const L=n.useMemo(()=>i.filter(b=>M.has(b.relation)),[i,M]),oe=b=>{A(B=>{const F=new Set(B);return F.has(b)?F.delete(b):F.add(b),F})},be=n.useCallback(b=>{b.button===0&&(ye.current=!0,j.current={x:b.clientX,y:b.clientY})},[]),Te=n.useCallback(b=>{if(!ye.current)return;const B=b.clientX-j.current.x,F=b.clientY-j.current.y;j.current={x:b.clientX,y:b.clientY},Q($=>({x:$.x+B,y:$.y+F}))},[]),ce=n.useCallback(()=>{ye.current=!1},[]),ge=n.useCallback(b=>{b.preventDefault();const B=b.deltaY>0?-.1:.1;_(F=>Math.min(3,Math.max(.2,F+B)))},[]),Ee=b=>`kg-arrow-${b.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(D)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:D}),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(i.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(ws,{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")}),q&&e.jsx("p",{className:`text-sm ${K?"text-red-500":"text-green-600"}`,children:q}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{onClick:P,disabled:k,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:k?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(He,{size:H.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(mt,{size:H.sm})," ",t("knowledgeGraph.refresh")]})]})]});const J=[...new Set(i.map(b=>b.relation))].sort(),m=!!(T||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(ws,{size:H.lg,className:"text-blue-600"}),e.jsx("h2",{className:"text-lg xl:text-xl font-bold text-[var(--fg-primary)]",children:t("knowledgeGraph.title")}),d&&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:V.length,edges:d.totalEdges})})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{onClick:()=>_(b=>Math.min(b+.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(Fn,{size:H.sm})}),e.jsx("button",{onClick:()=>_(b=>Math.max(b-.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(zn,{size:H.sm})}),e.jsx("button",{onClick:()=>{_(1),Q({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(pr,{size:H.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(mt,{size:H.sm})}),e.jsx("button",{onClick:P,disabled:k,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:k?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(He,{size:H.sm})," ",t("knowledgeGraph.discoverRelations")]})})]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-3 flex-shrink-0",children:J.map(b=>e.jsxs("button",{onClick:()=>oe(b),className:`flex items-center gap-1 px-2 py-0.5 rounded-full text-[11px] font-medium transition-all border ${M.has(b)?"border-transparent shadow-sm":"border-[var(--border-default)] bg-[var(--bg-surface)] text-[var(--fg-muted)] opacity-40"}`,style:M.has(b)?{backgroundColor:(xt[b]||"#6b7280")+"18",color:xt[b]||"#6b7280"}:{},children:[e.jsx("span",{className:"w-2 h-2 rounded-full",style:{backgroundColor:xt[b]||"#6b7280"}}),r(b),d?.byRelation?.[b]!=null&&e.jsxs("span",{className:"opacity-60",children:["(",d.byRelation[b],")"]})]},b))}),e.jsxs("div",{ref:Se,className:"flex-1 rounded-xl border overflow-hidden relative min-h-0 border-[var(--border-default)] bg-[var(--bg-subtle)]",style:{cursor:ye.current?"grabbing":"grab"},onWheel:ge,children:[e.jsxs("svg",{ref:me,width:"100%",height:"100%",viewBox:`${pe.x} ${pe.y} ${pe.w} ${pe.h}`,onMouseDown:be,onMouseMove:Te,onMouseUp:ce,onMouseLeave:ce,style:{transform:`scale(${v}) translate(${ae.x/v}px, ${ae.y/v}px)`},children:[e.jsxs("defs",{children:[J.map(b=>e.jsx("marker",{id:Ee(b),viewBox:"0 0 10 8",refX:"10",refY:"4",markerWidth:"7",markerHeight:"5",orient:"auto-start-reverse",children:e.jsx("path",{d:"M0,0 L10,4 L0,8 Z",fill:xt[b]||"#6b7280"})},b)),e.jsxs("filter",{id:"kg-glow",x:"-50%",y:"-50%",width:"200%",height:"200%",children:[e.jsx("feGaussianBlur",{in:"SourceAlpha",stdDeviation:"4",result:"blur"}),e.jsx("feFlood",{floodColor:"#3b82f6",floodOpacity:"0.3",result:"color"}),e.jsx("feComposite",{in:"color",in2:"blur",operator:"in",result:"shadow"}),e.jsxs("feMerge",{children:[e.jsx("feMergeNode",{in:"shadow"}),e.jsx("feMergeNode",{in:"SourceGraphic"})]})]})]}),e.jsx("g",{children:ne.map(b=>{const B=ue[b.group]||$s[0];return e.jsxs("g",{children:[e.jsx("ellipse",{cx:b.cx,cy:b.cy,rx:b.rx,ry:b.ry,fill:B.bg,stroke:B.border,strokeWidth:1.5,strokeDasharray:"6,4",opacity:.6}),e.jsxs("text",{x:b.cx,y:b.cy-b.ry+14,textAnchor:"middle",fontSize:11,fontWeight:600,fill:B.text,opacity:.8,style:{pointerEvents:"none",userSelect:"none"},children:[b.group||"general"," (",b.count,")"]})]},b.group)})}),e.jsx("g",{children:L.map(b=>{const B=Ne.get(b.fromId),F=Ne.get(b.toId);if(!B||!F)return null;const $=m?De.has(b.id):!1,E=le===b.id,te=m?$?.85:.06:E?.9:.35,fe=Rt(B.degree),je=Rt(F.degree),Pe=Me.get(b.id)||0,Le=Ii(B.x,B.y,F.x,F.y,fe,je,Pe);return e.jsxs("g",{children:[e.jsx("path",{d:Le,fill:"none",stroke:"transparent",strokeWidth:12,onMouseEnter:()=>w(b.id),onMouseLeave:()=>w(null),style:{cursor:"pointer"}}),e.jsx("path",{d:Le,fill:"none",stroke:xt[b.relation]||"#6b7280",strokeWidth:E||$?2:1.2,opacity:te,markerEnd:`url(#${Ee(b.relation)})`,strokeDasharray:b.relation==="related"?"6,3":void 0,style:{transition:"opacity 0.25s, stroke-width 0.15s",pointerEvents:"none"}}),E&&(()=>{const de=(B.x+F.x)/2,Oe=(B.y+F.y)/2;return e.jsxs("g",{children:[e.jsx("rect",{x:de-24,y:Oe-16,width:48,height:18,rx:4,fill:"var(--bg-surface)",stroke:xt[b.relation]||"#6b7280",strokeWidth:.8,opacity:.95}),e.jsx("text",{x:de,y:Oe-4,textAnchor:"middle",fontSize:9,fontWeight:600,fill:xt[b.relation]||"#6b7280",children:r(b.relation)})]})})()]},b.id)})}),e.jsx("g",{children:V.map(b=>{const B=Rt(b.degree),F=T===b.id,$=m&&ke.has(b.id),E=F||b.id===O,te=m&&!$,fe=te?.12:1,je=ue[b.group]||$s[0],Pe=E?je.border:je.bg,Le=E?je.text:je.border,de=E?"#ffffff":je.text,Oe=E?je.text:"var(--fg-muted)";return e.jsxs("g",{onClick:Be=>{Be.stopPropagation(),z(F?null:b.id)},onMouseEnter:()=>G(b.id),onMouseLeave:()=>G(null),style:{cursor:"pointer",transition:"opacity 0.25s"},opacity:fe,filter:E?"url(#kg-glow)":void 0,children:[e.jsx("circle",{cx:b.x,cy:b.y,r:B,fill:Pe,stroke:Le,strokeWidth:E?2.5:1.5}),e.jsx("text",{x:b.x,y:b.y+4,textAnchor:"middle",fontSize:Math.min(ki,B*.7),fill:de,fontWeight:700,style:{pointerEvents:"none",userSelect:"none"},children:La(b.label,4).toUpperCase()}),e.jsx("text",{x:b.x,y:b.y+B+14,textAnchor:"middle",fontSize:Ci,fill:Oe,fontWeight:E?600:400,style:{pointerEvents:"none",userSelect:"none"},children:La(b.label,18)}),b.degree>=3&&!te&&e.jsxs("g",{children:[e.jsx("circle",{cx:b.x+B*.7,cy:b.y-B*.7,r:8,fill:"#3b82f6",stroke:"var(--bg-surface)",strokeWidth:1.5}),e.jsx("text",{x:b.x+B*.7,y:b.y-B*.7+3.5,textAnchor:"middle",fontSize:8,fill:"white",fontWeight:700,style:{pointerEvents:"none"},children:b.degree})]})]},b.id)})})]}),T&&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:()=>z(null),children:t("knowledgeGraph.cancelSelection")})]}),T&&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(Us,{size:14,className:"text-blue-500"}),e.jsx("h3",{className:"font-semibold text-sm text-[var(--fg-primary)]",children:u[T]||T}),e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)] ml-auto",children:["ID: ",T]})]}),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:[i.filter(b=>b.fromId===T&&M.has(b.relation)).map(b=>e.jsxs("li",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:xt[b.relation]||"#6b7280"}}),e.jsx("span",{className:"text-[var(--fg-secondary)]",children:r(b.relation)}),e.jsx("span",{className:"text-[var(--fg-muted)]",children:"→"}),e.jsx("button",{className:"text-blue-600 hover:underline truncate",onClick:()=>z(b.toId),children:u[b.toId]||b.toId.substring(0,16)})]},b.id)),i.filter(b=>b.fromId===T&&M.has(b.relation)).length===0&&e.jsx("li",{className:"text-[var(--fg-muted)]",children:t("knowledgeGraph.none")})]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[var(--fg-secondary)] font-medium",children:t("knowledgeGraph.inEdges")}),e.jsxs("ul",{className:"mt-1.5 space-y-1",children:[i.filter(b=>b.toId===T&&M.has(b.relation)).map(b=>e.jsxs("li",{className:"flex items-center gap-1.5",children:[e.jsx("button",{className:"text-blue-600 hover:underline truncate",onClick:()=>z(b.fromId),children:u[b.fromId]||b.fromId.substring(0,16)}),e.jsx("span",{className:"text-[var(--fg-muted)]",children:"→"}),e.jsx("span",{className:"text-[var(--fg-secondary)]",children:r(b.relation)}),e.jsx("span",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:xt[b.relation]||"#6b7280"}})]},b.id)),i.filter(b=>b.toId===T&&M.has(b.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(ot,{className:"h-4 w-4 rounded-sm"}),e.jsx(ot,{className:"h-3.5 w-[30%]"}),e.jsx(ot,{className:"h-3.5 w-[12%]"}),e.jsx(ot,{className:"h-3.5 w-[12%]"}),e.jsx(ot,{className:"h-3.5 w-[15%]"}),e.jsx(ot,{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(ot,{className:"h-4 w-4 rounded-sm"}),e.jsx(ot,{className:"h-3.5 w-[28%]",style:{width:`${24+s%3*8}%`}}),e.jsx(ot,{className:"h-5 w-14 rounded-full"}),e.jsx(ot,{className:"h-5 w-16 rounded-full"}),e.jsx(ot,{className:"h-3.5 w-[12%]"}),e.jsx(ot,{className:"h-5 w-5 rounded"})]},s))]})}const ut={pending:{labelKey:"lifecycle.pending",color:"text-amber-700",bg:"bg-amber-50",border:"border-amber-200",icon:tt},active:{labelKey:"lifecycle.active",color:"text-green-700",bg:"bg-green-50",border:"border-green-200",icon:rs},deprecated:{labelKey:"lifecycle.deprecated",color:"text-orange-600",bg:"bg-orange-50",border:"border-orange-200",icon:Ws}},Yt={rule:{labelKey:"kind.rule",color:"text-red-700",bg:"bg-red-50",border:"border-red-200",icon:at},pattern:{labelKey:"kind.pattern",color:"text-violet-700",bg:"bg-violet-50",border:"border-violet-200",icon:Ft},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:rs},{action:"deprecate",labelKey:"knowledge.actionDeprecate",color:"text-orange-700",bg:"bg-orange-50 hover:bg-orange-100",icon:Ws,needsReason:!0}],active:[{action:"deprecate",labelKey:"knowledge.actionDeprecate",color:"text-orange-700",bg:"bg-orange-50 hover:bg-orange-100",icon:Ws,needsReason:!0}],deprecated:[{action:"reactivate",labelKey:"knowledge.actionReactivate",color:"text-green-700",bg:"bg-green-50 hover:bg-green-100",icon:cr}]};function Qt(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 o=Date.now()-a;if(o<0)return r.toLocaleDateString();const u=Math.floor(o/6e4);if(u<1)return s("candidates.timeJustNow");if(u<60)return s("candidates.timeMinutesAgo",{n:u});const p=Math.floor(u/60);if(p<24)return s("candidates.timeHoursAgo",{n:p});const c=Math.floor(p/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?oa(t).split(`
112
+ `).slice(0,s).join(`
113
+ `):""}const Ma={"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"}},_i=({onRefresh:t,idTitleMap:s})=>{const{t:a}=Ae(),r=A=>({pending:a("knowledge.lifecyclePending"),active:a("knowledge.lifecycleActive"),deprecated:a("knowledge.lifecycleDeprecated")})[A]||A,i=A=>({publish:a("knowledge.actionPublish"),deprecate:a("knowledge.actionDeprecate"),reactivate:a("knowledge.actionReactivate")})[A]||A,[o,u]=n.useState([]),[p,c]=n.useState(null),[x,h]=n.useState(!0),[g,d]=n.useState(1),[l,f]=n.useState(12),[y,D]=n.useState(0),[S,T]=n.useState(""),[z,O]=n.useState(""),[G,le]=n.useState(""),[w,k]=n.useState(""),[I,q]=n.useState(""),{isWide:W,toggle:K}=da(),[C,v]=n.useState(null),[_,ae]=n.useState(!1),[Q,me]=n.useState(new Set),[Se,ye]=n.useState(!1),j=n.useRef(!0);n.useEffect(()=>(j.current=!0,()=>{j.current=!1}),[]);const N=n.useCallback(async()=>{h(!0);try{const A=await ee.knowledgeList({page:g,limit:l,lifecycle:S||void 0,kind:z||void 0,category:G||void 0,keyword:w||void 0});j.current&&(u(A.data||[]),D(A.pagination?.total||0))}catch(A){Z(ve(A,a("knowledge.loadFailed")),{title:a("common.loadFailed"),type:"error"})}finally{j.current&&h(!1)}},[g,l,S,z,G,w]),P=n.useCallback(async()=>{try{const A=await ee.knowledgeStats();j.current&&c(A)}catch{}},[]);n.useEffect(()=>{N()},[N]),n.useEffect(()=>{P()},[P]),n.useEffect(()=>{const A=setTimeout(()=>{k(I),d(1)},300);return()=>clearTimeout(A)},[I]),n.useEffect(()=>{d(1)},[S,z,G]);const V=n.useCallback(()=>{N(),P(),t?.()},[N,P,t]),ne=n.useMemo(()=>{const A=new Map;if(s)for(const[L,oe]of Object.entries(s))A.set(L,oe);for(const L of o)L.id&&L.title&&A.set(L.id,L.title);return A},[o,s]),ue=async(A,L,oe)=>{ae(!0);try{const be=await ee.knowledgeLifecycle(A.id,L,oe);Z(`${A.title} → ${a(ut[be.lifecycle]?.labelKey||"")||be.lifecycle}`,{title:a("knowledge.operationSuccess")}),u(Te=>Te.map(ce=>ce.id===A.id?be:ce)),C?.id===A.id&&v(be),P()}catch(be){Z(ve(be,a("common.operationFailed")),{title:a("common.operationFailed"),type:"error"})}finally{j.current&&ae(!1)}},pe=async A=>{if(confirm(a("knowledge.deleteConfirmMsg",{title:A.title})))try{await ee.knowledgeDelete(A.id),Z(a("knowledge.deleteSuccess",{title:A.title}),{title:a("common.delete")}),u(L=>L.filter(oe=>oe.id!==A.id)),C?.id===A.id&&v(null),P()}catch(L){Z(ve(L,a("knowledge.deleteFailed")),{title:a("knowledge.deleteFailed"),type:"error"})}},Ne=async()=>{if(Q.size!==0){ye(!0);try{const A=await ee.knowledgeBatchPublish([...Q]);Z(a("knowledge.batchPublishResult",{success:A.successCount,fail:A.failureCount}),{title:a("knowledge.batchPublish")}),me(new Set),V()}catch(A){Z(ve(A,a("knowledge.batchPublishFailed")),{title:a("common.operationFailed"),type:"error"})}finally{ye(!1)}}},De=async()=>{ye(!0);try{const L=((await ee.knowledgeList({lifecycle:"pending",limit:500})).data||[]).filter(be=>be.autoApprovable).map(be=>be.id);if(L.length===0){Z(a("knowledge.noAutoApprovable"),{title:a("knowledge.noPublishable")});return}const oe=await ee.knowledgeBatchPublish(L);Z(a("knowledge.autoPublishResult",{count:oe.successCount}),{title:a("knowledge.batchPublishComplete")}),V()}catch(A){Z(ve(A,a("knowledge.batchPublishFailed")),{title:a("common.operationFailed"),type:"error"})}finally{ye(!1)}},ke=A=>{me(L=>{const oe=new Set(L);return oe.has(A)?oe.delete(A):oe.add(A),oe})},Me=()=>{Q.size===o.length?me(new Set):me(new Set(o.map(A=>A.id)))},M=(A,L)=>{const oe=prompt(a("knowledge.deprecateReasonPrompt"));oe&&ue(A,L,oe)};return e.jsxs("div",{className:"space-y-4 pb-6",children:[p&&e.jsx("div",{className:"grid grid-cols-3 gap-3",children:Object.entries(ut).map(([A,L])=>{const oe=p[A]||0,be=L.icon;return e.jsxs("button",{onClick:()=>{T(S===A?"":A)},className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-all text-left ${S===A?`${L.bg} ${L.border} ${L.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(be,{size:14}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium",children:r(A)}),e.jsx("div",{className:"text-lg font-bold",children:oe})]})]},A)})}),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(ht,{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:I,onChange:A=>q(A.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(Yt).map(([A,L])=>{const oe=L.icon;return e.jsxs("button",{onClick:()=>O(z===A?"":A),className:`flex items-center gap-1 px-2.5 py-1.5 rounded-md text-xs font-medium border transition-all ${z===A?`${L.bg} ${L.border} ${L.color}`:"bg-[var(--bg-surface)] border-[var(--border-default)] text-[var(--fg-secondary)] hover:bg-[var(--bg-subtle)]"}`,children:[e.jsx(oe,{size:12}),a(L.labelKey)]},A)})}),e.jsx(Ze,{value:G,onChange:A=>le(A),options:[{value:"",label:a("knowledge.allCategories")},...["View","Service","Tool","Model","Network","Storage","UI","Utility"].map(A=>({value:A,label:A}))],size:"sm",className:"text-xs"}),e.jsx("button",{onClick:V,className:"p-2 rounded-md text-[var(--fg-muted)] hover:bg-[var(--bg-subtle)]",title:a("common.refresh"),children:e.jsx(mt,{size:16})}),Q.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:Q.size})}),e.jsx("button",{onClick:Ne,disabled:Se,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:Se?e.jsx(Ce,{size:12,className:"animate-spin"}):a("knowledge.batchPublish")}),e.jsx("button",{onClick:()=>me(new Set),className:"p-1 text-[var(--fg-muted)] hover:text-[var(--fg-primary)]",children:e.jsx(Ue,{size:14})})]}),Q.size===0&&e.jsxs("button",{onClick:De,disabled:Se,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:[Se?e.jsx(Ce,{size:12,className:"animate-spin"}):e.jsx(Ke,{size:12}),a("knowledge.quickBatchPublish")]})]}),x?e.jsx(Ei,{}):o.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||S||z||G)&&e.jsx("button",{onClick:()=>{q(""),T(""),O(""),le("")},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:Q.size===o.length&&o.length>0,onChange:Me,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:y})})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:o.map(A=>{const L=ut[A.lifecycle]||ut.pending,oe=Yt[A.kind]||Yt.pattern,be=L.icon,Te=oe.icon,ce=Li(A.reasoning?.confidence);return e.jsxs("div",{onClick:()=>v(A),className:`group bg-[var(--bg-surface)] rounded-xl border shadow-sm hover:shadow-md cursor-pointer transition-all overflow-hidden ${C?.id===A.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:Q.has(A.id),onChange:ge=>{ge.stopPropagation(),ke(A.id)},onClick:ge=>ge.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 ${L.bg} ${L.color} ${L.border} border`,children:[e.jsx(be,{size:10}),r(A.lifecycle)]}),e.jsxs("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium ${oe.bg} ${oe.color} ${oe.border} border`,children:[e.jsx(Te,{size:10}),a(oe.labelKey)]}),A.category&&e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)]",children:A.category}),e.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded ${ce.bg} ${ce.text}`,children:A.reasoning?.confidence!=null?`${Math.round(A.reasoning.confidence*100)}%`:"—"}),A.autoApprovable&&A.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(Ke,{size:9}),a("knowledge.autoApprovable")]})]}),e.jsx("h3",{className:"text-sm font-bold text-[var(--fg-primary)] mb-1 break-words leading-snug",children:A.title}),(A.description||A.content?.rationale)&&e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] line-clamp-2 leading-relaxed",children:A.description||A.content?.rationale||""}),A.content?.pattern&&e.jsx("pre",{className:"mt-1.5 text-[10px] text-[var(--fg-secondary)] bg-[var(--bg-subtle)] rounded p-1.5 line-clamp-3 font-mono overflow-hidden",children:Mi(A.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:[A.tags?.slice(0,3).map(ge=>e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100",children:ge},ge)),A.tags&&A.tags.length>3&&e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)]",children:["+",A.tags.length-3]}),e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)] ml-auto",children:[A.trigger&&e.jsx("span",{className:"text-blue-400 mr-2",children:A.trigger}),A.source&&e.jsx("span",{className:"mr-2",children:A.source}),Qt(A.updatedAt,a)]})]})]},A.id)})}),e.jsx(ua,{currentPage:g,totalPages:Math.ceil(y/l),onPageChange:d,pageSize:l,onPageSizeChange:A=>{f(A),d(1)},totalItems:y})]}),C&&(()=>{const A=ut[C.lifecycle]||ut.pending,L=Yt[C.kind]||Yt.pattern,oe=it[C.category||""]||it.All||{},be=C.reasoning,Te=o.findIndex(U=>U.id===C.id),ce=Te>0,ge=Te<o.length-1,Ee=()=>{ce&&v(o[Te-1])},J=()=>{ge&&v(o[Te+1])};return e.jsxs(we,{open:!!C,onClose:()=>v(null),size:W?"lg":"md",children:[e.jsxs(we.Header,{title:C.title,children:[e.jsx(we.Nav,{currentIndex:Te,total:o.length,onPrev:Ee,onNext:J,hasPrev:ce,hasNext:ge}),e.jsxs(we.HeaderActions,{children:[e.jsx(we.WidthToggle,{isWide:W,onToggle:K,title:a(W?"knowledge.narrow":"knowledge.widen")}),e.jsx(Ge,{variant:"danger",size:"icon-sm",onClick:()=>{pe(C),v(null)},children:e.jsx(et,{size:16})}),e.jsx(we.CloseButton,{onClose:()=>v(null)})]})]}),e.jsxs(we.Body,{children:[C.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:C.rejectionReason})]}),e.jsx(pa,{badges:(()=>{const U=[];return U.push({label:r(C.lifecycle),className:`${A.bg} ${A.color} ${A.border}`,icon:A.icon}),U.push({label:a(L.labelKey),className:`${L.bg} ${L.color} ${L.border}`,icon:L.icon}),U.push({label:C.category||"general",className:`font-bold uppercase ${oe?.bg||"bg-[var(--bg-subtle)]"} ${oe?.color||"text-[var(--fg-muted)]"} ${oe?.border||"border-[var(--border-default)]"}`}),C.knowledgeType&&U.push({label:C.knowledgeType,className:"bg-purple-50 text-purple-700 border-purple-200"}),C.language&&U.push({label:C.language,className:"uppercase font-bold text-[var(--fg-secondary)] bg-[var(--bg-subtle)] border-[var(--border-default)]"}),C.trigger&&U.push({label:C.trigger,className:"font-mono font-bold bg-amber-50 text-amber-700 border-amber-200"}),U})(),metadata:(()=>{const U=[];return C.scope&&U.push({icon:_t,iconClass:"text-teal-400",label:a("knowledge.scope"),value:C.scope==="universal"?a("knowledge.scopeUniversal"):C.scope==="project-specific"?a("knowledge.scopeProject"):C.scope==="module-level"?a("knowledge.scopeModule"):C.scope}),C.complexity&&U.push({icon:rt,iconClass:"text-orange-400",label:a("knowledge.complexity"),value:C.complexity==="advanced"?a("knowledge.complexityAdvanced"):C.complexity==="intermediate"?a("knowledge.complexityIntermediate"):C.complexity==="beginner"?a("knowledge.complexityBeginner"):C.complexity}),C.source&&C.source!=="unknown"&&U.push({icon:_t,iconClass:"text-violet-400",label:a("knowledge.source"),value:Ma[C.source||""]?a(Ma[C.source||""].labelKey):C.source||"-"}),C.createdAt&&U.push({icon:tt,iconClass:"text-[var(--fg-muted)]",label:a("knowledge.createdAt"),value:Qt(C.createdAt,a)}),C.updatedAt&&U.push({icon:tt,iconClass:"text-[var(--fg-muted)]",label:a("knowledge.updatedAt"),value:Qt(C.updatedAt,a)}),C.publishedAt&&U.push({icon:rs,iconClass:"text-emerald-400",label:a("knowledge.published"),value:Qt(C.publishedAt,a)}),U})(),tags:C.tags,id:C.id,sourceFile:C.sourceFile??void 0,sourceFileLabel:a("knowledge.sourceFile")}),C.relations&&Object.entries(C.relations).some(([,U])=>Array.isArray(U)&&U.length>0)&&e.jsxs("div",{className:"px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[e.jsx(ta,{size:12,className:"text-purple-400"}),e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase",children:a("knowledge.relatedKnowledge")}),(()=>{const U=Object.values(C.relations).flat().length;return U>0?e.jsx("span",{className:"text-[9px] bg-purple-100 text-purple-600 px-1.5 py-0.5 rounded-full font-bold",children:U}):null})()]}),e.jsx("div",{className:"space-y-1.5",children:Object.entries(C.relations).map(([U,m])=>!Array.isArray(m)||m.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:U}),e.jsx("div",{className:"flex flex-wrap gap-1",children:m.map((b,B)=>{const F=b.target||(typeof b=="string"?b:JSON.stringify(b)),$=ne.get(F)||F;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:F,children:$},B)})})]},U))})]}),C.stats&&Object.values(C.stats).some(U=>U>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:C.stats?.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:C.stats?.guardHits??0}),e.jsx("div",{className:"text-[10px] text-[var(--fg-muted)] font-medium",children:a("knowledge.guardHits")})]}),e.jsxs("div",{className:"bg-[var(--bg-subtle)] rounded-xl p-3 text-center border border-[var(--border-default)]",children:[e.jsx("div",{className:"text-lg font-bold text-[var(--fg-primary)]",children:C.stats?.adoptions??0}),e.jsx("div",{className:"text-[10px] text-[var(--fg-muted)] font-medium",children:a("knowledge.adoptions")})]}),e.jsxs("div",{className:"bg-blue-50/60 rounded-xl p-3 text-center border border-blue-100",children:[e.jsx("div",{className:"text-lg font-bold text-blue-700",children:C.stats?.searchHits??0}),e.jsx("div",{className:"text-[10px] text-blue-500 font-medium",children:a("knowledge.searchHits")})]})]}),(C.stats.views>0||C.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"),": ",C.stats.views]}),e.jsxs("span",{children:[a("knowledge.statApplications"),": ",C.stats.applications]})]})]}),e.jsx(Fe.Reasoning,{reasoning:be,labels:{section:a("knowledge.reasoning"),source:`${a("knowledge.source")}:`,confidence:`${a("knowledge.confidence")}:`,alternatives:`${a("knowledge.alternatives")}:`},filterSubmitted:!0}),e.jsx(Fe.Quality,{quality:C.quality,labels:{section:a("knowledge.qualityGrade"),completeness:a("knowledge.qualityCompletionLabel"),adaptation:a("knowledge.qualityAdaptation"),documentation:a("knowledge.qualityDocumentation")},formatFixed:!0}),e.jsx(Fe.Description,{label:a("knowledge.summary"),text:C.description}),e.jsx(Fe.MarkdownSection,{label:a("knowledge.markdownDoc"),content:C.content?.markdown}),e.jsx(Fe.Headers,{label:a("knowledge.importHeaders"),headers:C.headers}),e.jsx(Fe.CodePattern,{label:a("knowledge.codePattern"),code:C.content?.pattern,language:C.language}),e.jsx(Fe.Delivery,{delivery:{topicHint:C.topicHint,whenClause:C.whenClause,doClause:C.doClause,dontClause:C.dontClause,coreCode:C.coreCode},language:C.language}),e.jsx(Fe.Rationale,{label:a("knowledge.designRationale"),text:C.content?.rationale}),e.jsx(Fe.Steps,{label:a("knowledge.implementSteps"),steps:C.content?.steps}),e.jsx(Fe.Constraints,{label:a("knowledge.constraintsLabel"),constraints:C.constraints}),C.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(Ft,{size:11,className:"text-cyan-400"})," ",a("knowledge.aiInsight")]}),e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] leading-relaxed",children:C.aiInsight})]}),(()=>{const U=Array.isArray(C.lifecycleHistory)?C.lifecycleHistory:(()=>{try{const m=typeof C.lifecycleHistory=="string"?JSON.parse(C.lifecycleHistory):null;return Array.isArray(m)?m:[]}catch{return[]}})();return U.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(tt,{size:11,className:"text-[var(--fg-muted)]"})," ",a("knowledge.lifecycleHistoryLabel")]}),e.jsx("div",{className:"space-y-1",children:U.map((m,b)=>{const B=ut[m.from]||ut.pending,F=ut[m.to]||ut.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:Qt(m.at,a)}),e.jsx("span",{className:`${B.color}`,children:r(m.from)}),e.jsx("span",{className:"text-[var(--fg-muted)]",children:"→"}),e.jsx("span",{className:`${F.color} font-medium`,children:r(m.to)}),e.jsxs("span",{className:"text-[var(--fg-muted)] ml-auto",children:["by ",m.by]})]},b)})})]}):null})()]}),e.jsxs(we.Footer,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("button",{onClick:()=>{pe(C),v(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(et,{size:14})," ",a("common.delete")]})}),e.jsx("div",{className:"flex items-center gap-2",children:(Pi[C.lifecycle]||[]).map(U=>{const m=U.icon;return e.jsxs("button",{onClick:()=>U.needsReason?M(C,U.action):ue(C,U.action),disabled:_,className:`flex items-center gap-1.5 px-4 py-2 rounded-lg text-xs font-bold border transition-colors disabled:opacity-50 ${U.bg} ${U.color} border-current/20`,children:[_?e.jsx(Ce,{size:14,className:"animate-spin"}):e.jsx(m,{size:14}),i(U.action)]},U.action)})})]})]})})()]})},ms={manual:{label:"manual",color:"bg-[var(--bg-subtle)] text-[var(--fg-secondary)]",icon:ir},"user-ai":{label:"user-ai",color:"bg-violet-100 text-violet-600",icon:He},"system-ai":{label:"system-ai",color:"bg-amber-100 text-amber-600",icon:as},"external-ai":{label:"external-ai",color:"bg-cyan-100 text-cyan-600",icon:sa}},Fi=({onRefresh:t,signalSuggestionCount:s=0,onSuggestionCountChange:a})=>{const{t:r}=Ae(),[i,o]=n.useState([]),[u,p]=n.useState(!0),[c,x]=n.useState(null),[h,g]=n.useState(!1),[d,l]=n.useState(!1),[f,y]=n.useState("all"),[D,S]=n.useState(!1),[T,z]=n.useState([]),[O,G]=n.useState(!1),[le,w]=n.useState(!1),[k,I]=n.useState(null),[q,W]=n.useState(!1),[K,C]=n.useState(""),[v,_]=n.useState(!1),[ae,Q]=n.useState(!1),[me,Se]=n.useState(!1),ye=n.useCallback(async()=>{p(!0);try{const M=await ee.listSkills();o(M.skills||[])}catch(M){na(M)!==404&&Z(ve(M,""),{title:r("skills.fetchFailed"),type:"error"}),o([])}finally{p(!1)}},[]);n.useEffect(()=>{ye()},[ye]);const j=async M=>{if(c?.skillName===M){x(null);return}W(!1),Q(!1),g(!0);try{const A=await ee.loadSkill(M);x(A)}catch{Z(`"${M}" ${r("skills.loadError")}`,{title:r("skills.loadSkillFailed"),type:"error"})}finally{g(!1)}},N=()=>{c?.content&&(navigator.clipboard.writeText(c.content).catch(()=>{}),S(!0),setTimeout(()=>S(!1),2e3))},P=()=>{c&&(C(c.content),W(!0))},V=()=>{W(!1),C("")},ne=async()=>{if(!(!c||!K.trim())){_(!0);try{await ee.updateSkill(c.skillName,{content:K}),Z(r("skills.saveSuccess"),{title:`Skill "${c.skillName}" ${r("skills.updateSuccess")}`}),W(!1);const M=await ee.loadSkill(c.skillName);x(M)}catch(M){Z(ve(M,""),{title:r("skills.updateFailed"),type:"error"})}finally{_(!1)}}},ue=async()=>{if(c){Se(!0);try{await ee.deleteSkill(c.skillName),Z(r("skills.deleteSuccess"),{title:`Skill "${c.skillName}" ${r("skills.deleteSuccess")}`}),x(null),Q(!1),W(!1),ye(),t?.()}catch(M){Z(ve(M,""),{title:r("skills.deleteFailed"),type:"error"})}finally{Se(!1)}}},pe=async()=>{G(!0),w(!0);try{const[M,A]=await Promise.allSettled([ee.suggestSkills(),ee.getSignalStatus()]),L=M.status==="fulfilled"?M.value.suggestions||[]:[],oe=A.status==="fulfilled"?A.value.suggestions||[]:[],be=new Map;for(const ce of L)be.set(ce.name,ce);for(const ce of oe)be.set(ce.name,{...be.get(ce.name),...ce});const Te=[...be.values()];z(Te),a?.(Te.length)}catch(M){Z(ve(M,""),{title:r("skills.aiRecommendFailed"),type:"error"}),z([]),a?.(0)}finally{G(!1)}};n.useEffect(()=>{s>0&&T.length===0&&!le&&pe()},[]);const Ne=async M=>{I(M.name);try{const A=M.description||M.rationale||M.name,L=`${r("skillsView.aiPromptPrefix")}
114
+
115
+ 名称:${M.name}
116
+ 描述:${A}
117
+ 推荐原因:${M.rationale}
118
+
119
+ 请直接生成 Skill 正文内容(Markdown 格式),不需要 frontmatter,不需要输出 JSON 元数据。内容应该详细、实用,包含具体的操作指南和示例。`;let be=(await ee.aiGenerateSkill(L)).reply||M.body||`# ${A}
120
+
121
+ ${M.rationale||""}`;be=be.replace(/^\s*\{["']name["']\s*:.*\}\s*\n?/,"").trim(),await ee.createSkill({name:M.name,description:A,content:be,createdBy:"user-ai"}),Z(r("skills.createAddedToKB"),{title:`Skill "${M.name}" ${r("skills.createSuccess")}`}),z(Te=>{const ce=Te.filter(ge=>ge.name!==M.name);return a?.(ce.length),ce}),ye()}catch(A){Z(ve(A,""),{title:r("skills.createFailed"),type:"error"})}finally{I(null)}},De=i.filter(M=>f==="all"?!0:M.source===f).sort((M,A)=>M.source===A.source?M.name.localeCompare(A.name):M.source==="project"?-1:1),ke=i.filter(M=>M.source==="builtin").length,Me=i.filter(M=>M.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:pe,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(Ce,{size:14,className:"animate-spin"}):e.jsx(Ft,{size:14}),r("skills.aiRecommend")]}),e.jsx("button",{onClick:ye,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(mt,{size:16})}),e.jsxs("button",{onClick:()=>l(!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(He,{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:i.length},{key:"project",label:r("skills.filterProject"),count:Me,icon:jt},{key:"builtin",label:r("skills.filterBuiltin"),count:ke,icon:Bn}].map(M=>e.jsxs("button",{onClick:()=>y(M.key),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${f===M.key?"bg-[var(--bg-surface)] text-violet-700 shadow-sm":"text-[var(--fg-secondary)] hover:text-[var(--fg-primary)]"}`,children:[M.icon&&e.jsx(M.icon,{size:12}),M.label,e.jsx("span",{className:`ml-0.5 px-1.5 py-0.5 rounded-full text-[10px] ${f===M.key?"bg-violet-100 text-violet-600":"bg-[var(--bg-subtle)] text-[var(--fg-secondary)]"}`,children:M.count})]},M.key))}),le&&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(Ft,{size:16,className:"text-amber-600"}),e.jsx("span",{className:"text-sm font-semibold text-amber-800",children:r("skills.aiRecommendDesc")}),T.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:T.length})]}),e.jsx("button",{onClick:()=>w(!1),className:"p-1 text-amber-400 hover:text-amber-600",children:e.jsx(Ue,{size:14})})]}),O?e.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-xs py-2",children:[e.jsx(Ce,{size:14,className:"animate-spin"}),r("skills.aiRecommending")]}):T.length===0?e.jsx("p",{className:"text-xs text-amber-600/70",children:r("skills.noRecommendations")}):e.jsx("div",{className:"space-y-2",children:T.map(M=>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:M.name}),e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[9px] font-bold uppercase ${M.priority==="high"?"bg-red-100 text-red-600":M.priority==="medium"?"bg-amber-100 text-amber-600":"bg-[var(--bg-subtle)] text-[var(--fg-secondary)]"}`,children:M.priority}),e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)]",children:M.source})]}),e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] mb-1",children:M.description}),e.jsx("p",{className:"text-[11px] text-[var(--fg-muted)] line-clamp-2",children:M.rationale})]}),e.jsx("button",{onClick:()=>Ne(M),disabled:k===M.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:k===M.name?e.jsxs(e.Fragment,{children:[e.jsx(Ce,{size:12,className:"animate-spin"})," ",r("skills.creating")]}):e.jsxs(e.Fragment,{children:[e.jsx(Ke,{size:12})," ",r("skills.acceptRecommend")]})})]},M.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:u?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx(Ce,{size:24,className:"animate-spin text-violet-400"})}):De.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")})]}):De.map(M=>e.jsx("button",{onClick:()=>j(M.name),className:`w-full text-left p-4 rounded-xl border transition-all ${c?.skillName===M.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?.skillName===M.name?"text-violet-500":"text-[var(--fg-muted)]"}`,children:c?.skillName===M.name?e.jsx(Nt,{size:16}):e.jsx(Qe,{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:M.name}),e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-bold uppercase tracking-wider ${M.source==="builtin"?"bg-blue-100 text-blue-600":"bg-emerald-100 text-emerald-600"}`,children:M.source==="builtin"?r("skills.filterBuiltin"):r("skills.filterProject")}),M.createdBy&&ms[M.createdBy]&&(()=>{const A=ms[M.createdBy],L=A.icon;return e.jsxs("span",{className:`flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[10px] font-medium ${A.color}`,children:[e.jsx(L,{size:10}),A.label]})})()]}),e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] line-clamp-2",children:M.summary}),M.useCase&&e.jsxs("p",{className:"text-[11px] text-violet-500 mt-1 italic",children:[r("skills.useCase"),":",M.useCase]})]})]})},M.name))}),e.jsx("div",{className:"w-1/2 overflow-y-auto border border-[var(--border-default)] rounded-xl bg-[var(--bg-surface)]",children:h?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(Ce,{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(ct,{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&&ms[c.createdBy]&&(()=>{const M=ms[c.createdBy],A=M.icon;return e.jsxs("span",{className:`flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[10px] font-medium ${M.color}`,children:[e.jsx(A,{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:D?e.jsx(pt,{size:14,className:"text-emerald-500"}):e.jsx(Ot,{size:14})}),c.source==="project"&&!q&&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(qs,{size:14})}),e.jsx("button",{onClick:()=>Q(!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(et,{size:14})})]}),q&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:ne,disabled:v,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:[v?e.jsx(Ce,{size:12,className:"animate-spin"}):e.jsx(Rs,{size:12}),r("common.save")]}),e.jsx("button",{onClick:V,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(M=>e.jsx("button",{onClick:()=>j(M),className:"text-[11px] text-violet-600 hover:text-violet-800 bg-violet-50 px-2 py-0.5 rounded-full transition-colors",children:M},M))]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 relative",children:[q?e.jsx("textarea",{value:K,onChange:M=>C(M.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}),ae&&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(et,{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:()=>Q(!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:me,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:[me?e.jsx(Ce,{size:14,className:"animate-spin"}):e.jsx(et,{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")})]})})})]}),d&&e.jsx(zi,{onClose:()=>l(!1),onCreated:()=>{l(!1),ye(),t?.()}})]})},zi=({onClose:t,onCreated:s})=>{const{t:a}=Ae(),[r,i]=n.useState("ai"),[o,u]=n.useState(""),[p,c]=n.useState(!1),[x,h]=n.useState(""),[g,d]=n.useState(""),[l,f]=n.useState(""),[y,D]=n.useState(!1),[S,T]=n.useState(""),[z,O]=n.useState(!1),G=async()=>{if(o.trim()){c(!0),T("");try{const k=(await ee.aiGenerateSkill(o)).reply||"";let I="",q="",W=k;const K=/```(?:json)?\s*\n?\s*(\{[^}]*"name"[^}]*\})\s*\n?\s*```/i,C=k.match(K);if(C)try{const v=JSON.parse(C[1]);I=v.name||"",q=v.description||"",W=k.replace(C[0],"").trim()}catch{}if(!I){const v=k.split(`
122
+ `);for(let _=0;_<Math.min(v.length,5);_++){const ae=v[_].trim();if(!(!ae||ae.startsWith("```"))&&ae.startsWith("{")&&ae.endsWith("}"))try{const Q=JSON.parse(ae);if(Q.name){I=Q.name,q=Q.description||"";let me=_+1;for(;me<v.length&&!v[me].trim();)me++;W=v.slice(me).join(`
123
+ `).trim();break}}catch{}}}if(!I){const v=/"name"\s*:\s*"([a-z][a-z0-9-]{1,62}[a-z0-9])"/,_=/"description"\s*:\s*"([^"]+)"/,ae=k.match(v),Q=k.match(_);ae&&(I=ae[1]),Q&&(q=Q[1])}W=W.replace(/```(?:json)?\s*\n?\s*\{[^}]*"name"[^}]*\}\s*\n?\s*```/gi,"").replace(/^\s*\{[^}]*"name"[^}]*\}\s*$/gm,"").trim(),I&&h(I),q&&d(q),f(W||k.trim()),O(!0),i("manual"),Z(a("skills.checkGenerated"),{title:a("skills.aiGenerated")})}catch(w){T(a("skills.aiGenFailed")+": "+ve(w,""))}finally{c(!1)}}},le=async()=>{if(!x.trim()||!g.trim()||!l.trim()){T(a("skills.fillRequired"));return}D(!0),T("");try{await ee.createSkill({name:x.trim(),description:g.trim(),content:l.trim(),createdBy:z?"user-ai":"manual"}),Z(a("skills.savedToKB"),{title:`Skill "${x}" ${a("skills.createSuccess")}`}),s()}catch(w){T(a("skills.createFailed")+": "+ve(w,""))}finally{D(!1)}};return e.jsxs(Ve,{className:"z-40 flex items-center justify-center",children:[e.jsx(Ve.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(He,{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(Ue,{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:()=>i("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(He,{size:12}),a("skills.aiGenMode")]}),e.jsxs("button",{onClick:()=>i("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(ct,{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:o,onChange:w=>u(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:p})})]}),e.jsx("button",{onClick:G,disabled:p||!o.trim(),className:"w-full flex items-center justify-center gap-2 px-4 py-3 bg-violet-600 text-white rounded-xl hover:bg-violet-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-medium",children:p?e.jsxs(e.Fragment,{children:[e.jsx(Ce,{size:16,className:"animate-spin"}),a("skills.aiGeneratingContent")]}):e.jsxs(e.Fragment,{children:[e.jsx(Zs,{size:16}),a("skills.generateSkill")]})})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-[var(--fg-primary)] mb-1.5",children:[a("skills.skillName")," ",e.jsx("span",{className:"text-[var(--fg-muted)] text-xs",children:"(kebab-case)"})]}),e.jsx("input",{type:"text",value:x,onChange:w=>h(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=>d(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:l,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"})]})]}),S&&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(Kt,{size:16,className:"shrink-0 mt-0.5"}),e.jsx("span",{children:S})]})]}),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:le,disabled:y||!x.trim()||!g.trim()||!l.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:y?e.jsxs(e.Fragment,{children:[e.jsx(Ce,{size:14,className:"animate-spin"}),a("common.saving")]}):e.jsxs(e.Fragment,{children:[e.jsx(gt,{size:14}),a("skills.addSkill")]})})]})]})]})},_a=["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(Ht,{className:"w-5 h-5"}),architecture:e.jsx(rt,{className:"w-5 h-5"}),"best-practice":e.jsx(He,{className:"w-5 h-5"}),"event-and-data-flow":e.jsx(Ke,{className:"w-5 h-5"}),"project-profile":e.jsx(Ns,{className:"w-5 h-5"}),"agent-guidelines":e.jsx(sa,{className:"w-5 h-5"})};function Gi(t){return Bi[t]||e.jsx(Ht,{className:"w-5 h-5"})}const $i=({task:t})=>{const{t:s}=Ae(),{status:a,meta:r}=t,i={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"},o={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(Ce,{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(pt,{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(Ue,{className:"w-3 h-3"}),s("bootstrap.statusLabels.failed")]})};return e.jsxs("div",{className:`relative rounded-xl border p-4 transition-all duration-300 ${i[a]||i.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 u=`bootstrap.pipelineLabels.${r.dimId}`,p=s(u);return p!==u?p:r.label})()}),a==="completed"&&t.result&&e.jsx("p",{className:"text-xs text-emerald-600 mt-0.5",children:(()=>{const u=t.result,p=u.sourceCount??0,c=u.extracted??0;return u.type==="empty"?s("bootstrap.noMatch"):u.type==="skill"?u.empty?s("bootstrap.noMatch"):c>0?s("bootstrap.featuresAndCandidates",{sourceCount:p,extracted:c}):s("bootstrap.featuresOnly",{sourceCount:p}):c>0?s("bootstrap.candidatesOnly",{extracted:c}):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:o[a]})]})]})},Hi=[{key:"round1",labelKey:"bootstrap.reviewRounds.round1Label",descKey:"bootstrap.reviewRounds.round1Desc",icon:e.jsx(hr,{className:"w-4 h-4"})},{key:"round2",labelKey:"bootstrap.reviewRounds.round2Label",descKey:"bootstrap.reviewRounds.round2Desc",icon:e.jsx(gs,{className:"w-4 h-4"})},{key:"round3",labelKey:"bootstrap.reviewRounds.round3Label",descKey:"bootstrap.reviewRounds.round3Desc",icon:e.jsx(Gn,{className:"w-4 h-4"})}],Oi=({review:t})=>{const{t:s}=Ae();return t.activeRound===0?null:e.jsxs("div",{className:"mt-5 border border-purple-200 rounded-xl bg-purple-50/50 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(qt,{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:i,icon:o})=>{const u=t[a],p=u.status==="running",c=u.status==="completed",x=u.status==="idle";return e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg border transition-all duration-300 ${p?"border-purple-300 bg-purple-100/60":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 ${p?"bg-purple-200 text-purple-700":c?"bg-emerald-100 text-emerald-600":"bg-[var(--bg-subtle)] text-[var(--fg-muted)]"}`,children:o}),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(i)})]}),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"&&p&&typeof t.round2.progress=="number"&&e.jsxs("div",{className:"mt-1.5",children:[e.jsx("div",{className:"w-full h-1.5 bg-purple-200 rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-purple-500 rounded-full transition-all duration-300",style:{width:`${t.round2.progress}%`}})}),e.jsx("p",{className:"text-xs text-purple-600 mt-0.5",children:s("bootstrap.round2Progress",{current:t.round2.current??0,total:t.round2.total??"?"})})]}),a==="round2"&&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:[p&&e.jsx(Ce,{className:"w-4 h-4 text-purple-500 animate-spin"}),c&&e.jsx(pt,{className:"w-4 h-4 text-emerald-500"})]})]},a)})})]})};function Fa(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:i}=Ae(),[o,u]=n.useState(Date.now());if(n.useEffect(()=>{if(!t||t.status!=="running")return;const f=setInterval(()=>u(Date.now()),1e3);return()=>clearInterval(f)},[t?.status]),!t)return null;const p=t.startedAt?o-t.startedAt:t.elapsedMs??0,c=t.completed+t.failed,x=t.total-c,h=t.elapsedMs??0,g=c>0&&h>0?Math.round(h/c*x):-1,d=t.totalToolCalls??0,l=t.status==="completed"?i("bootstrap.allCompleted"):t.status==="completed_with_errors"?i("bootstrap.completedWithErrors"):null;return e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-[var(--border-default)] shadow-sm p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-5",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold text-[var(--fg-primary)]",children:i("bootstrap.title")}),l&&e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] mt-0.5",children:l})]}),s&&r&&e.jsx("button",{onClick:r,className:"text-sm px-3 py-1.5 rounded-lg bg-[var(--bg-subtle)] hover:bg-[var(--bg-subtle)] text-[var(--fg-secondary)] transition-colors",children:i("bootstrap.close")})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-5 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[var(--fg-secondary)]",children:[e.jsx(tt,{size:14,className:"text-[var(--fg-muted)]"}),e.jsxs("span",{children:[i("bootstrap.elapsed")," ",e.jsx("span",{className:"font-medium text-[var(--fg-primary)]",children:Fa(p)})]})]}),t.status==="running"&&x>0&&g>0&&e.jsxs("div",{className:"flex items-center gap-1.5 text-[var(--fg-secondary)]",children:[e.jsx(tt,{size:14,className:"text-blue-400"}),e.jsxs("span",{children:[i("bootstrap.estimatedRemaining")," ",e.jsx("span",{className:"font-medium text-blue-600",children:Fa(g)})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-[var(--fg-secondary)]",children:[e.jsx(fr,{size:14,className:"text-[var(--fg-muted)]"}),e.jsxs("span",{children:[i("bootstrap.toolCalls")," ",e.jsx("span",{className:"font-medium text-[var(--fg-primary)]",children:d})]})]}),e.jsx("div",{className:"text-[var(--fg-muted)] text-xs",children:i("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,y)=>{const D=_a.indexOf(f.meta?.dimId??f.id),S=_a.indexOf(y.meta?.dimId??y.id);return(D===-1?999:D)-(S===-1?999:S)}).map(f=>e.jsx($i,{task:f},f.id))}),a&&a.activeRound>0&&e.jsx(Oi,{review:a})]})},xs={index:{icon:qe,color:"text-blue-600",label:"overview"},architecture:{icon:rt,color:"text-violet-600",label:"architecture"},"getting-started":{icon:kt,color:"text-emerald-600",label:"getting-started"},protocols:{icon:He,color:"text-amber-600",label:"protocols"},components:{icon:kt,color:"text-emerald-600",label:"components"},patterns:{icon:He,color:"text-amber-600",label:"patterns"},module:{icon:jt,color:"text-cyan-600",label:"module"},document:{icon:ct,color:"text-orange-600",label:"document"},_index:{icon:Xs,color:"text-[var(--fg-secondary)]",label:"index"}};function qi(t){const s=t.split("/").pop()?.replace(".md","")||"";return s==="_index"?xs._index:t.startsWith("modules/")?xs.module:t.startsWith("documents/")?xs.document:xs[s]||{icon:ct,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 Hr(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}=Ae();return t.status==="running"?null:t.status==="error"?e.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-xl p-4 mb-6 flex items-center gap-3",children:[e.jsx("div",{className:"p-1.5 bg-red-100 rounded-lg",children:e.jsx(Kt,{size:H.md,className:"text-red-600"})}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-red-800",children:a("wiki.genFailed")}),e.jsx("span",{className:"text-sm text-red-600 ml-3",children:t.error||a("common.operationFailed")})]})]}):s?.exists&&s.hasChanges?e.jsxs("div",{className:"bg-amber-50 border border-amber-200 rounded-xl p-4 mb-6 flex items-center gap-3",children:[e.jsx("div",{className:"p-1.5 bg-amber-100 rounded-lg",children:e.jsx(Kt,{size:H.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?.map(x=>[x.path,x])||[]),i=[],o=new Map;for(const x of t){const h=x.path.split("/"),g=r.get(x.path);if(h.length===1)i.push({name:h[0],path:x.path,isDir:!1,file:x,metaInfo:g});else{const d=h[0];o.has(d)||o.set(d,[]),o.get(d).push({name:h.slice(1).join("/"),path:x.path,isDir:!1,file:x,metaInfo:g})}}const u=["index.md","architecture.md","getting-started.md","patterns.md","protocols.md","components.md"];i.sort((x,h)=>{const g=u.indexOf(x.name),d=u.indexOf(h.name);return g!==-1&&d!==-1?g-d:g!==-1?-1:d!==-1?1:x.name.localeCompare(h.name)}),a.push(...i);const p=["modules","patterns","documents"],c=[...o.entries()].sort(([x],[h])=>{const g=p.indexOf(x),d=p.indexOf(h);return g!==-1&&d!==-1?g-d:g!==-1?-1:d!==-1?1:x.localeCompare(h)});for(const[x,h]of c){const g=h.filter(d=>!d.name.startsWith("_index")).sort((d,l)=>d.name.localeCompare(l.name));a.push({name:x,path:x,isDir:!0,children:g})}return a}const Qi=({tree:t,selectedFile:s,onSelect:a,searchQuery:r})=>{const[i,o]=n.useState(new Set(["modules","documents"])),u=x=>{o(h=>{const g=new Set(h);return g.has(x)?g.delete(x):g.add(x),g})},c=(x=>{if(!r)return x;const h=r.toLowerCase();return x.filter(g=>g.isDir?g.children?.some(d=>d.name.toLowerCase().includes(h)||d.path.toLowerCase().includes(h)):g.name.toLowerCase().includes(h)||g.path.toLowerCase().includes(h))})(t);return e.jsx("div",{className:"space-y-0.5",children:c.map(x=>{if(x.isDir){const h=i.has(x.path),g=r.toLowerCase(),d=r?x.children?.filter(l=>l.name.toLowerCase().includes(g)||l.path.toLowerCase().includes(g)):x.children;return e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>u(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:[h?e.jsx(Nt,{size:14,className:"text-[var(--fg-muted)] flex-shrink-0"}):e.jsx(Qe,{size:14,className:"text-[var(--fg-muted)] flex-shrink-0"}),e.jsx(jt,{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:d?.length||0})]}),h&&d&&e.jsx("div",{className:"ml-3",children:d.map(l=>e.jsx(za,{node:l,isActive:s===l.path,onSelect:a},l.path))})]},x.path)}return e.jsx(za,{node:x,isActive:s===x.path,onSelect:a},x.path)})})},za=({node:t,isActive:s,onSelect:a})=>{const r=qi(t.path),i=r.icon,o=t.metaInfo?.polished,u=t.metaInfo?.source;return e.jsxs("button",{onClick:()=>a(t.path),className:`w-full flex items-center gap-2 px-3 py-2 text-sm rounded-lg transition-all ${s?"bg-blue-50 text-blue-700 border border-blue-200 shadow-sm":"text-[var(--fg-secondary)] hover:bg-[var(--bg-subtle)]"}`,children:[e.jsx(i,{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:[o&&e.jsx("span",{title:"AI Enhanced",children:e.jsx(He,{size:10,className:"text-violet-400"})}),u&&e.jsx("span",{title:`Source: ${u}`,children:e.jsx(Hn,{size:10,className:"text-orange-400"})})]})]})},Xi=({filePath:t,content:s,loading:a,meta:r,onBack:i})=>{const{t:o}=Ae(),[u,p]=n.useState(!1),c=r?.files?.find(d=>d.path===t),x=()=>{navigator.clipboard.writeText(s).catch(()=>{}),p(!0),setTimeout(()=>p(!1),2e3)},h=t.split("/"),g=h.map((d,l)=>({label:l===h.length-1?d.replace(".md",""):d,isLast:l===h.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:i,className:"p-1.5 hover:bg-[var(--bg-subtle)] rounded-lg transition-colors lg:hidden",title:o("wiki.backToList"),children:e.jsx($n,{size:H.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((d,l)=>e.jsxs(St.Fragment,{children:[e.jsx(Qe,{size:12,className:"text-[var(--fg-muted)]"}),e.jsx("span",{className:d.isLast?"font-medium text-[var(--fg-primary)]":"text-[var(--fg-muted)]",children:d.label})]},l))]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[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(He,{size:10}),o("wiki.aiBadge")]}),c?.source&&(()=>{const d=Ui[c.source];return e.jsx("span",{className:`flex items-center gap-1 text-xs border px-2 py-0.5 rounded-full ${d?.bg||"bg-[var(--bg-subtle)] border-[var(--border-default)]"} ${d?.color||"text-[var(--fg-secondary)]"}`,children:d?.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:[u?e.jsx(pt,{size:12,className:"text-emerald-500"}):e.jsx(Ot,{size:12}),o(u?"wiki.copySuccess":"wiki.copyBtn")]})]})]}),e.jsx("div",{className:"flex-1 overflow-auto scrollbar-light",style:{scrollbarGutter:"stable"},children:a?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx(Ce,{size:H.xl,className:"text-blue-500 animate-spin"})}):e.jsx("div",{className:"px-4 xl:px-6 2xl:px-8 py-6 max-w-4xl mx-auto",children:e.jsx(Ct,{content:s,className:"wiki-reader"})})})]})},Zi=()=>{const{t}=Ae();return e.jsxs("div",{className:"h-72 flex flex-col items-center justify-center bg-[var(--bg-surface)] rounded-2xl border border-dashed border-[var(--border-default)] text-[var(--fg-muted)]",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-[var(--bg-subtle)] flex items-center justify-center mb-4",children:e.jsx(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:i})=>{const{t:o}=Ae(),u=[{path:"index.md",label:o("wiki.quickOverview"),desc:o("wiki.quickOverviewDesc"),icon:qe,color:"bg-blue-50 text-blue-600 border-blue-200"},{path:"architecture.md",label:o("wiki.quickArch"),desc:o("wiki.quickArchDesc"),icon:rt,color:"bg-violet-50 text-violet-600 border-violet-200"},{path:"getting-started.md",label:o("wiki.quickStart"),desc:o("wiki.quickStartDesc"),icon:kt,color:"bg-emerald-50 text-emerald-600 border-emerald-200"},{path:"protocols.md",label:o("wiki.quickProtocols"),desc:o("wiki.quickProtocolsDesc"),icon:He,color:"bg-amber-50 text-amber-600 border-amber-200"}],p=new Set(t?.files?.map(x=>x.path||x.name)??[]),c=u.filter(x=>p.size===0||p.has(x.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(sa,{size:36,className:"text-blue-500 animate-pulse"})})]}),e.jsx("h3",{className:"text-lg font-semibold text-[var(--fg-primary)] mb-1",children:o("wiki.wikiGenerating")}),e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] max-w-md text-center leading-relaxed",children:i||o("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(ct,{size:24,className:"text-[var(--fg-muted)]"})}),e.jsx("h3",{className:"text-lg font-semibold text-[var(--fg-primary)]",children:o("wiki.selectFile")}),e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] mt-1",children:o("wiki.selectPlaceholder")})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 max-w-lg mx-auto",children:c.map(x=>{const h=x.icon;return e.jsxs("button",{onClick:()=>s(x.path),className:`text-left p-4 rounded-xl border ${x.color} hover:shadow-sm transition-all group`,children:[e.jsx(h,{size:20,className:"mb-2 opacity-70 group-hover:opacity-100"}),e.jsx("div",{className:"font-medium text-sm",children:x.label}),e.jsx("div",{className:"text-xs opacity-60 mt-0.5",children:x.desc})]},x.path)})}),t&&e.jsxs("div",{className:"mt-8 text-center text-xs text-[var(--fg-muted)]",children:[t.generatedAt&&`${o("wiki.lastGenerated")}: ${new Date(t.generatedAt).toLocaleString()}`,t.duration!=null&&` · ${o("wiki.duration")} ${Hr(t.duration)}`,t.version&&` · v${t.version}`]})]})},tc=()=>{const{t}=Ae(),[s,a]=n.useState({task:{status:"idle"}}),[r,i]=n.useState([]),[o,u]=n.useState(!1),[p,c]=n.useState(null),[x,h]=n.useState(""),[g,d]=n.useState(!1),[l,f]=n.useState(!0),[y,D]=n.useState(""),[S,T]=n.useState(null),z=n.useRef(null),O=n.useCallback(async()=>{try{const C=await ee.wikiStatus();return a(C),C}catch{return null}},[]),G=n.useCallback(async()=>{try{const C=await ee.wikiFiles();i(C.files||[]),u(C.exists)}catch{}},[]),le=n.useCallback(async()=>{try{const C=await ee.wikiFileContent("meta.json");C?.content&&T(JSON.parse(C.content))}catch{}},[]);n.useEffect(()=>{(async()=>(f(!0),await Promise.all([O(),G(),le()]),f(!1)))()},[O,G,le]),n.useEffect(()=>{if(s.task.status==="running"){let C=0;z.current=setInterval(async()=>{const v=await O();C++,C%3===0&&await G(),v&&v.task.status!=="running"&&(await Promise.all([G(),le()]),z.current&&clearInterval(z.current))},1500)}else z.current&&clearInterval(z.current);return()=>{z.current&&clearInterval(z.current)}},[s.task.status,O,G,le]);const w=async()=>{try{await ee.wikiUpdate(),a(C=>({...C,task:{...C.task,status:"running",progress:0,message:t("wiki.incrementalUpdating")}}))}catch(C){console.error("Wiki update failed:",C)}},k=async C=>{if(C!=="meta.json"){c(C),d(!0);try{const v=await ee.wikiFileContent(C);h(v.content)}catch{h(`# ${t("wiki.loadFailed")}
124
+
125
+ ${t("wiki.loadFailedDesc")}`)}finally{d(!1)}}},I=()=>{c(null),h("")},q=n.useMemo(()=>r.filter(C=>C.path!=="meta.json"),[r]),W=n.useMemo(()=>Yi(q,S?.files),[q,S]);if(l)return e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx(Ce,{size:H.xl,className:"text-blue-500 animate-spin"})});const K=!o&&q.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}),K?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(Ce,{size:16,className:"text-blue-600 animate-spin relative"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium text-blue-800",children:t("wiki.wikiGenerating")}),s.task.message&&e.jsx("span",{className:"text-xs text-blue-500 ml-2 truncate",children:s.task.message})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("div",{className:"w-24 bg-blue-100 rounded-full h-1.5",children:e.jsx("div",{className:"bg-blue-500 h-1.5 rounded-full transition-all duration-700 ease-out",style:{width:`${Math.max(s.task.progress||0,3)}%`}})}),e.jsxs("span",{className:"text-xs font-mono text-blue-600 w-8 text-right",children:[s.task.progress||0,"%"]})]})]}),e.jsxs("div",{className:"flex gap-4 flex-1 min-h-0 overflow-hidden",children:[e.jsxs("div",{className:`w-64 flex-shrink-0 bg-[var(--bg-surface)] border border-[var(--border-default)] rounded-xl flex flex-col overflow-hidden ${p?"hidden lg:flex":""}`,children:[e.jsxs("div",{className:"px-3 pt-3 pb-2 border-b border-[var(--border-default)] shrink-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qe,{size:16,className:"text-blue-500"}),e.jsx("span",{className:"text-sm font-semibold text-[var(--fg-primary)]",children:"Wiki"}),S?.version&&e.jsxs("span",{className:"text-[10px] text-[var(--fg-muted)]",children:["v",S.version]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[o&&e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)]",children:t("wiki.fileCount",{count:q.length})}),s.task.status!=="running"&&o&&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(mt,{size:13})})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(ht,{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:y,onChange:C=>D(C.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:W,selectedFile:p,onSelect:k,searchQuery:y}),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(Ce,{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")})]})]}),S?.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(tt,{size:10}),e.jsx("span",{children:Vi(S.generatedAt)}),S.duration!=null&&e.jsxs("span",{children:["· ",Hr(S.duration)]})]})})]}),e.jsx("div",{className:`flex-1 bg-[var(--bg-surface)] border border-[var(--border-default)] rounded-xl overflow-hidden flex flex-col min-h-0 ${p?"":"hidden lg:flex"}`,children:p?e.jsx(Xi,{filePath:p,content:x,loading:g,meta:S,onBack:I}):e.jsx(ec,{meta:S,onSelectFile:k,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:i=!1})=>{const{t:o}=Ae(),[u,p]=n.useState("preview"),c=n.useRef(!0);n.useEffect(()=>()=>{c.current=!1},[]);const x=(()=>{const d=(t.language||"").toLowerCase();return["objectivec","objc","objective-c","obj-c"].includes(d)?"objectivec":t.language||"text"})(),h=async d=>{try{if(await ee.setRecipeAuthority(t.name,d),c.current){const l=t.stats?{...t.stats,authority:d}:{...sc,authority:d};s({...t,stats:l})}}catch(l){console.warn(o("recipeEditor.authorityFailed"),ve(l))}},g=d=>{if(!d)return"";const l=typeof d=="string"?new Date(d).getTime():d;return isNaN(l)?"":new Date(l).toLocaleString("zh-CN",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"})};return e.jsxs(Ve,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx(Ve.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:o("recipeEditor.title")}),t.kind&&(()=>{const l={rule:{label:"Rule",color:"text-red-700",bg:"bg-red-50",border:"border-red-200",icon:at},pattern:{label:"Pattern",color:"text-violet-700",bg:"bg-violet-50",border:"border-violet-200",icon:Ft},fact:{label:"Fact",color:"text-cyan-700",bg:"bg-cyan-50",border:"border-cyan-200",icon:qe}}[t.kind];if(!l)return null;const f=l.icon;return e.jsxs("span",{className:`text-[10px] font-bold px-2 py-1 rounded uppercase flex items-center gap-1 border ${l.bg} ${l.color} ${l.border}`,children:[e.jsx(f,{size:H.sm}),l.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:o("recipeEditor.authorityScore")}),u==="preview"?e.jsx("span",{className:"text-sm text-[var(--fg-primary)]",children:t.stats?.authority??3}):e.jsx(Ze,{value:String(t.stats?.authority??3),onChange:d=>h(parseInt(d)),options:[{value:"1",label:`1 - ${o("recipeEditor.qualityLevels.basic")}`,icon:"⭐"},{value:"2",label:`2 - ${o("recipeEditor.qualityLevels.good")}`,icon:"⭐⭐"},{value:"3",label:`3 - ${o("recipeEditor.qualityLevels.solid")}`,icon:"⭐⭐⭐"},{value:"4",label:`4 - ${o("recipeEditor.qualityLevels.great")}`,icon:"⭐⭐⭐⭐"},{value:"5",label:`5 - ${o("recipeEditor.qualityLevels.excellent")}`,icon:"⭐⭐⭐⭐⭐"}],size:"xs",className:"font-bold text-amber-600 bg-amber-50 border-amber-100"})]}),e.jsxs("div",{className:"flex bg-[var(--bg-subtle)] p-1 rounded-lg mr-4",children:[e.jsxs("button",{onClick:()=>p("preview"),className:`px-4 py-1.5 rounded-md text-xs font-bold transition-all flex items-center gap-2 ${u==="preview"?"bg-[var(--bg-surface)] shadow-sm text-[var(--accent)]":"text-[var(--fg-muted)]"}`,children:[e.jsx(ks,{size:H.sm})," ",o("recipeEditor.preview")]}),e.jsxs("button",{onClick:()=>p("edit"),className:`px-4 py-1.5 rounded-md text-xs font-bold transition-all flex items-center gap-2 ${u==="edit"?"bg-[var(--bg-surface)] shadow-sm text-[var(--accent)]":"text-[var(--fg-muted)]"}`,children:[e.jsx(Et,{size:H.sm})," ",o("recipeEditor.edit")]})]}),e.jsx("button",{onClick:r,className:"p-2 hover:bg-[var(--bg-subtle)] rounded-full",children:e.jsx(Ue,{size:H.lg})})]})]}),e.jsx("div",{className:"p-6 space-y-4 flex-1 flex flex-col overflow-hidden",children:e.jsx("div",{className:"flex-1 flex flex-col min-h-0",children:u==="edit"?e.jsxs("div",{className:"flex-1 overflow-y-auto space-y-5 pr-1",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-[var(--fg-muted)] uppercase mb-1",children:o("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:d=>s({...t,name:d.target.value})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs font-bold text-[var(--fg-muted)] uppercase mb-1",children:o("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:d=>s({...t,description:d.target.value}),placeholder:o("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(ct,{size:11,className:"text-blue-400"})," ",o("recipeEditor.markdown")]}),e.jsx("div",{className:"border border-[var(--border-default)] rounded-lg overflow-hidden",style:{minHeight:180},children:e.jsx(As,{value:t.content?.markdown||"",onChange:d=>s({...t,content:{...t.content,markdown:d}}),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(Ht,{size:11,className:"text-emerald-500"})," ",o("recipeEditor.code")]}),e.jsx("div",{className:"border border-[var(--border-default)] rounded-lg overflow-hidden",style:{minHeight:180},children:e.jsx(As,{value:t.content?.pattern||"",onChange:d=>s({...t,content:{...t.content,pattern:d}}),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:o("recipeEditor.rationale")}),e.jsx("textarea",{className:"w-full px-3 py-2 text-sm border border-[var(--border-default)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)] resize-y",rows:3,value:t.content?.rationale||"",onChange:d=>s({...t,content:{...t.content,rationale:d.target.value}}),placeholder:o("recipeEditor.rationalePlaceholder")})]})]}):e.jsxs("div",{className:"flex-1 overflow-y-auto space-y-6 scrollbar-light",children:[(()=>{const d=[["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(([,l])=>!!l);return d.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:d.map(([l,f])=>e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"text-[10px] text-[var(--fg-muted)] font-bold uppercase mb-1",children:l}),e.jsx("span",{className:"text-sm text-[var(--fg-primary)] break-all font-medium",children:f})]},l))})]})})(),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:o("recipeEditor.description")}),e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] leading-relaxed",children:t.description})]}),t.content?.markdown&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-blue-100 p-6",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-3 block flex items-center gap-1.5",children:[e.jsx(ct,{size:11,className:"text-blue-400"})," ",o("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(Ct,{content:t.content.markdown})})})]}),t.content?.pattern&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-emerald-100 p-6",children:[e.jsxs("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-3 block flex items-center gap-1.5",children:[e.jsx(Ht,{size:11,className:"text-emerald-500"})," ",o("recipeEditor.code")]}),e.jsx(ft,{code:t.content.pattern,language:x,showLineNumbers:!0})]}),t.content?.rationale&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-[var(--border-default)] p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:o("recipeEditor.rationale")}),e.jsx("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-xl p-4",children:e.jsx("p",{className:"text-sm text-[var(--fg-secondary)] leading-relaxed",children:t.content.rationale})})]}),t.content?.steps&&t.content.steps.length>0&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-[var(--border-default)] p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:o("recipeEditor.steps")}),e.jsx("div",{className:"space-y-2",children:t.content.steps.map((d,l)=>typeof d=="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:l+1}),e.jsx("p",{className:"text-xs text-[var(--fg-primary)] leading-relaxed",children:d})]},l):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:l+1}),d.title&&e.jsx("span",{className:"text-xs font-bold text-[var(--fg-primary)]",children:d.title})]}),d.description&&e.jsx("p",{className:"text-xs text-[var(--fg-secondary)] ml-7 leading-relaxed",children:d.description}),d.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:d.code})]},l))})]}),t.content?.codeChanges&&t.content.codeChanges.length>0&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-[var(--border-default)] p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:o("recipeEditor.codeChanges")}),e.jsx("div",{className:"space-y-2",children:t.content.codeChanges.map((d,l)=>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(kt,{size:11,className:"text-blue-400"}),e.jsx("code",{className:"text-[10px] font-mono text-[var(--fg-secondary)]",children:d.file})]}),d.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:d.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:d.before||o("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:d.after})]})]},l))})]}),t.content?.verification&&e.jsxs("div",{className:"bg-[var(--bg-surface)] rounded-2xl border border-teal-100 p-6",children:[e.jsx("label",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase mb-2 block",children:o("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:o("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:o("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(ur,{size:11,className:"text-blue-400"})," ",o("recipeEditor.tags")]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.tags.map((d,l)=>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:d},l))})]}),!!(t.constraints&&(t.constraints.guards?.length||t.constraints.boundaries?.length||t.constraints.preconditions?.length||t.constraints.sideEffects?.length))&&e.jsxs("div",{className:"bg-[var(--bg-subtle)] border border-[var(--border-default)] rounded-2xl p-6 space-y-4",children:[e.jsxs("h3",{className:"text-[10px] font-bold text-[var(--fg-muted)] uppercase tracking-widest flex items-center gap-1.5",children:[e.jsx(at,{size:11,className:"text-amber-500"})," ",o("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:o("recipeEditor.guardRules")}),e.jsx("ul",{className:"text-sm text-[var(--fg-secondary)] space-y-1",children:t.constraints.guards.map((d,l)=>e.jsxs("li",{className:"flex gap-2 items-start",children:[e.jsx("span",{className:`text-xs mt-0.5 ${d.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:d.pattern}),d.message&&e.jsxs("span",{className:"text-xs text-[var(--fg-muted)]",children:["— ",d.message]})]},l))})]}),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:o("recipeEditor.boundaryConstraints")}),e.jsx("ul",{className:"text-sm text-[var(--fg-secondary)] space-y-1",children:t.constraints.boundaries.map((d,l)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-orange-400",children:"●"}),d]},l))})]}),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:o("recipeEditor.preconditions")}),e.jsx("ul",{className:"text-sm text-[var(--fg-secondary)] space-y-1",children:t.constraints.preconditions.map((d,l)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-blue-400",children:"◆"}),d]},l))})]}),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:o("recipeEditor.sideEffects")}),e.jsx("ul",{className:"text-sm text-[var(--fg-secondary)] space-y-1",children:t.constraints.sideEffects.map((d,l)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-pink-400",children:"⚡"}),d]},l))})]})]}),t.relations&&Object.entries(t.relations).some(([,d])=>Array.isArray(d)&&d.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:o("recipeEditor.relations")}),e.jsx("div",{className:"space-y-2",children:[{key:"inherits",label:o("recipeEditor.relationTypes.inherits"),color:"text-green-600",icon:"↑"},{key:"implements",label:o("recipeEditor.relationTypes.implements"),color:"text-blue-600",icon:"◇"},{key:"calls",label:o("recipeEditor.relationTypes.calls"),color:"text-cyan-600",icon:"→"},{key:"dependsOn",label:o("recipeEditor.relationTypes.dependsOn"),color:"text-yellow-600",icon:"⊕"},{key:"dataFlow",label:o("recipeEditor.relationTypes.dataFlow"),color:"text-purple-600",icon:"⇢"},{key:"conflicts",label:o("recipeEditor.relationTypes.conflicts"),color:"text-red-600",icon:"✕"},{key:"extends",label:o("recipeEditor.relationTypes.extends"),color:"text-teal-600",icon:"⊃"},{key:"related",label:o("recipeEditor.relationTypes.associates"),color:"text-[var(--fg-muted)]",icon:"∼"}].map(({key:d,label:l,color:f,icon:y})=>{const D=t.relations?.[d];return!D||!Array.isArray(D)||D.length===0?null:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("span",{className:`text-xs font-mono ${f} shrink-0 whitespace-nowrap pt-0.5`,children:[y," ",l]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:D.map((S,T)=>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 S=="string"?S:S.id||S.title||JSON.stringify(S)},T))})]},d)})})]}),!t.content?.markdown&&!t.content?.pattern&&!t.description&&e.jsx("div",{className:"bg-[var(--bg-surface)] p-8 rounded-2xl border border-[var(--border-default)] shadow-sm min-h-[200px] flex items-center justify-center",children:e.jsx("div",{className:"text-[var(--fg-muted)] italic",children:o("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:i,className:"px-4 py-2 text-[var(--fg-secondary)] font-medium disabled:opacity-50",children:o("recipeEditor.cancel")}),e.jsxs("button",{onClick:a,disabled:i,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:[i?e.jsx(Ce,{size:H.lg,className:"animate-spin"}):e.jsx(Rs,{size:H.lg}),o(i?"recipeEditor.saving":"recipeEditor.saveChanges")]})]})]})]})},rc=({setShowCreateModal:t,createPath:s,setCreatePath:a,handleCreateFromPath:r,handleCreateFromClipboard:i,isExtracting:o})=>{const{t:u}=Ae();return e.jsxs(Ve,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx(Ve.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(gt,{size:H.xl,className:"text-blue-600"})," ",u("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(Ue,{size:H.lg})})]}),e.jsxs("div",{className:"p-8 space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs font-bold uppercase tracking-widest text-[var(--fg-muted)]",children:[e.jsx(Ks,{size:H.sm})," ",u("createModal.importFromPath")]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:"flex-1 p-3 rounded-xl text-sm outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)] border bg-[var(--bg-subtle)] border-[var(--border-default)] text-[var(--fg-primary)]",placeholder:u("createModal.pathPlaceholder"),value:s,onChange:p=>a(p.target.value)}),e.jsxs("button",{onClick:r,disabled:!s||o,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(Ks,{size:14,className:"inline -mt-0.5 mr-1"}),u("createModal.scanFile")]})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("div",{className:"w-full border-t 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:u("createModal.or")})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs font-bold uppercase tracking-widest text-[var(--fg-muted)]",children:[e.jsx(On,{size:H.sm})," ",u("createModal.importFromClipboard")]}),e.jsxs("button",{onClick:()=>i(),disabled:o,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(Ke,{size:H.lg})," ",u("createModal.useClipboard")]})]})]}),o&&e.jsxs("div",{className:"bg-blue-600 text-white p-4 flex items-center justify-center gap-3 animate-pulse",children:[e.jsx(as,{size:H.lg,className:"animate-spin"}),e.jsx("span",{className:"font-bold text-sm",children:u("createModal.aiThinking")})]})]})]})};function nc(t){if(!t)return"";if(typeof t=="object"){const i=t.code||t.pattern||t.markdown||t.snippet||t.body||"";if(i)return i}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}=Ae(),[i,o]=n.useState([]),[u,p]=n.useState(!0),[c,x]=n.useState(null),h=n.useRef(!0),g=n.useRef(null);n.useEffect(()=>(h.current=!0,g.current=new AbortController,ee.search(t||"",{mode:"bm25",type:"recipe",signal:g.current.signal}).then(l=>{h.current&&o((l.items||[]).map(f=>({name:(f.title||f.name||"")+".md",path:"",content:f.content,qualityScore:(f.quality||{}).overall||f.qualityScore||0,recommendReason:""})))}).catch(l=>{l.name!=="AbortError"&&h.current&&o([])}).finally(()=>{h.current&&p(!1)}),()=>{h.current=!1,g.current&&g.current.abort()}),[t]);const d=async l=>{x(l.name);try{const f=nc(l.content);await ee.insertAtSearchMark({path:s,content:f}),h.current&&(alert(r("searchModal.insertSuccess")+" "+s),a())}catch{h.current&&alert(r("searchModal.insertFailed"))}finally{h.current&&x(null)}};return e.jsxs(Ve,{className:"z-40 flex items-center justify-center p-4",children:[e.jsx(Ve.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(ht,{size:H.xl,className:"text-blue-600"})," ",r("searchModal.title")]}),e.jsx("button",{onClick:a,className:"p-2 hover:bg-[var(--bg-surface)] rounded-full transition-colors",children:e.jsx(Ue,{size:H.lg})})]}),e.jsxs("div",{className:"p-4 text-sm text-[var(--fg-muted)] border-b border-[var(--border-default)]",children:[r("searchModal.keyword")," ",t||r("searchModal.keywordAll")," · ",r("searchModal.insertTo")," ",s]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:u?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"})}):i.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:i.map(l=>e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>d(l),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:l.name}),(l.qualityScore!==void 0||l.recommendReason)&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[l.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")," ",(l.qualityScore*100).toFixed(0),"%"]}),l.recommendReason&&e.jsx("span",{className:"text-xs text-[var(--fg-secondary)] italic truncate max-w-xs",children:l.recommendReason})]})]}),c===l.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(gr,{size:H.md})," ",r("searchModal.insertBtn")]})]})},l.name))})})]})]})},Hs=[{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}=Ae(),[r,i]=n.useState(!0),[o,u]=n.useState(!1),[p,c]=n.useState(!1),[x,h]=n.useState("google"),[g,d]=n.useState("gemini-2.0-flash"),[l,f]=n.useState(""),[y,D]=n.useState(""),[S,T]=n.useState(!1),[z,O]=n.useState({}),[G,le]=n.useState(!1);n.useEffect(()=>{w()},[]);const w=async()=>{i(!0);try{const v=await ee.getLlmEnvConfig();c(v.hasEnvFile);const _=v.vars||{};_.ASD_AI_PROVIDER&&h(_.ASD_AI_PROVIDER),_.ASD_AI_MODEL&&d(_.ASD_AI_MODEL),_.ASD_AI_PROXY&&D(_.ASD_AI_PROXY),O(_)}catch{}finally{i(!1)}},k=Hs.find(v=>v.id===x),I=k?.keyEnv||"",q=I?!!z[I]:!0,W=v=>{h(v);const _=Hs.find(ae=>ae.id===v);_&&d(_.defaultModel),f("")},K=async()=>{if(x){if(I&&!q&&!l.trim()){alert(a("llmConfig.apiKeyRequired"));return}u(!0),le(!1);try{await ee.saveLlmEnvConfig({provider:x,model:g||void 0,apiKey:l.trim()||void 0,proxy:y.trim()||void 0}),le(!0),setTimeout(()=>{s(),t()},800)}catch(v){alert(ve(v,a("llmConfig.saveFailed")))}finally{u(!1)}}},C=v=>!v||v.length<10?v?"••••••":"":`${v.slice(0,6)}••••${v.slice(-4)}`;return e.jsx("div",{className:"fixed inset-0 bg-black/40 flex items-center justify-center z-50",onClick:t,children:e.jsxs("div",{className:"rounded-2xl shadow-2xl w-full max-w-lg mx-4 overflow-hidden bg-[var(--bg-surface)]",onClick:v=>v.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-[var(--border-default)]",children:[e.jsx("h2",{className:"text-lg font-semibold text-[var(--fg-primary)]",children:a("llmConfig.title")}),e.jsx("button",{onClick:t,className:"p-1 rounded-lg transition-all duration-150 hover:bg-[var(--bg-subtle)] text-[var(--fg-muted)] hover:text-[var(--fg-primary)]",children:e.jsx(Ue,{size:H.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(Ce,{size:24,className:"animate-spin text-blue-500"})}):e.jsxs(e.Fragment,{children:[!p&&e.jsxs("div",{className:"flex items-start gap-2 p-3 bg-amber-50 border border-amber-200 rounded-lg text-sm text-amber-700",children:[e.jsx(It,{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:Hs.map(v=>e.jsx("button",{type:"button",onClick:()=>W(v.id),className:`px-3 py-2 rounded-lg text-sm font-medium border transition-all ${x===v.id?"bg-[var(--accent-subtle)] border-[var(--accent-emphasis)] text-[var(--accent)] ring-1 ring-[var(--accent-emphasis)]/30":"bg-[var(--bg-surface)] border-[var(--border-default)] text-[var(--fg-secondary)] hover:border-[var(--border-emphasis)] hover:bg-[var(--bg-subtle)]"}`,children:a(v.labelKey)},v.id))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5 text-[var(--fg-primary)]",children:a("llmConfig.model")}),e.jsx("input",{type:"text",value:g,onChange:v=>d(v.target.value),placeholder:k?.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)]"})]}),I&&e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium mb-1.5 text-[var(--fg-primary)]",children:[a("llmConfig.apiKey"),q&&e.jsxs("span",{className:"ml-2 text-xs text-green-600 font-normal",children:["(",a("llmConfig.configured")," ",C(z[I]),")"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:S?"text":"password",value:l,onChange:v=>f(v.target.value),placeholder:a(q?"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:()=>T(v=>!v),className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-[var(--fg-muted)] hover:text-[var(--fg-secondary)]",children:S?e.jsx(Kn,{size:16}):e.jsx(ks,{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:y,onChange:v=>D(v.target.value),placeholder:"http://127.0.0.1:7890",className:"w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[var(--accent-emphasis)]/20 focus:border-[var(--accent-emphasis)] border-[var(--border-default)] bg-[var(--bg-subtle)] text-[var(--fg-primary)]"})]})]})}),e.jsxs("div",{className:"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:K,disabled:o||r||G,className:`flex items-center gap-2 px-5 py-2 rounded-lg text-sm font-medium transition-all ${G?"bg-green-500 text-white":"bg-blue-600 text-white hover:bg-blue-700 shadow-sm"} disabled:opacity-60`,children:[o?e.jsx(Ce,{size:16,className:"animate-spin"}):G?e.jsx(rs,{size:16}):e.jsx(Rs,{size:16}),a(G?"llmConfig.saved":"llmConfig.saveToEnv")]})]})]})})};class ic extends St.Component{constructor(s){super(s),this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}render(){return this.state.hasError?e.jsxs("div",{style:{padding:40,textAlign:"center"},children:[e.jsx("h2",{style:{color:"#ef4444",marginBottom:12},children:Vs.app.errorBoundary.title}),e.jsx("pre",{style:{fontSize:12,color:"#64748b",whiteSpace:"pre-wrap",maxWidth:600,margin:"0 auto"},children:this.state.error?.message}),e.jsx("button",{onClick:()=>{this.setState({hasError:!1,error:null}),window.location.reload()},style:{marginTop:16,padding:"8px 20px",background:"#3b82f6",color:"#fff",border:"none",borderRadius:8,cursor:"pointer"},children:Vs.app.errorBoundary.refreshBtn})]}):this.props.children}}function Xt(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=()=>{const t=yl(),s=wl(t.user?.role),a=Nl(),{t:r}=Ae(),i=()=>{const R=window.location.pathname.replace(/^\//,"").split("/")[0]||"";return cl.includes(R)?R:"help"},[o,u]=n.useState(null),[p,c]=n.useState(i()),[x,h]=n.useState(""),[g,d]=n.useState(!1),[l,f]=n.useState(!0),[y,D]=n.useState(null),[S,T]=n.useState([]),[z,O]=n.useState([]),[G,le]=n.useState(null),[w,k]=n.useState(!1),[I,q]=n.useState({current:0,total:0,status:""}),[W,K]=n.useState([]),[C,v]=n.useState([]),[_,ae]=n.useState(null),[Q,me]=n.useState(1),[Se,ye]=n.useState(12),[j,N]=n.useState(!1),[P,V]=n.useState(""),[ne,ue]=n.useState(!1),[pe,Ne]=n.useState(null),[De,ke]=n.useState(null),[Me,M]=n.useState(!1),[A,L]=n.useState(!0),[oe,be]=n.useState(!1),[Te,ce]=n.useState(0),ge=n.useRef(null),Ee=n.useRef(null);n.useEffect(()=>{me(1)},[x]),n.useEffect(()=>{if(o?.projectRoot)try{const R=`asd:custom-folder-targets:${o.projectRoot}`,X=localStorage.getItem(R);O(X?JSON.parse(X):[])}catch{O([])}},[o?.projectRoot]);const J=()=>{ge.current&&ge.current.abort()};n.useEffect(()=>{let R=!1;const X=async()=>{try{const ie=await ee.getSignalStatus();if(!R){const xe=ie?.suggestions?.length||0,Ie=ie?.snapshot?.lastResult?.newSuggestions||0;ce(xe||Ie)}}catch{}};X();const se=setInterval(X,300*1e3);return()=>{R=!0,clearInterval(se)}},[]);const U=n.useRef(null);n.useEffect(()=>{if(a.isAllDone&&a.session){if(U.current!==a.session.id){U.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});Z(R,{title:r("bootstrap.coldStartComplete"),type:a.session.failed>0?"error":"success"})}F()}},[a.isAllDone,a.session?.id]),n.useEffect(()=>{if(a.candidateCreatedTick>0){const R=setTimeout(()=>F(),2e3);return()=>clearTimeout(R)}},[a.candidateCreatedTick]);const m=(R,X)=>{c(R);const se=X?.preserveSearch&&window.location.search?window.location.search:"";window.history.pushState({},document.title,`/${R}${se}`)},b=R=>{D(R),c("recipes");const X=new URLSearchParams(window.location.search);X.set("edit",encodeURIComponent(R.name)),window.history.pushState({},document.title,`/recipes?${X.toString()}`)},B=()=>{D(null),window.history.replaceState({},document.title,"/recipes")};n.useEffect(()=>{x===""&&Ne(null)},[x]),n.useEffect(()=>{c(i())},[]),n.useEffect(()=>{if(!o)return;const R=window.location.pathname.replace(/^\//,"").split("/")[0],se=new URLSearchParams(window.location.search).get("edit");if(R==="recipes"&&se&&o.recipes)try{const ie=decodeURIComponent(se),xe=o.recipes.find(Ie=>Ie.name===ie);xe&&!y&&(c("recipes"),b(xe))}catch{}},[o]),n.useEffect(()=>{F(),$(),E();const R=()=>{c(i())};window.addEventListener("popstate",R);const X=new URLSearchParams(window.location.search),se=X.get("action"),ie=X.get("path"),xe=X.get("q")||"";return se==="search"&&ie?ke({q:xe,path:ie}):se==="create"&&ie&&(V(ie),N(!0),X.get("autoScan")==="1"&&setTimeout(()=>je(ie),500)),se&&window.history.replaceState({},document.title,window.location.pathname),()=>{window.removeEventListener("popstate",R)}},[]);const F=async()=>{f(!0);try{const R=await ee.fetchData();u(R)}catch(R){Z(ve(R,r("app.load.failed")),{title:r("app.load.failedTitle"),type:"error"})}finally{f(!1)}},$=async()=>{try{const R=await ee.fetchTargets();T(R)}catch(R){console.warn("删除候选残留失败:",ve(R))}},E=async()=>{try{const R=await ee.getLlmEnvConfig();L(R.llmReady)}catch{}},te=async()=>{try{await ee.syncSnippets("all"),Z(r("app.sync.success"),{title:r("app.sync.successTitle")})}catch{Z(r("app.sync.failedHint"),{title:r("app.sync.failed"),type:"error"})}},fe=async()=>{try{await ee.refreshProject(),$(),Z(r("app.projectRefresh.success"),{title:r("app.projectRefresh.successTitle")})}catch{Z(r("app.load.failedHint"),{title:r("app.projectRefresh.failed"),type:"error"})}},je=async R=>{ue(!0);try{const X=await ee.extractFromPath(R);v(X.result.map(se=>({...Xt(se,"extract"),mode:"full",lang:"cn"}))),m("spm"),N(!1),F(),X.result?.length>0&&Z(r("app.extract.success"),{title:r("app.extract.successTitle")})}catch{Z(r("app.extract.failed"),{type:"error"})}finally{ue(!1)}},Pe=async()=>{if(P){ue(!0);try{const R=await ee.extractFromPath(P);v(R.result.map(X=>({...Xt(X,"extract"),mode:"full",lang:"cn"}))),m("spm"),N(!1),F(),R.result?.length>0?Z(R.isMarked?r("app.extract.markerSuccess"):r("app.extract.normalSuccess"),{title:r("app.extract.successTitle")}):R.isMarked||Z(r("app.extract.noMarker"),{title:r("app.extract.extracting"),type:"info"})}catch{Z(r("app.extract.failed"),{type:"error"})}finally{ue(!1)}}},Le=async R=>{try{const X=await navigator.clipboard.readText();if(!X)return Z(r("app.clipboard.empty"),{title:r("app.clipboard.emptyTitle"),type:"info"});Z(r("app.clipboard.analyzing"),{title:r("app.clipboard.analyzingTitle"),type:"info"}),ue(!0);const se=R||P;try{const ie=await ee.extractFromText(X,se||void 0),xe=ie._multipleCount;v([{...Xt(ie,"clipboard"),mode:"full",lang:"cn"}]),m("spm"),N(!1),F(),Z(xe?r("app.clipboard.resultMulti",{count:xe}):r("app.extract.normalSuccess"),{title:r("app.clipboard.resultTitle")})}catch(ie){const xe=ve(ie);gl(ie)?Z(xe,{title:r("app.clipboard.aiFailed"),type:"error"}):Z(xe,{title:r("common.operationFailed"),type:"error"})}}catch{Z(r("app.clipboard.permissionError"),{title:r("app.clipboard.permissionTitle"),type:"error"})}finally{ue(!1)}},de={"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")}},Oe=async R=>{if(w)return;ge.current&&ge.current.abort(),Ee.current&&(clearInterval(Ee.current),Ee.current=null);const X=new AbortController;ge.current=X,le(R.name),k(!0),v([]),ae(null),K([]),q({current:0,total:100,status:r("app.scan.streamInit")});try{const se=await ee.scanTargetStream(R,Ie=>{const ze=de[Ie.type];if(ze){const $e=typeof ze.status=="function"?ze.status(Ie):ze.status;q({current:ze.percent,total:100,status:$e})}Ie.type==="scan:files-loaded"&&Ie.files&&K(Ie.files),Ie.type==="scan:ai-extracting"&&(Ee.current&&clearInterval(Ee.current),Ee.current=setInterval(()=>{q($e=>({...$e,current:Math.min($e.current+1,80)}))},3e3)),(Ie.type==="scan:enriching"||Ie.type==="scan:completed")&&Ee.current&&(clearInterval(Ee.current),Ee.current=null)},X.signal);Ee.current&&(clearInterval(Ee.current),Ee.current=null),q({current:100,total:100,status:r("app.scan.completed")});const ie=se.recipes||[],xe=se.scannedFiles||[];if(ie.length>0||xe.length>0){const Ie=typeof R=="string"?R:R?.name||"unknown",ze=ie.map($e=>({...Xt($e,"ai-scan"),mode:"full",lang:"cn",candidateTargetName:Ie,scanMode:"target"}));if(v(ze),xe.length>0&&K(xe),F(),ie.length>0)Z(r("app.scan.targetSuccess",{count:ie.length}),{title:r("app.scan.targetSuccessTitle")});else if(se.message){const $e=se.noAi;Z(se.message,{title:r($e?"app.scan.aiNotConfigured":"app.scan.noResults"),type:$e?"info":"error"})}else Z(r("app.scan.noSnippets"),{title:r("app.scan.scanComplete"),type:"info"})}else Z(r("app.scan.scanFailedHint"),{title:r("app.scan.scanFailed"),type:"error"})}catch(se){if(Ee.current&&(clearInterval(Ee.current),Ee.current=null),Cs(se))return;const ie=Ls(se),xe=ie?r("app.scan.timeout"):ve(se,r("app.scan.scanError"));Z(xe,{title:r(ie?"app.scan.timeoutTitle":"app.scan.scanError"),type:"error"})}finally{ge.current===X&&(k(!1),q({current:0,total:0,status:""}),ge.current=null)}},Be=async()=>{if(w)return;ge.current&&ge.current.abort();const R=new AbortController;ge.current=R,m("candidates"),k(!0),v([]),ae(null),K([]),q({current:0,total:100,status:r("app.coldStart.collecting")}),a.resetSession();try{const X=await ee.bootstrap(R.signal);q({current:100,total:100,status:r("app.coldStart.skeletonCreated")}),X.bootstrapSession&&a.initFromApiResponse(X.bootstrapSession),F();const se=X.report||{},ie=X.targets?.length||0,xe=se.totals?.files||0,Ie=se.totals?.graphEdges||0,ze=X.guardSummary,$e=ze?`, ${r("app.coldStart.guardSuffix",{count:ze.totalViolations})}`:"";Z(r("app.coldStart.skeletonDetail",{targets:ie,files:xe,deps:Ie})+$e)}catch(X){if(wa(X))return;const ie=Ls(X)?r("app.coldStart.timeout"):ve(X);Z(ie,{type:"error"})}finally{ge.current===R&&(k(!1),q({current:0,total:0,status:""}),ge.current=null)}},Y=async()=>{if(w)return;ge.current&&ge.current.abort();const R=new AbortController;ge.current=R,m("spm"),le("__project__"),k(!0),v([]),ae(null),K([]),q({current:0,total:100,status:r("app.fullScan.collecting")});const X=[{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 se=0;const ie=setInterval(()=>{se=Math.min(se+1,X.length);const xe=X[se-1];xe&&q(Ie=>({...Ie,current:xe.percent,status:xe.status}))},15e3);try{const xe=await ee.scanProject(R.signal);clearInterval(ie),q({current:100,total:100,status:xe.partial?r("app.fullScan.partialComplete"):r("app.fullScan.completed")});const Ie=xe.recipes||[],ze=xe.scannedFiles||[];if(Ie.length>0||ze.length>0){const $e=Ie.map(Ur=>({...Xt(Ur,"ai-scan"),mode:"full",lang:"cn",candidateTargetName:"__project__",scanMode:"project"}));v($e),K(ze),ae(xe.guardAudit||null),F();const lt=xe.guardAudit?.summary,ls=lt?`, ${r("app.fullScan.guardSuffix",{count:lt.totalViolations})}`:"",Ut=xe.partial?r("app.fullScan.timeoutSuffix"):"";Z(r("app.fullScan.resultDetail",{count:Ie.length})+ls+Ut)}else Z(r("app.fullScan.noContent"))}catch(xe){if(clearInterval(ie),wa(xe))return;const ze=Ls(xe)?r("app.fullScan.timeout"):ve(xe);Z(ze,{type:"error"})}finally{ge.current===R&&(k(!1),q({current:0,total:0,status:""}),ge.current=null)}},_e=(R,X)=>{const se=[...C],ie={...se[R],...X};se[R]=ie,v(se)},dt=async R=>{if(!Me){M(!0);try{const X=(R.content?.pattern||"").trim(),se=(()=>{if(!X)return!1;const lt=X.split(`
126
+ `).filter(Ut=>Ut.trim());return lt.filter(Ut=>/^\s*(#{1,6}\s|[-*>]\s|\d+\.\s)/.test(Ut)).length<=lt.length*.3})(),ie=(R.trigger||"").split(/[,,\s]+/).map(lt=>lt.trim()).filter(Boolean);if(se&&ie.length===0){Z(r("app.recipe.triggerRequired"),{type:"error"}),M(!1);return}const xe={title:R.title||"Untitled",description:R.description||"",trigger:ie.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},Ie=await ee.knowledgeCreate(xe);if(Ie?.id)try{await ee.knowledgeLifecycle(Ie.id,"publish")}catch(lt){console.warn("auto-publish after save failed:",lt)}Z(r(se?"app.recipe.savedAsRecipe":"app.recipe.savedToKb")),v(lt=>lt.filter(ls=>ls.title!==R.title));const ze=R.candidateTargetName,$e=R.candidateId;if(ze&&$e)try{await ee.deleteCandidate($e)}catch{}F()}catch(X){const se=ja(X)??bs(X);Z(se??r("app.recipe.saveFailed"),{type:"error"})}finally{M(!1)}}},bt=async()=>{if(!(!y||Me)){M(!0);try{const R=y.id||y.name?.replace(/\.md$/,""),X=typeof y.content=="string"?{pattern:y.content,markdown:"",rationale:"",steps:[],codeChanges:[],verification:null}:y.content||{};await ee.knowledgeUpdate(R,{title:y.name?.replace(/\.md$/,"")||"",description:y.description||"",content:X,tags:y.tags||[],kind:y.kind,language:y.language,category:y.category}),B(),F()}catch(R){const X=ja(R)??bs(R);Z(X??r("app.recipe.saveRecipeFailed"),{type:"error"})}finally{M(!1)}}},zt=async R=>{if(window.confirm(r("common.areYouSure")))try{await ee.deleteRecipe(R),F()}catch(X){const se=bs(X);Z(se??r("common.deleteFailed"),{type:"error"})}},Re=async(R,X)=>{try{await ee.deleteCandidate(X),v(se=>se.filter(ie=>!(ie.candidateId===X&&ie.candidateTargetName===R))),u(se=>{if(!se?.candidates)return se;const ie={...se.candidates};if(ie[R]){const xe=ie[R].items.filter(Ie=>Ie.id!==X);xe.length===0?delete ie[R]:ie[R]={...ie[R],items:xe}}return{...se,candidates:ie}})}catch{Z(r("common.operationFailed"),{type:"error"})}},nt=async R=>{if(window.confirm(r("app.candidate.clearConfirm",{name:R})))try{await ee.deleteAllCandidatesInTarget(R),F(),Z(r("app.candidate.clearDone",{name:R}))}catch{Z(r("common.operationFailed"),{type:"error"})}},Xe=async(R,X)=>{try{await ee.promoteToCandidate(R,R.candidateTargetName||G||"_review"),Z(r("app.candidate.pushSuccess")),v(se=>se.filter((ie,xe)=>xe!==X)),F()}catch(se){Z(ve(se,r("app.candidate.pushFailed")),{type:"error"})}},We=(o?.recipes||[]).filter(R=>{if(pe)return pe.some(xe=>xe.metadata.type==="recipe"&&xe.metadata.name===R.name);const X=R.name||"",se=typeof R.content=="string"?R.content:[R.content?.pattern,R.content?.markdown].filter(Boolean).join(" ");return X.toLowerCase().includes(x.toLowerCase())||se.toLowerCase().includes(x.toLowerCase())||(R.description||"").toLowerCase().includes(x.toLowerCase())}).sort((R,X)=>{if(pe){const xe=pe.find(ze=>ze.metadata.name===R.name)?.similarity||0;return(pe.find(ze=>ze.metadata.name===X.name)?.similarity||0)-xe}const se=R.stats?.authorityScore??0;return(X.stats?.authorityScore??0)-se}),Je=St.useMemo(()=>{const R=new Set(S.map(se=>`${se.discovererId||""}::${se.name}`)),X=z.filter(se=>!R.has(`${se.discovererId||""}::${se.name}`));return[...S,...X]},[S,z]),Or=Je.filter(R=>R.name.toLowerCase().includes(x.toLowerCase())).sort((R,X)=>{const se=os(R.name),ie=os(X.name);if(se&&!ie)return 1;if(!se&&ie)return-1;const xe=R.isVirtual?1:0,Ie=X.isVirtual?1:0;return xe!==Ie?xe-Ie:R.name.localeCompare(X.name)}),Kr=n.useCallback(R=>{O(X=>{if(X.some(ie=>ie.path===R.path))return X;const se=[...X,R];return o?.projectRoot&&localStorage.setItem(`asd:custom-folder-targets:${o.projectRoot}`,JSON.stringify(se)),se})},[o?.projectRoot]),qr=n.useCallback(R=>{O(X=>{const se=X.filter(ie=>ie.path!==R);return o?.projectRoot&&localStorage.setItem(`asd:custom-folder-targets:${o.projectRoot}`,JSON.stringify(se)),se})},[o?.projectRoot]),Es=Object.values(o?.candidates||{}).reduce((R,X)=>R+X.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:p,navigateToTab:m,candidateCount:Es,signalSuggestionCount:Te,currentUser:s.user!=="anonymous"?s.user:void 0,currentRole:s.role,permissionMode:s.mode,onLogout:void 0,projectName:o?.projectName}),e.jsxs("main",{className:"flex-1 flex flex-col overflow-hidden relative",children:[e.jsx(Zl,{setShowCreateModal:N,handleSyncSnippets:te,aiConfig:o?.aiConfig,llmReady:A,onOpenLlmConfig:()=>be(!0),onBeforeAiSwitch:J,onAiConfigChange:F,activeTab:p,onOpenCommandPalette:()=>d(!0),projectName:o?.projectName,candidateCount:Es}),e.jsx("div",{className:`flex-1 ${p==="wiki"?"overflow-hidden":"overflow-y-auto p-4 xl:p-6 2xl:p-8"}`,children:e.jsx(qn,{mode:"wait",children:e.jsx(Un.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:l?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-[var(--accent-emphasis)]"})}):p==="recipes"?e.jsx(Ko,{recipes:We,openRecipeEdit:b,handleDeleteRecipe:zt,onRefresh:F,idTitleMap:o?.idTitleMap,currentPage:Q,onPageChange:me,pageSize:Se,onPageSizeChange:R=>{ye(R),me(1)}}):p==="guard"?e.jsx(fi,{onRefresh:F}):p==="skills"?e.jsx(Fi,{onRefresh:F,signalSuggestionCount:Te,onSuggestionCountChange:ce}):p==="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:o,isShellTarget:os,isSilentTarget:ul,isPendingTarget:pl,handleDeleteCandidate:Re,onEditRecipe:b,onColdStart:Be,isScanning:w,isBootstrapping:a.session?.status==="running",onRefresh:F,onAuditCandidate:(R,X)=>{const se=(R.content?.pattern||"").trim(),ie=!!se&&(()=>{const xe=se.split(`
127
+ `).filter(ze=>ze.trim());return xe.filter(ze=>/^\s*(#{1,6}\s|[-*>]\s|\d+\.\s)/.test(ze)).length<=xe.length*.3})();v([{...R,mode:ie?"full":"preview",lang:"cn",includeHeaders:!0,difficulty:R.difficulty||R.complexity||"intermediate",authority:R.stats?.authority||3,candidateId:R.id,candidateTargetName:X}]),m("spm")},onAuditAllInTarget:(R,X)=>{v(R.map(se=>{const ie=(se.content?.pattern||"").trim(),xe=!!ie&&(()=>{const Ie=ie.split(`
128
+ `).filter($e=>$e.trim());return Ie.filter($e=>/^\s*(#{1,6}\s|[-*>]\s|\d+\.\s)/.test($e)).length<=Ie.length*.3})();return{...se,mode:xe?"full":"preview",lang:"cn",includeHeaders:!0,difficulty:se.difficulty||se.complexity||"intermediate",authority:se.stats?.authority||3,candidateId:se.id,candidateTargetName:X}})),m("spm")},handleDeleteAllInTarget:nt})]}):p==="knowledge"?e.jsx(_i,{onRefresh:fe,idTitleMap:o?.idTitleMap}):p==="depgraph"?e.jsx(hi,{}):p==="knowledgegraph"?e.jsx(Ti,{}):p==="spm"?e.jsx(di,{targets:Je,filteredTargets:Or,selectedTargetName:G,isScanning:w,scanProgress:I,scanFileList:W,scanResults:C,guardAudit:_,handleScanTarget:Oe,handleScanProject:Y,handleUpdateScanResult:_e,handleSaveExtracted:dt,handlePromoteToCandidate:Xe,handleDeleteCandidate:Re,onEditRecipe:b,isShellTarget:os,recipes:o?.recipes??[],isSavingRecipe:Me,handleRefreshProject:fe,onAddCustomFolder:Kr,onRemoveCustomFolder:qr}):p==="wiki"?e.jsx(tc,{}):p==="help"?e.jsx(Vo,{}):e.jsx(yi,{})},p)})}),y&&e.jsx(ac,{editingRecipe:y,setEditingRecipe:D,handleSaveRecipe:bt,closeRecipeEdit:B,isSavingRecipe:Me}),j&&e.jsx(rc,{setShowCreateModal:N,createPath:P,setCreatePath:V,handleCreateFromPath:Pe,handleCreateFromClipboard:Le,isExtracting:ne}),De&&e.jsx(lc,{searchQ:De.q,insertPath:De.path,onClose:()=>{ke(null),window.history.replaceState({},document.title,window.location.pathname)}}),oe&&e.jsx(oc,{onClose:()=>be(!1),onSaved:()=>{E(),F()}})]}),e.jsx(dc,{}),e.jsx(no,{open:g,onOpenChange:d,navigateToTab:m,setShowCreateModal:N,handleSyncSnippets:te,searchQuery:x,setSearchQuery:h,onOpenLlmConfig:()=>be(!0),candidateCount:Es})]})})})},dc=()=>{const{isOpen:t}=ns();return t?e.jsx(Kl,{}):null};pn.createRoot(document.getElementById("root")).render(e.jsx(St.StrictMode,{children:e.jsx(Zn,{children:e.jsx(Yn,{children:e.jsx(cc,{})})})}));