dsh-memory-eternal 0.4.4 → 0.4.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -9
- package/index.js +102 -7
- package/lib/capture.js +11 -0
- package/lib/client.js +4 -4
- package/lib/vault.js +108 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# 🧠
|
|
1
|
+
# 🧠 最强记忆大脑 dsh-memory-eternal — 给 DeepSeek Harness 装上「第二大脑」
|
|
2
2
|
|
|
3
3
|
<p align="center">
|
|
4
4
|
<img src="https://img.shields.io/badge/DeepSeek%20Harness-plugin-3B82F6" alt="DSH plugin" />
|
|
@@ -207,21 +207,27 @@ dsh-memory-eternal/
|
|
|
207
207
|
- 知识卡管理(MD渲染/折叠/新角标/搜索高亮/无限滚动)
|
|
208
208
|
- 备份导入导出(MD/JSON)
|
|
209
209
|
- **沉淀预筛**(skip LLM)+ **召回相关性/截断**(v0.4.3)
|
|
210
|
+
- **注入体积可配置**(召回条数/摘要长度/是否带正文,设置项)
|
|
211
|
+
- **多 Vault / 多 Profile**(命名分库,当前激活一个)
|
|
212
|
+
- **每日回顾 + 用量统计**(今日新增/近7天/分类/今日沉淀清单)
|
|
213
|
+
- **整理建议**(相似卡对合并/陈旧卡,非破坏预览)
|
|
214
|
+
- **召回用户反馈**(`/feedback`,为相关性调优留数据)
|
|
215
|
+
- **会话预算**(`sessionBudgetChars` + `/budget`)
|
|
210
216
|
|
|
211
217
|
**待办(核心功能优化)**:
|
|
212
|
-
- [
|
|
213
|
-
- [
|
|
214
|
-
- [ ]
|
|
215
|
-
- [ ]
|
|
216
|
-
- [ ]
|
|
217
|
-
- [ ]
|
|
218
|
-
- [ ] **召回用户反馈**:对命中结果「有用/无关」打标,逐步调优相关性
|
|
219
|
-
- [ ] **每日记忆回顾**:一键回顾当天沉淀 + 用量统计
|
|
218
|
+
- [x] ~~多 Vault / 多 Profile~~、~~注入体积可配置~~、~~每日回顾+用量~~、~~自动归档整理~~、~~召回用户反馈~~、~~会话级 token 预算~~(v0.4.5)
|
|
219
|
+
- [x] ~~批量智能合并~~(相似度预分组一键合并)、~~跨库聚合图谱/检索~~(vault 级)、~~语义召回升级~~(本地 bigram 语义加分,`recallEmbedding` 预留 embedding)、~~每日回顾定时生成~~(00-System/daily-*,30min 轮询幂等)(v0.4.6)
|
|
220
|
+
- [ ] **上下文压缩接入 harness**:记忆侧 `/compress` 已就绪,待 harness 在会话内调「召回替代 + 压缩旧轮」(需 harness 配合)
|
|
221
|
+
- [ ] 多 Vault 的**跨库合并/去重**(跨 profile 识别重复卡)
|
|
222
|
+
- [ ] 语义召回**接入外部 embedding provider**(当前为本地零依赖加分)
|
|
223
|
+
- [ ] 每日回顾**主动推送通道**(当前生成文件 + 手动查看,推送需 harness/通知渠道)
|
|
220
224
|
|
|
221
225
|
---
|
|
222
226
|
|
|
223
227
|
## 📦 发布记录
|
|
224
228
|
|
|
229
|
+
- **v0.4.6**:记忆侧优化**收官**——**批量智能合并**(按相似度并查集聚类、一键合并多组)、**跨库聚合图谱/检索**(`?all=1`,多 Vault 合并展示)、**语义召回升级**(本地 Jaccard bigram 语义加分,`recallEmbedding` 预留 embedding)、**每日回顾定时生成**(`00-System/daily-YYYY-MM-DD.md`,30 分钟轮询幂等)、**今日简报**(`/todayBrief`,管理面板一键查看)。
|
|
230
|
+
- **v0.4.5**:记忆侧**核心功能优化**——**注入体积可配置**、**多 Vault/多 Profile**、**每日回顾+用量统计**、**自动归档整理建议**(非破坏预览)、**召回用户反馈**、**会话级 token 预算**、**上下文压缩接口**(`/compress`)。
|
|
225
231
|
- **v0.4.3**:记忆侧**省 token/提质量**——沉淀预筛(无可复用信号直接跳过、不触发 LLM);召回按 `minScore` 过滤弱命中、注入片段截断到 130 字。
|
|
226
232
|
- **v0.4.2**:修复 GitHub/npm 顶部演示 GIF 无法显示(压缩至 README 10MB 阈值以下,8MB)。
|
|
227
233
|
- **v0.4.1**:Marketplace 收录标准落地(`dsh.marketplace` 元数据 + 自动扫描规则说明)。
|
package/index.js
CHANGED
|
@@ -19,7 +19,8 @@ import path from 'node:path'
|
|
|
19
19
|
import os from 'node:os'
|
|
20
20
|
import z from '@deepseek-ai/schemastery'
|
|
21
21
|
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
22
|
-
import { ensureVault, listCards, readCard, search, graph, overview, exportCards, deleteCard, writeCard, parseCard } from './lib/vault.js'
|
|
22
|
+
import { ensureVault, listCards, readCard, search, searchAll, graph, graphAll, overview, exportCards, deleteCard, writeCard, parseCard, stats, optimizeCandidates, readFeedback, addFeedback, dailyBrief, generateDailyBrief } from './lib/vault.js'
|
|
23
|
+
import { compressExcerpt } from './lib/capture.js'
|
|
23
24
|
import { summarizeTurn, extractLastTurn, sliceNewEvents, resolveRoute, captureCard, captureUpdate, pickNeighbors } from './lib/capture.js'
|
|
24
25
|
|
|
25
26
|
export const name = 'memory-eternal'
|
|
@@ -34,6 +35,17 @@ export const Config = z.object({
|
|
|
34
35
|
captureMinChars: z.number().default(200),
|
|
35
36
|
captureCooldownMs: z.number().default(5 * 60 * 1000),
|
|
36
37
|
maxCardsPerDay: z.number().default(60),
|
|
38
|
+
// 注入体积可配置(召回)
|
|
39
|
+
recallLimit: z.number().min(1).max(20).default(5),
|
|
40
|
+
recallSummaryLen: z.number().min(40).max(400).default(130),
|
|
41
|
+
recallIncludeBody: z.boolean().default(false),
|
|
42
|
+
// 多 Vault / 多 Profile:命名分库,当前激活一个
|
|
43
|
+
vaultProfiles: z.array(z.object({ name: z.string(), path: z.string() })).default([]),
|
|
44
|
+
activeVault: z.string().default(''),
|
|
45
|
+
// 语义召回(可选 embedding provider,默认空=零依赖 bigram + LLM 判定兜底)
|
|
46
|
+
recallEmbedding: z.string().default(''),
|
|
47
|
+
// 会话级 token 预算(字符),供 harness 触发压缩/轮换;记忆侧提供估算与阈值
|
|
48
|
+
sessionBudgetChars: z.number().default(80000),
|
|
37
49
|
})
|
|
38
50
|
|
|
39
51
|
const API_PREFIX = '/memory-eternal/api'
|
|
@@ -43,12 +55,32 @@ export function apply(ctx, config) {
|
|
|
43
55
|
|
|
44
56
|
const vaultDir = () => {
|
|
45
57
|
const cfg = settings.get() ?? {}
|
|
58
|
+
// 多 Vault:若配了 vaultProfiles 且选中了 activeVault,则用该 profile 的目录。
|
|
59
|
+
const profiles = Array.isArray(cfg.vaultProfiles) ? cfg.vaultProfiles : []
|
|
60
|
+
const active = String(cfg.activeVault || '').trim()
|
|
61
|
+
const hit = active && profiles.find((p) => p.name === active)
|
|
62
|
+
if (hit && hit.path && hit.path.trim()) return path.resolve(hit.path.trim())
|
|
46
63
|
if (cfg.vaultDir && cfg.vaultDir.trim()) return path.resolve(cfg.vaultDir.trim())
|
|
47
64
|
const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
|
|
48
65
|
return path.join(home, 'memory-vault')
|
|
49
66
|
}
|
|
50
67
|
|
|
51
|
-
//
|
|
68
|
+
// 所有 profile 目录(当前激活 + 其余命名的),供跨库聚合。
|
|
69
|
+
const vaultRoots = () => {
|
|
70
|
+
const cfg = settings.get() ?? {}
|
|
71
|
+
const active = vaultDir()
|
|
72
|
+
const roots = [{ name: '', root: active }]
|
|
73
|
+
const seen = new Set([active])
|
|
74
|
+
const profiles = Array.isArray(cfg.vaultProfiles) ? cfg.vaultProfiles : []
|
|
75
|
+
for (const p of profiles) {
|
|
76
|
+
if (!p || !p.path || !p.path.trim()) continue
|
|
77
|
+
const r = path.resolve(p.path.trim())
|
|
78
|
+
if (seen.has(r)) continue
|
|
79
|
+
seen.add(r)
|
|
80
|
+
roots.push({ name: p.name || r, root: r })
|
|
81
|
+
}
|
|
82
|
+
return roots
|
|
83
|
+
}
|
|
52
84
|
// agent/turn-stopping 是 serial 事件:不在监听器里 await LLM(会拖慢收尾),
|
|
53
85
|
// 同步抓取增量事件快照后,把真正的捕获调度到后台队列执行。
|
|
54
86
|
const pending = new Map() // sessionId -> merged events array
|
|
@@ -187,19 +219,36 @@ export function apply(ctx, config) {
|
|
|
187
219
|
if (!cfg.enabled) return '(记忆核心已禁用)'
|
|
188
220
|
const query = String(args.query || '').trim()
|
|
189
221
|
if (!query) return '(未提供检索词)'
|
|
190
|
-
const
|
|
222
|
+
const cfg2 = settings.get() ?? {}
|
|
223
|
+
const defLimit = Number(cfg2.recallLimit) || 5
|
|
224
|
+
const defLen = Number(cfg2.recallSummaryLen) || 130
|
|
225
|
+
const includeBody = cfg2.recallIncludeBody === true
|
|
226
|
+
const limit = Math.min(Math.max(Number(args.limit) || defLimit, 1), 20)
|
|
191
227
|
const hits = await search(vaultDir(), query, { limit, minScore: 2 })
|
|
192
228
|
if (hits.length === 0) return `记忆库中没有与「${query}」相关的内容。`
|
|
193
229
|
const lines = hits.map((h, i) => {
|
|
194
230
|
const tags = h.tags.length ? ` [${h.tags.join(', ')}]` : ''
|
|
195
|
-
const snippet = String(h.summary
|
|
196
|
-
|
|
231
|
+
const snippet = String(includeBody ? h.summary : h.summary || '')
|
|
232
|
+
.replace(/\s+/g, ' ').trim().slice(0, defLen)
|
|
233
|
+
const body = includeBody ? `\n${String(h.excerpt || '')}` : ''
|
|
234
|
+
return `### ${i + 1}. ${h.title}${tags}\n路径:${h.path}\n${snippet}${body}`
|
|
197
235
|
})
|
|
198
236
|
return `从记忆核心检索到 ${hits.length} 条相关卡片:\n\n${lines.join('\n\n')}`
|
|
199
237
|
},
|
|
200
238
|
}))
|
|
201
239
|
}
|
|
202
240
|
|
|
241
|
+
// 每日回顾:每 30 分钟检查一次,跨天就生成当日简报文件(幂等,凌晨/首日各一次)。
|
|
242
|
+
let lastBriefDate = ''
|
|
243
|
+
const briefTimer = setInterval(() => {
|
|
244
|
+
const d = new Date()
|
|
245
|
+
const date = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
|
|
246
|
+
if (lastBriefDate === date) return
|
|
247
|
+
lastBriefDate = date
|
|
248
|
+
generateDailyBrief(vaultDir()).catch(() => {})
|
|
249
|
+
}, 30 * 60 * 1000)
|
|
250
|
+
ctx.effect(() => () => clearInterval(briefTimer), 'memory-eternal: daily brief timer')
|
|
251
|
+
|
|
203
252
|
// -- 3. 知识库 JSON API(客户端设置页数据源) ----------------------------
|
|
204
253
|
const webServer = ctx.get('webServer')
|
|
205
254
|
if (webServer !== undefined) {
|
|
@@ -260,12 +309,22 @@ async function handleApi(req, res, vaultRoot) {
|
|
|
260
309
|
case '/search': {
|
|
261
310
|
const q = query.get('q') || ''
|
|
262
311
|
if (!q.trim()) return json(res, 200, { ok: true, hits: [] })
|
|
263
|
-
|
|
312
|
+
const all = query.get('all') === '1'
|
|
313
|
+
const semantic = query.get('semantic') === '1'
|
|
314
|
+
const hits = all ? await searchAll(vaultRoots(), q, { limit: 30, semantic }) : await search(vaultRoot, q, { limit: 30, semantic })
|
|
315
|
+
json(res, 200, { ok: true, hits })
|
|
264
316
|
return
|
|
265
317
|
}
|
|
266
318
|
case '/graph': {
|
|
267
319
|
await ensureVault(vaultRoot)
|
|
268
|
-
|
|
320
|
+
const all = query.get('all') === '1'
|
|
321
|
+
json(res, 200, { ok: true, ...(all ? await graphAll(vaultRoots()) : await graph(vaultRoot)) })
|
|
322
|
+
return
|
|
323
|
+
}
|
|
324
|
+
case '/todayBrief': {
|
|
325
|
+
await ensureVault(vaultRoot)
|
|
326
|
+
const s = await stats(vaultRoot)
|
|
327
|
+
json(res, 200, { ok: true, today: s.today, brief: dailyBrief(s.todayCards) })
|
|
269
328
|
return
|
|
270
329
|
}
|
|
271
330
|
case '/export': {
|
|
@@ -320,6 +379,42 @@ async function handleApi(req, res, vaultRoot) {
|
|
|
320
379
|
json(res, 200, { ok: true })
|
|
321
380
|
return
|
|
322
381
|
}
|
|
382
|
+
case '/stats': {
|
|
383
|
+
await ensureVault(vaultRoot)
|
|
384
|
+
json(res, 200, { ok: true, ...(await stats(vaultRoot)) })
|
|
385
|
+
return
|
|
386
|
+
}
|
|
387
|
+
case '/optimize': {
|
|
388
|
+
// 非破坏性:只返回「整理建议」(相似卡对 + 陈旧卡),不自动删改。
|
|
389
|
+
json(res, 200, { ok: true, ...(await optimizeCandidates(vaultRoot)) })
|
|
390
|
+
return
|
|
391
|
+
}
|
|
392
|
+
case '/feedback': {
|
|
393
|
+
let raw = ''
|
|
394
|
+
for await (const chunk of req) raw += chunk
|
|
395
|
+
let rec
|
|
396
|
+
try { rec = JSON.parse(raw || '{}') } catch { return json(res, 400, { ok: false, error: 'JSON 解析失败' }) }
|
|
397
|
+
if (!rec || !rec.path) return json(res, 400, { ok: false, error: '缺少 path' })
|
|
398
|
+
await addFeedback(vaultRoot, { query: String(rec.query || ''), path: String(rec.path || ''), useful: rec.useful === true })
|
|
399
|
+
json(res, 200, { ok: true })
|
|
400
|
+
return
|
|
401
|
+
}
|
|
402
|
+
case '/budget': {
|
|
403
|
+
const cfg = settings.get() ?? {}
|
|
404
|
+
json(res, 200, { ok: true, budgetChars: cfg.sessionBudgetChars ?? 80000, recallLimit: cfg.recallLimit ?? 5, embedding: cfg.recallEmbedding || '' })
|
|
405
|
+
return
|
|
406
|
+
}
|
|
407
|
+
case '/compress': {
|
|
408
|
+
// 记忆侧「压缩产物」接口:供 harness 在会话内压缩旧轮次时调用,返回一段可注入的摘要。
|
|
409
|
+
const cfg = settings.get() ?? {}
|
|
410
|
+
const body = new URLSearchParams(query)
|
|
411
|
+
const text = body.get('text') || ''
|
|
412
|
+
const maxChars = Math.min(Number(body.get('max')) || 2400, 6000)
|
|
413
|
+
if (!text.trim()) return json(res, 400, { ok: false, error: '缺少 text' })
|
|
414
|
+
const compressed = await compressExcerpt(text, maxChars)
|
|
415
|
+
json(res, 200, { ok: true, compressed, budgetChars: cfg.sessionBudgetChars ?? 80000 })
|
|
416
|
+
return
|
|
417
|
+
}
|
|
323
418
|
default:
|
|
324
419
|
json(res, 404, { ok: false, error: '未知接口' })
|
|
325
420
|
}
|
package/lib/capture.js
CHANGED
|
@@ -221,6 +221,17 @@ export function sliceNewEvents(events, lastSeq) {
|
|
|
221
221
|
return out
|
|
222
222
|
}
|
|
223
223
|
|
|
224
|
+
/** 解析当前模型路由:取第一个 provider 的旗舰模型(与驯兽师一致)。 */
|
|
225
|
+
/** 记忆侧「压缩产物」接口:确定性(无 LLM)从一段文本抽出结构化关键内容,供 harness 会话内压缩旧轮次时注入。 */
|
|
226
|
+
export function compressExcerpt(text, maxChars = 2400) {
|
|
227
|
+
const lines = String(text || '').split(/\r?\n/).map((L) => L.trim()).filter(Boolean)
|
|
228
|
+
const structured = lines.filter((L) => /^(#{1,6}\s|[-*]\s|\d+[.、)]\s|>|`|\[x\]|\[ \])/.test(L))
|
|
229
|
+
const src = structured.length ? structured : lines
|
|
230
|
+
let out = src.join('\n')
|
|
231
|
+
if (out.length > maxChars) out = out.slice(0, maxChars).replace(/\n+$/, '') + '\n…(已压缩,细节见记忆库)'
|
|
232
|
+
return out
|
|
233
|
+
}
|
|
234
|
+
|
|
224
235
|
/** 解析当前模型路由:取第一个 provider 的旗舰模型(与驯兽师一致)。 */
|
|
225
236
|
export async function resolveRoute(llm) {
|
|
226
237
|
try {
|
package/lib/client.js
CHANGED
|
@@ -3,7 +3,7 @@ window.__ModuleLoader__.load({
|
|
|
3
3
|
factory: (require) => {
|
|
4
4
|
var module = { exports: {} };
|
|
5
5
|
var exports = module.exports;
|
|
6
|
-
var
|
|
6
|
+
var st=Object.create;var Pe=Object.defineProperty;var lt=Object.getOwnPropertyDescriptor;var ct=Object.getOwnPropertyNames;var dt=Object.getPrototypeOf,pt=Object.prototype.hasOwnProperty;var mt=(o,s)=>{for(var m in s)Pe(o,m,{get:s[m],enumerable:!0})},tt=(o,s,m,u)=>{if(s&&typeof s=="object"||typeof s=="function")for(let n of ct(s))!pt.call(o,n)&&n!==m&&Pe(o,n,{get:()=>s[n],enumerable:!(u=lt(s,n))||u.enumerable});return o};var ut=(o,s,m)=>(m=o!=null?st(dt(o)):{},tt(s||!o||!o.__esModule?Pe(m,"default",{value:o,enumerable:!0}):m,o)),gt=o=>tt(Pe({},"__esModule",{value:!0}),o);var Bt={};mt(Bt,{apply:()=>xt,inject:()=>ft});module.exports=gt(Bt);var c=ut(require("react"),1),e=require("react/jsx-runtime"),Be="memory-eternal",U="/memory-eternal/api",ft=["settingsScope","slots","locale","connection","remote"],bt={nav:"\u8BB0\u5FC6",loading:"\u52A0\u8F7D\u4E2D\u2026",refresh:"\u5237\u65B0",overview:"\u8BB0\u5FC6\u5E93\u6982\u89C8",total:"\u77E5\u8BC6\u5361",recent:"\u8FD1 7 \u5929\u65B0\u589E",tags:"\u6807\u7B7E",searchPlaceholder:"\u641C\u7D22\u8BB0\u5FC6\uFF08\u652F\u6301\u4E2D\u6587\u7247\u6BB5\uFF09\u2026",search:"\u641C\u7D22",all:"\u5168\u90E8",kindProject:"\u9879\u76EE",kindKnowledge:"\u77E5\u8BC6",kindContent:"\u5185\u5BB9",kindPrompt:"\u63D0\u793A\u8BCD",kindBusiness:"\u4E1A\u52A1",kindTool:"\u5DE5\u5177",kindMistake:"\u6559\u8BAD",cardsTab:"\u77E5\u8BC6\u5361",graphTab:"\u77E5\u8BC6\u56FE\u8C31",graph:"\u77E5\u8BC6\u56FE\u8C31",graphHint:"\u8282\u70B9=\u77E5\u8BC6\u5361\uFF1B\u8FDE\u7EBF=[[\u94FE\u63A5]] \u6216\u5171\u4EAB\u6807\u7B7E\u3002\u70B9\u51FB\u8282\u70B9\u9605\u8BFB\u5361\u7247\u3002",graphTip:"\u5DE6\u952E\u51F8\u663E \xB7 Shift+\u62D6\u62FD\u6846\u9009 \xB7 \u53F3\u952E\u83DC\u5355 \xB7 \u6EDA\u8F6E\u7F29\u653E \xB7 \u62D6\u62FD\u5E73\u79FB",rebuild:"\u91CD\u5EFA",reset:"\u91CD\u7F6E",expandAll:"\u5168\u90E8\u5C55\u5F00",capped:"\u5DF2\u5C55\u793A\u6700\u6838\u5FC3\u7684",clearFocus:"\u53D6\u6D88\u9AD8\u4EAE",empty:"\u8BB0\u5FC6\u5E93\u8FD8\u662F\u7A7A\u7684\u3002\u591A\u804A\u51E0\u8F6E\u540E\uFF0C\u503C\u5F97\u4FDD\u5B58\u7684\u5185\u5BB9\u4F1A\u81EA\u52A8\u6C89\u6DC0\u6210\u77E5\u8BC6\u5361\u3002",emptyGraph:"\u56FE\u8C31\u6682\u65E0\u6570\u636E\u3002",open:"\u9605\u8BFB",updated:"\u66F4\u65B0\u4E8E",created:"\u521B\u5EFA\u4E8E",source:"\u6765\u6E90",close:"\u5173\u95ED",vaultDir:"\u8BB0\u5FC6\u5E93\u76EE\u5F55",capture:"\u81EA\u52A8\u6C89\u6DC0",recall:"\u81EA\u52A8\u53EC\u56DE",enabled:"\u5DF2\u542F\u7528",disabled:"\u5DF2\u7981\u7528",error:"\u52A0\u8F7D\u5931\u8D25",back:"\u8FD4\u56DE\u5217\u8868",cardCount:"\u5F20\u5361",nodes:"\u8282\u70B9",edges:"\u8FDE\u7EBF",memoryTitle:"\u8BB0\u5FC6\u5E93",memoryHint:"\u4F60\u7684\u672C\u5730\u7B2C\u4E8C\u5927\u8111",zoomIn:"\u653E\u5927",zoomOut:"\u7F29\u5C0F",fit:"\u9002\u5E94",exportGraph:"\u5BFC\u51FA",openCard:"\u6253\u5F00\u5361\u7247",focusNeighbors:"\u51F8\u663E\u5173\u8054",copyName:"\u590D\u5236\u540D\u79F0",noMatch:"\u6CA1\u6709\u5339\u914D\u7684\u8BB0\u5FC6",clearFilter:"\u6E05\u9664\u8FC7\u6EE4",sortRecent:"\u6700\u8FD1",sortTitle:"\u6807\u9898",sortHot:"\u70ED\u70B9",exportSel:"\u5BFC\u51FA\u9009\u4E2D",clearSelection:"\u6E05\u7A7A\u9009\u62E9",download:"\u4E0B\u8F7D",openNewTab:"\u65B0\u6807\u7B7E\u6253\u5F00",copyImage:"\u590D\u5236\u56FE\u7247",done:"\u5B8C\u6210",downloaded:"\u5DF2\u5F00\u59CB\u4E0B\u8F7D",openedTab:"\u5DF2\u5728\u65B0\u6807\u7B7E\u6253\u5F00",copied:"\u5DF2\u590D\u5236",exportedSel:"\u4E2A\u8282\u70B9\u5DF2\u5BFC\u51FA",fullscreen:"\u5168\u5C4F",exitFull:"\u9000\u51FA\u5168\u5C4F",copyFail:"\u590D\u5236\u5931\u8D25",timeDim:"\u65F6\u95F4\u7EF4",timeNew:"3 \u5929\u5185",timeRecent:"2 \u5468\u5185",timeMonth:"1 \u6708\u5185",timeOld:"\u66F4\u65E9",newBadge:"\u65B0",expand:"\u5C55\u5F00\u5168\u90E8",collapse:"\u6536\u8D77",exportVault:"\u5BFC\u51FAMD",exportJson:"\u5BFC\u51FAJSON",exporting:"\u5BFC\u51FA\u4E2D\u2026",exportedVault:"\u8BB0\u5FC6\u5E93\u5DF2\u5BFC\u51FA",exportFail:"\u5BFC\u51FA\u5931\u8D25",importVault:"\u5BFC\u5165",importedVault:"\u5BFC\u5165\u5B8C\u6210",importedSkipped:"\uFF08\u8DF3\u8FC7\u91CD\u590D ",importFail:"\u5BFC\u5165\u5931\u8D25",location:"\u81EA\u9009\u4F4D\u7F6E",saveAs:"\u53E6\u5B58\u4E3A",saveAsUnsupported:"\u5F53\u524D\u73AF\u5883\u4E0D\u652F\u6301\u9009\u62E9\u4FDD\u5B58\u4F4D\u7F6E",exportedTo:"\u5DF2\u5BFC\u51FA\u5230",defaultDownloads:"\u9ED8\u8BA4\u4E0B\u8F7D\u6587\u4EF6\u5939",exportCancel:"\u5DF2\u53D6\u6D88\u5BFC\u51FA",manage:"\u7BA1\u7406",tabUsage:"\u7528\u91CF/\u4ECA\u65E5",tabOptimize:"\u6574\u7406\u5EFA\u8BAE",todayAdd:"\u4ECA\u65E5\u65B0\u589E",weekAdd:"\u8FD1 7 \u5929",byKind:"\u5206\u7C7B\u7EDF\u8BA1",todayList:"\u4ECA\u65E5\u6C89\u6DC0",budgetLabel:"\u4F1A\u8BDD\u9884\u7B97",budgetChars:"\u9884\u7B97\u5B57\u7B26",recallLimitLabel:"\u53EC\u56DE\u6761\u6570",embeddingLabel:"\u8BED\u4E49\u53EC\u56DE",mergePairs:"\u76F8\u4F3C\u5361\u5BF9\uFF08\u53EF\u5408\u5E76\uFF09",staleCards:"\u9648\u65E7\u5361\uFF08>90 \u5929\u672A\u66F4\u65B0\uFF09",noOptimize:"\u6682\u65E0\u53EF\u6574\u7406\u9879\uFF0C\u5F88\u5065\u5EB7 \u{1F389}",mergeNow:"\u5408\u5E76",delete:"\u5220\u9664",todayBriefLabel:"\u6BCF\u65E5\u56DE\u987E",todayBrief:"\u67E5\u770B\u4ECA\u65E5\u7B80\u62A5",batchMerge:"\u4E00\u952E\u667A\u80FD\u5408\u5E76",mergeAllConfirm:"\u5C06\u6309\u76F8\u4F3C\u5EA6\u5206\u7EC4\u7684\u5361\u7247\u5404\u5408\u5E76\u4E3A\u4E00\u5F20\uFF08\u4FDD\u7559\u5404\u81EA kind\uFF09\uFF0C\u539F\u5361\u5220\u9664\uFF1F",crossVault:"\u8DE8\u5E93\u805A\u5408",deleteConfirm:"\u786E\u5B9A\u5220\u9664\u8BE5\u8BB0\u5FC6\u5361\uFF1F\u6B64\u64CD\u4F5C\u4E0D\u53EF\u64A4\u9500\u3002",deleted:"\u5DF2\u5220\u9664",deleteFail:"\u5220\u9664\u5931\u8D25",deleteSelected:"\u5220\u9664\u9009\u4E2D",deletedSelected:"\u5F20\u5361\u5DF2\u5220\u9664",merge:"\u5408\u5E76",mergeNeed:"\u81F3\u5C11\u9009 2 \u5F20\u5361",mergeConfirm:"\u5C06\u6240\u9009\u5361\u7247\u5408\u5E76\u4E3A\u4E00\u5F20\u5E76\u5220\u9664\u539F\u5361\uFF1F",merged:"\u5DF2\u5408\u5E76",mergeFail:"\u5408\u5E76\u5931\u8D25"},ht={nav:"Memory",loading:"Loading\u2026",refresh:"Refresh",overview:"Memory Overview",total:"Cards",recent:"Added (7d)",tags:"Tags",searchPlaceholder:"Search memory\u2026",search:"Search",all:"All",kindProject:"Projects",kindKnowledge:"Knowledge",kindContent:"Content",kindPrompt:"Prompts",kindBusiness:"Business",kindTool:"Tools",kindMistake:"Mistakes",cardsTab:"Cards",graphTab:"Graph",graph:"Knowledge Graph",graphHint:"Nodes = cards; edges = [[links]] or shared tags. Click a node to read.",graphTip:"Left-click highlights \xB7 Shift+drag box-select \xB7 right-click menu \xB7 scroll zoom \xB7 drag to pan",rebuild:"Rebuild",reset:"Reset",expandAll:"Expand all",capped:"Showing the",clearFocus:"Clear highlight",empty:"Memory is empty. After a few conversations, valuable content is auto-captured.",emptyGraph:"No graph data yet.",open:"Read",updated:"Updated",created:"Created",source:"Source",close:"Close",vaultDir:"Vault directory",capture:"Auto capture",recall:"Auto recall",enabled:"on",disabled:"off",error:"Load failed",back:"Back to list",cardCount:"cards",nodes:"nodes",edges:"edges",memoryTitle:"Memory Library",memoryHint:"Your local second brain",zoomIn:"Zoom in",zoomOut:"Zoom out",fit:"Fit",exportGraph:"Export",openCard:"Open card",focusNeighbors:"Highlight links",copyName:"Copy name",noMatch:"No matching memory",clearFilter:"Clear filter",sortRecent:"Recent",sortTitle:"Title",sortHot:"Hot",exportSel:"Export selected",clearSelection:"Clear selection",download:"Download",openNewTab:"Open in new tab",copyImage:"Copy image",done:"Done",downloaded:"Download started",openedTab:"Opened in new tab",copied:"Copied",exportedSel:" nodes exported",fullscreen:"Fullscreen",exitFull:"Exit fullscreen",copyFail:"Copy failed",timeDim:"Time",timeNew:"\u22643 days",timeRecent:"\u22642 weeks",timeMonth:"\u22641 month",timeOld:"Older",newBadge:"NEW",expand:"Expand",collapse:"Collapse",exportVault:"Export MD",exportJson:"Export JSON",exporting:"Exporting\u2026",exportedVault:"Vault exported",exportFail:"Export failed",importVault:"Import",importedVault:"Import complete",importedSkipped:" (skipped dup ",importFail:"Import failed",location:"Choose location",saveAs:"Save as",saveAsUnsupported:"Choose-save-location not supported here",exportedTo:"Exported to",defaultDownloads:"default Downloads folder",exportCancel:"Export cancelled",manage:"Manage",tabUsage:"Usage / Today",tabOptimize:"Optimize",todayAdd:"Added today",weekAdd:"Last 7d",byKind:"By kind",todayList:"Captured today",budgetLabel:"Session budget",budgetChars:"Budget chars",recallLimitLabel:"Recall limit",embeddingLabel:"Semantic recall",mergePairs:"Similar pairs (mergeable)",staleCards:"Stale (>90d)",noOptimize:"Nothing to organize, healthy \u{1F389}",mergeNow:"Merge",delete:"Delete",todayBriefLabel:"Daily review",todayBrief:"Today brief",batchMerge:"Smart batch merge",mergeAllConfirm:"Merge similar-grouped cards into one each (keep kind), delete originals?",crossVault:"All vaults",deleteConfirm:"Delete this memory card? This cannot be undone.",deleted:"Deleted",deleteFail:"Delete failed",deleteSelected:"Delete selected",deletedSelected:" cards deleted",merge:"Merge",mergeNeed:"Select at least 2 cards",mergeConfirm:"Merge the selected cards into one and delete the originals?",merged:"Merged",mergeFail:"Merge failed"},yt=["all","project","knowledge","content","prompt","business","tool","mistake"],We={project:"#3B82F6",knowledge:"#10B981",content:"#F59E0B",prompt:"#A855F7",business:"#EC4899",tool:"#06B6D4",mistake:"#EF4444",other:"#6B7280"},ve={project:"kindProject",knowledge:"kindKnowledge",content:"kindContent",prompt:"kindPrompt",business:"kindBusiness",tool:"kindTool",mistake:"kindMistake",other:"kindKnowledge"},we=`
|
|
7
7
|
.memory-eternal-root { font-family: inherit; color: var(--dsw-alias-label-primary, #1f2937); }
|
|
8
8
|
.mc-card { background: var(--dsw-alias-bg-layer-1, #fff); border: 1px solid var(--dsw-alias-border-l1, #e5e7eb); border-radius: 12px; padding: 14px 16px; }
|
|
9
9
|
.mc-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(110px, 1fr)); gap: 10px; margin-bottom: 14px; }
|
|
@@ -105,12 +105,12 @@ var it=Object.create;var je=Object.defineProperty;var st=Object.getOwnPropertyDe
|
|
|
105
105
|
.me-graph-ctxmenu button { display: block; width: 100%; text-align: left; padding: 7px 10px; border: none; border-radius: 7px; background: transparent; color: inherit; font: inherit; cursor: pointer; }
|
|
106
106
|
.me-graph-ctxmenu button:hover { background: rgba(255,255,255,0.1); }
|
|
107
107
|
.me-graph-hint { font-size: 11px; opacity: 0.6; margin-left: auto; }
|
|
108
|
-
`;function xt(
|
|
108
|
+
`;function xt(o){o.effect(()=>o.locale.register(Be,{zh:bt,en:ht}),"memory-eternal: locale");let s=o.locale.bind(Be);o.effect(()=>o.slots.inject("settings.section",()=>o.slots.register({name:"settings.section",id:Be,order:25,label:()=>s("nav"),locale:Be,inject:()=>({})},()=>c.default.createElement(nt,{t:s,inModal:!1}))),"memory-eternal: settings section"),o.effect(()=>o.slots.inject("sidebar.footer.action",()=>o.slots.register({name:"sidebar.footer.action",id:`${Be}:footer`,order:100,label:()=>s("nav"),locale:Be,inject:()=>({})},m=>c.default.createElement(vt,{t:s,wide:!(m&&m.wide===!1)}))),"memory-eternal: sidebar footer action")}function vt({t:o,wide:s}){let[m,u]=(0,c.useState)(!1);return(0,e.jsxs)("div",{className:`me-footer${s?"":" rail"}`,children:[(0,e.jsx)("style",{children:we}),(0,e.jsxs)("button",{type:"button",className:"me-footer-btn",onClick:()=>u(!0),"aria-label":o("nav"),title:o("nav"),children:[(0,e.jsx)("span",{className:"me-footer-ico","aria-hidden":"true",children:(0,e.jsx)(at,{})}),(0,e.jsx)("span",{className:"me-footer-label",children:o("nav")})]}),m&&(0,e.jsx)(wt,{t:o,onClose:()=>u(!1)})]})}function at(){return(0,e.jsxs)("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:[(0,e.jsx)("defs",{children:(0,e.jsxs)("linearGradient",{id:"mg-brain",x1:"0",y1:"0",x2:"1",y2:"1",children:[(0,e.jsx)("stop",{offset:"0%",stopColor:"#FFC46B"}),(0,e.jsx)("stop",{offset:"50%",stopColor:"#F97316"}),(0,e.jsx)("stop",{offset:"100%",stopColor:"#EA580C"})]})}),(0,e.jsx)("path",{fill:"url(#mg-brain)",d:"M12 4.5a3.2 3.2 0 0 0-6.4.1 4.1 4.1 0 0 0-2.7 5.9 4.1 4.1 0 0 0 .6 6.7A4.2 4.2 0 0 0 12 18.2Z"}),(0,e.jsx)("path",{fill:"url(#mg-brain)",d:"M12 4.5a3.2 3.2 0 0 1 6.4.1 4.1 4.1 0 0 1 2.7 5.9 4.1 4.1 0 0 1-.6 6.7A4.2 4.2 0 0 1 12 18.2Z"}),(0,e.jsx)("path",{d:"M12 9.2c-.8-1.4-1.7-2-3.1-2.2M12 9.2c.8-1.4 1.7-2 3.1-2.2M12 12.4c-1.2 1-3.2 1.6-5 1.4M12 12.4c1.2 1 3.2 1.6 5 1.4M12 13.2v4",fill:"none",stroke:"rgba(255,255,255,0.62)",strokeWidth:"1",strokeLinecap:"round"}),(0,e.jsx)("circle",{cx:"12",cy:"8.6",r:"1.1",fill:"rgba(255,255,255,0.85)"})]})}function wt({t:o,onClose:s}){return(0,c.useEffect)(()=>{let m=u=>{u.key==="Escape"&&s()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[s]),(0,e.jsxs)("div",{className:"me-overlay-top",onClick:s,children:[(0,e.jsx)("style",{children:we}),(0,e.jsx)("div",{className:"me-modal",onClick:m=>m.stopPropagation(),children:(0,e.jsx)(nt,{t:o,inModal:!0,onClose:s})})]})}function nt({t:o,inModal:s,onClose:m}){let[u,n]=(0,c.useState)(null),[g,I]=(0,c.useState)([]),[z,P]=(0,c.useState)(!0),[T,F]=(0,c.useState)(""),[_,me]=(0,c.useState)("all"),[V,ke]=(0,c.useState)(""),[A,ce]=(0,c.useState)("cards"),[J,ue]=(0,c.useState)("recent"),[ne,R]=(0,c.useState)(null),W=(0,c.useRef)(null),h=(0,c.useRef)(null),[j,L]=(0,c.useState)(!1),[$,ye]=(0,c.useState)(!1),[ee,S]=(0,c.useState)(null),[H,G]=(0,c.useState)(null),[Ce,re]=(0,c.useState)(!1),de=(0,c.useRef)(null),[fe,Ne]=(0,c.useState)(24),xe=(0,c.useRef)(null);(0,c.useEffect)(()=>{if(A!=="cards")return;let d=xe.current;if(!d)return;let x=new IntersectionObserver(f=>{f[0]&&f[0].isIntersecting&&Ne(t=>t+24)},{rootMargin:"400px"});return x.observe(d),()=>x.disconnect()},[A,g,_,V]);let Fe=(0,c.useCallback)(async(d=_,x=V)=>{try{P(!0),F("");let f=new URLSearchParams;d&&d!=="all"&&f.set("kind",d),x.trim()&&f.set("q",x.trim());let q=await(await fetch(`${U}/cards?${f.toString()}`)).json();q.ok&&(I(q.cards||[]),Ne(24))}catch(f){F(String(f&&f.message?f.message:f))}finally{P(!1)}},[_,V]),te=(0,c.useCallback)(async()=>{try{let[d,x]=await Promise.all([fetch(`${U}/overview`).then(f=>f.json()),fetch(`${U}/cards`).then(f=>f.json())]);d.ok&&n(d),x.ok&&(I(x.cards||[]),Ne(24))}catch(d){F(String(d&&d.message?d.message:d))}finally{P(!1)}},[]),be=async d=>{try{let f=await(await fetch(`${U}/delete?path=${encodeURIComponent(d)}`)).json();f.ok?(R({ok:!0,msg:o("deleted")}),await te()):R({ok:!1,msg:f.error||o("deleteFail")})}catch{R({ok:!1,msg:o("deleteFail")})}W.current&&clearTimeout(W.current),W.current=setTimeout(()=>R(null),2e3)};(0,c.useEffect)(()=>(te(),()=>{de.current&&clearTimeout(de.current)}),[te]);let O=d=>{ke(d),de.current&&clearTimeout(de.current),de.current=setTimeout(()=>Fe(_,d),280)},Me=d=>{me(d),Fe(d,V)},Z=async d=>{try{let f=await(await fetch(`${U}/card?path=${encodeURIComponent(d.path||d.id)}`)).json();f.ok&&S({path:f.path,title:d.title,text:f.text})}catch(x){F(String(x&&x.message?x.message:x))}},i=async(d,x)=>{L(!0);try{let f=await fetch(`${U}/export`);if(!f.ok)throw new Error("HTTP "+f.status);let t=await f.json();if(!t.ok)throw new Error(t.error||"export failed");let q,Se,Ie;d==="json"?(Se="memory-vault.json",Ie="application/json",q=JSON.stringify(t.cards.map(se=>({path:se.path,title:se.title,kind:se.kind,text:se.text})),null,2)):(Se="memory-vault.md",Ie="text/markdown;charset=utf-8",q=t.cards.map(se=>se.text.trim()).filter(Boolean).join(`
|
|
109
109
|
|
|
110
110
|
---
|
|
111
111
|
|
|
112
|
-
`));let e=new Blob([N],{type:D}),ne=await at(e,R,a);if(!ne.ok){z({ok:!1,msg:ne.aborted?n("exportCancel"):n("exportFail")}),O(!1);return}z({ok:!0,msg:ne.picked?n("exportedTo")+"\uFF1A"+ne.name:n("exportedTo")+"\uFF1A"+n("defaultDownloads")+" \xB7 "+ne.name})}catch(t){z({ok:!1,msg:n("exportFail")+" \xB7 "+(t.message||"")})}finally{O(!1)}j.current&&clearTimeout(j.current),j.current=setTimeout(()=>z(null),2600)},F=async d=>{let a=d.target.files&&d.target.files[0];if(d.target.value="",!!a){try{let t=await a.text(),N=await(await fetch(`${ee}/import`,{method:"POST",headers:{"Content-Type":"application/json"},body:t})).json();N.ok?(await Z(),z({ok:!0,msg:n("importedVault")+"\uFF1A"+(N.imported||0)+(N.skipped?n("importedSkipped")+N.skipped:"")})):z({ok:!1,msg:N.error||n("importFail")})}catch{z({ok:!1,msg:n("importFail")})}j.current&&clearTimeout(j.current),j.current=setTimeout(()=>z(null),2400)}},be=(0,c.useMemo)(()=>{let d=b.slice();return me==="title"?d.sort((a,t)=>String(a.title||"").localeCompare(String(t.title||""))):me==="hot"?d.sort((a,t)=>(t.weight||t.links||0)-(a.weight||a.links||0)):d.sort((a,t)=>new Date(t.updated||0).getTime()-new Date(a.updated||0).getTime()),d},[b,me]);return(0,o.jsxs)("div",{className:"memory-eternal-root",style:{height:"100%",display:"flex",flexDirection:"column"},children:[(0,o.jsx)("style",{children:Ne}),oe&&(0,o.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,position:"fixed",left:"50%",transform:"translateX(-50%)",top:22,zIndex:70,background:"rgba(20,22,26,0.97)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",color:"#f5f5f5",borderRadius:12,padding:"10px 20px",fontSize:13.5,fontWeight:600,boxShadow:"0 14px 44px rgba(0,0,0,.5)",pointerEvents:"none",animation:"me-pop .22s ease",borderLeft:"4px solid "+(oe.ok?"#22c55e":"#ef4444"),maxWidth:"90vw"},children:[(0,o.jsx)("span",{style:{color:oe.ok?"#34d399":"#f87171",fontWeight:800,fontSize:15},children:oe.ok?"\u2713":"\u2715"}),(0,o.jsx)("span",{children:oe.msg})]}),l&&(0,o.jsxs)("div",{className:"me-modal-head",children:[(0,o.jsxs)("div",{className:"me-modal-title",children:[(0,o.jsx)("span",{className:"me-wicon",children:(0,o.jsx)(ot,{})}),(0,o.jsx)("h2",{children:n("memoryTitle")}),(0,o.jsx)("span",{children:n("memoryHint")})]}),(0,o.jsx)("div",{className:"spacer"}),(0,o.jsx)("button",{type:"button",className:"me-modal-close",onClick:m,"aria-label":n("close"),children:"\u2715"})]}),(0,o.jsxs)("div",{className:"me-modal-body",children:[(0,o.jsxs)("div",{className:"mc-stats",children:[(0,o.jsx)(De,{label:n("total"),value:h?h.total:"\u2014"}),(0,o.jsx)(De,{label:n("recent"),value:h?h.recent:"\u2014"}),(0,o.jsx)(De,{label:n("tags"),value:h?h.tags:"\u2014"}),(0,o.jsx)(De,{label:n("cardCount"),value:h?h.byKind?.knowledge??0:"\u2014"})]}),(0,o.jsxs)("div",{className:"mc-toolbar",children:[(0,o.jsx)("input",{type:"text",placeholder:n("searchPlaceholder"),value:q,onChange:d=>xe(d.target.value)}),(0,o.jsxs)("div",{className:"mc-tabs",children:[(0,o.jsx)("button",{type:"button",className:`mc-tab${B==="cards"?" active":""}`,onClick:()=>se("cards"),children:n("cardsTab")}),(0,o.jsx)("button",{type:"button",className:`mc-tab${B==="graph"?" active":""}`,onClick:()=>se("graph"),children:n("graphTab")})]}),(0,o.jsx)("input",{ref:Me,type:"file",accept:".json,application/json",style:{display:"none"},onChange:F}),(0,o.jsx)("button",{type:"button",className:"mc-btn",onClick:()=>Me.current&&Me.current.click(),children:n("importVault")}),(0,o.jsxs)("label",{className:"mc-btn",style:{display:"inline-flex",alignItems:"center",gap:5,cursor:"pointer"},title:n("location"),children:[(0,o.jsx)("input",{type:"checkbox",checked:V,onChange:d=>Ye(d.target.checked)}),n("location")]}),(0,o.jsx)("button",{type:"button",className:"mc-btn",disabled:ge,onClick:()=>ce("md",V),children:n(ge?"exporting":"exportVault")}),(0,o.jsx)("button",{type:"button",className:"mc-btn",disabled:ge,onClick:()=>ce("json",V),children:n(ge?"exporting":"exportJson")}),(0,o.jsx)("button",{type:"button",className:"mc-btn",onClick:()=>Z(),children:n("refresh")})]}),B==="cards"&&(0,o.jsxs)("div",{className:"mc-chips",children:[bt.map(d=>(0,o.jsx)("button",{type:"button",className:`mc-chip${ie===d?" active":""}`,onClick:()=>Ee(d),children:n(d==="all"?"all":Ce[d])},d)),(0,o.jsx)("span",{className:"spacer",style:{flex:1}}),[{key:"recent",label:n("sortRecent")},{key:"title",label:n("sortTitle")},{key:"hot",label:n("sortHot")}].map(d=>(0,o.jsx)("button",{type:"button",className:`mc-chip${me===d.key?" active":""}`,onClick:()=>ue(d.key),children:d.label},d.key))]}),E&&(0,o.jsxs)("div",{className:"mc-empty",children:[n("error"),"\uFF1A",E]}),B==="cards"?W&&!b.length?(0,o.jsx)("div",{className:"mc-empty",children:n("loading")}):b.length===0?(0,o.jsx)("div",{className:"mc-empty",children:n("empty")}):(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("div",{className:"mc-grid",children:be.slice(0,A).map(d=>(0,o.jsx)(vt,{card:d,t:n,query:q.trim(),onOpen:le,onDelete:Ie},d.path))}),be.length>A&&(0,o.jsx)("div",{ref:U,style:{height:1}})]}):(0,o.jsx)(Ct,{t:n,onOpen:le}),_&&(0,o.jsx)(kt,{t:n,card:_,onClose:()=>J(null),onDelete:d=>{J(null),Ie(d)}})]})]})}var De=({label:n,value:l})=>(0,o.jsxs)("div",{className:"mc-stat mc-card",children:[(0,o.jsx)("b",{children:l}),(0,o.jsx)("span",{children:n})]}),vt=({card:n,t:l,onOpen:m,query:h,onDelete:i})=>(0,o.jsxs)("article",{className:"mc-cardrow mc-card",onClick:()=>m(n),children:[(0,o.jsxs)("h4",{children:[(0,o.jsx)("span",{className:"mc-kind",style:{background:Pe[n.kind]||Pe.other}}),h?tt(n.title,h):n.title,St(n.updated)&&(0,o.jsx)("span",{className:"mc-new",children:l("newBadge")})]}),(0,o.jsx)("p",{children:h?tt(n.summary||"",h):n.summary||""}),n.tags.length>0&&(0,o.jsx)("div",{className:"mc-tags",children:n.tags.slice(0,4).map(b=>(0,o.jsx)("span",{className:"mc-tag",children:b},b))}),(0,o.jsxs)("footer",{children:[(0,o.jsx)("span",{children:l(Ce[n.kind])}),(0,o.jsx)("span",{children:zt(n.updated)}),(0,o.jsx)("span",{className:"spacer",style:{flex:1}}),(0,o.jsx)("button",{type:"button",className:"mc-card-del",title:l("delete"),onClick:b=>{b.stopPropagation(),window.confirm(l("deleteConfirm"))&&i&&i(n.path)},children:"\u2715"})]})]});function kt({t:n,card:l,onClose:m,onDelete:h}){(0,c.useEffect)(()=>{let W=C=>{C.key==="Escape"&&m()};return window.addEventListener("keydown",W),()=>window.removeEventListener("keydown",W)},[m]);let[i,b]=(0,c.useState)(!1),T=(l.text||"").length>460;return(0,o.jsxs)("div",{className:"me-overlay",onClick:m,children:[(0,o.jsx)("style",{children:Ne}),(0,o.jsxs)("div",{className:"me-dialog",onClick:W=>W.stopPropagation(),children:[(0,o.jsxs)("div",{className:"me-dialog-head",children:[(0,o.jsx)("h3",{children:l.title}),(0,o.jsxs)("div",{style:{display:"flex",gap:8},children:[T&&(0,o.jsx)("button",{type:"button",className:"mc-btn",onClick:()=>b(W=>!W),children:n(i?"collapse":"expand")}),(0,o.jsx)("button",{type:"button",className:"mc-btn",style:{color:"#f87171"},onClick:()=>{window.confirm(n("deleteConfirm"))&&h&&h(l.path)},children:n("delete")}),(0,o.jsx)("button",{type:"button",className:"mc-btn",onClick:m,children:n("close")})]})]}),(0,o.jsx)("div",{className:"me-dialog-body",style:i?{}:{maxHeight:300,overflow:"hidden"},dangerouslySetInnerHTML:{__html:Tt(l.text)}})]})]})}function Ct({t:n,onOpen:l}){let[m,h]=(0,c.useState)(null),[i,b]=(0,c.useState)(""),T=(0,c.useCallback)(async()=>{try{let E=await(await fetch(`${ee}/graph`)).json();h(E.ok?E:null),b("")}catch(C){b(String(C&&C.message?C.message:C))}},[]);(0,c.useEffect)(()=>{let C=!0;return fetch(`${ee}/graph`).then(E=>E.json()).then(E=>{C&&h(E.ok?E:null)}).catch(E=>{C&&b(String(E&&E.message?E.message:E))}),()=>{C=!1}},[]);let W=(0,c.useCallback)(async C=>{try{let G=await(await fetch(`${ee}/delete?path=${encodeURIComponent(C)}`)).json();return G&&G.ok?(await T(),!0):!1}catch{return!1}},[T]);return(0,o.jsxs)("div",{className:"me-graph",children:[(0,o.jsx)("style",{children:Ne}),i&&(0,o.jsxs)("div",{className:"mc-empty",children:[n("error"),"\uFF1A",i]}),!m&&!i&&(0,o.jsx)("div",{className:"mc-empty",children:n("loading")}),m&&m.nodes.length===0&&(0,o.jsx)("div",{className:"mc-empty",children:n("emptyGraph")}),m&&m.nodes.length>0&&(0,o.jsx)(Mt,{nodes:m.nodes,edges:m.edges,onOpen:l,onDelete:W,t:n,countLabel:`${m.nodes.length} ${n("nodes")} \xB7 ${Nt(m.edges)} ${n("edges")}`})]})}function Nt(n){let l=new Set;for(let m of n||[])l.add([m.source,m.target].sort().join("|"));return l.size}var $e={colors:{project:"#3B82F6",knowledge:"#10B981",content:"#F59E0B",prompt:"#A855F7",business:"#EC4899",tool:"#06B6D4",mistake:"#EF4444",other:"#6B7280"},shapes:{project:"circle",knowledge:"circle",content:"rect",prompt:"diamond",business:"hexagon",tool:"circle",mistake:"diamond",other:"circle"}};function Mt({nodes:n,edges:l,onOpen:m,onDelete:h,t:i,countLabel:b}){let T=(0,c.useRef)(null),W=(0,c.useRef)(null),C=(0,c.useRef)(null),E=(0,c.useRef)(null),G=(0,c.useRef)(null),ie=(0,c.useRef)(m);(0,c.useEffect)(()=>{ie.current=m},[m]);let pe=(0,c.useRef)(h);(0,c.useEffect)(()=>{pe.current=h},[h]);let[q,Oe]=(0,c.useState)(""),[B,se]=(0,c.useState)(null),me=(0,c.useRef)("");(0,c.useEffect)(()=>{me.current=q.trim().toLowerCase()},[q]);let[ue,oe]=(0,c.useState)("all"),z=(0,c.useRef)("all"),[j,Me]=(0,c.useState)(!1),ge=(0,c.useRef)(!1),[O,V]=(0,c.useState)(null);(0,c.useEffect)(()=>{z.current=ue},[ue]),(0,c.useEffect)(()=>{ge.current=j},[j]);let Ye=(()=>{let a=q.trim().toLowerCase();return!!a&&!n.some(t=>(t.title||t.name||"").toLowerCase().includes(a)||String(t.kind||"").toLowerCase().includes(a)||String(Ce[t.kind]||"").toLowerCase().includes(a))})();(0,c.useEffect)(()=>{let a=C.current;a&&a.wake&&a.wake()},[q]),(0,c.useEffect)(()=>{let a=C.current;a&&a.render&&a.render()},[ue,j]);let _=(0,c.useRef)(null),[J,X]=(0,c.useState)([]),[A,fe]=(0,c.useState)(null),[U,he]=(0,c.useState)(!1),[Z,Ie]=(0,c.useState)(null),[xe,Ee]=(0,c.useState)(""),le=(0,c.useRef)(null),ce=(0,c.useRef)(null),F=(a,t=!0)=>{le.current&&clearTimeout(le.current),Ie({msg:a,ok:t}),le.current=setTimeout(()=>Ie(null),1900)},be=a=>{Ee(a),ce.current&&clearTimeout(ce.current),ce.current=setTimeout(()=>Ee(""),1600)};(0,c.useEffect)(()=>()=>{le.current&&clearTimeout(le.current),ce.current&&clearTimeout(ce.current)},[]);let d=(0,c.useMemo)(()=>n.reduce((a,t)=>(a[t.id]=t,a),{}),[n]);return(0,c.useEffect)(()=>{let a=T.current;if(!a||n.length===0)return;let t=a.getContext("2d");if(!t)return;let y=Math.max(1,window.devicePixelRatio||1),N=()=>document.documentElement.getAttribute("data-theme")==="dark",R={};l.forEach(r=>{R[r.source]=(R[r.source]||0)+1,R[r.target]=(R[r.target]||0)+1});let D=Math.max(1,...Object.values(R)),e={nodes:n.map(r=>({id:r.id,name:r.title||"",type:r.kind||"other",r:9+Math.min(10,(R[r.id]||0)/D*8),x:0,y:0,vx:0,vy:0})),edges:l.map(r=>({sourceNodeId:r.source,targetNodeId:r.target,weight:1})),panX:0,panY:0,zoom:1,running:!0,raf:0,tickCount:0,quietTicks:0,dragNode:null,selectedId:null,mouseX:0,mouseY:0,w:0,h:0,dpr:y,ctx:t,multi:[],marquee:null};e.domain=n,e.domainById=n.reduce((r,u)=>(r[u.id]=u,r),{}),e.nodes.forEach((r,u)=>{let p=u/e.nodes.length*Math.PI*2-Math.PI/2;r.x=Math.cos(p)*60,r.y=Math.sin(p)*60});let ne=[...new Set(e.nodes.map(r=>r.type))];e.clustered=ne.length>1,e.typeCenters={},ne.forEach((r,u)=>{let p=u/ne.length*Math.PI*2-Math.PI/2;e.typeCenters[r]={x:Math.cos(p)*160,y:Math.sin(p)*160}}),C.current=e;let ae=()=>{let r=a.clientWidth,u=a.clientHeight;e.w=r,e.h=u,a.width=r*y,a.height=u*y,t.setTransform(y,0,0,y,0,0)};ae();let We=new ResizeObserver(ae);We.observe(a.parentElement);let rt=(r,u)=>r&&r.length>u?r.slice(0,u)+"\u2026":r,Se=(r,u,p,g)=>{if(t.beginPath(),g==="rect")t.rect(r-p,u-p*.75,p*2,p*1.5);else if(g==="diamond")t.moveTo(r,u-p),t.lineTo(r+p,u),t.lineTo(r,u+p),t.lineTo(r-p,u),t.closePath();else if(g==="hexagon"){for(let f=0;f<6;f++){let v=Math.PI/3*f-Math.PI/2,M=r+p*Math.cos(v),s=u+p*Math.sin(v);f===0?t.moveTo(M,s):t.lineTo(M,s)}t.closePath()}else t.arc(r,u,p,0,Math.PI*2)},Fe=()=>{if(!e.nodes.length)return;let r=1/0,u=-1/0,p=1/0,g=-1/0;e.nodes.forEach(k=>{r=Math.min(r,k.x),u=Math.max(u,k.x),p=Math.min(p,k.y),g=Math.max(g,k.y)});let f=36,v=u-r+f*2,M=g-p+f*2,s=Math.min(e.w/v,e.h/M);e.zoom=Math.max(.45,Math.min(2.4,s*1.22)),e.panX=e.w/2-(r+u)/2*e.zoom,e.panY=e.h/2-(p+g)/2*e.zoom};E.current=Fe;let qe=()=>{t.clearRect(0,0,e.w,e.h),e.searchTerm=me.current,e.kindFilter=z.current,e.timeMode=ge.current;let r=e.kindFilter,u=s=>String(s||"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");t.save(),t.strokeStyle=N()?"rgba(255,255,255,0.04)":"rgba(0,0,0,0.04)",t.lineWidth=.5;for(let s=0;s<e.w;s+=24)t.beginPath(),t.moveTo(s,0),t.lineTo(s,e.h),t.stroke();for(let s=0;s<e.h;s+=24)t.beginPath(),t.moveTo(0,s),t.lineTo(e.w,s),t.stroke();t.restore(),t.save(),t.translate(e.panX,e.panY),t.scale(e.zoom,e.zoom);let p={};e.nodes.forEach(s=>p[s.id]=s);let g=e.nodes.length>40,f=g?1.5:.55,v=e.selectedId||e.hoverId;e.edges.forEach(s=>{let k=p[s.sourceNodeId],I=p[s.targetNodeId];if(!k||!I)return;if(r!=="all"){let Y=e.domainById[s.sourceNodeId]&&e.domainById[s.sourceNodeId].kind,Ze=e.domainById[s.targetNodeId]&&e.domainById[s.targetNodeId].kind;if(Y!==r&&Ze!==r)return}let x=I.x-k.x,w=I.y-k.y,S=Math.sqrt(x*x+w*w)||1,L=g?12:18,$=-w/S*L,K=x/S*L,P=(k.x+I.x)/2+$,te=(k.y+I.y)/2+K,H=$e.colors[e.domainById[k.id]&&e.domainById[k.id].kind||"other"],re=v&&(s.sourceNodeId===v||s.targetNodeId===v),ye=v?re?.6:.08:g?.14:.24,ze=parseInt(H.slice(1,3),16),Le=parseInt(H.slice(3,5),16),Je=parseInt(H.slice(5,7),16);t.strokeStyle="rgba("+ze+","+Le+","+Je+","+ye+")",t.lineWidth=re?1.6+(s.weight||1):.8+(s.weight||1)*.5,t.beginPath(),t.moveTo(k.x,k.y),t.quadraticCurveTo(P,te,I.x,I.y),t.stroke()});let M=[];if(e.nodes.forEach(s=>{let k=e.domainById[s.id]||{},I=k.kind||"other",x=e.timeMode?It(k.updated):$e.colors[I],w=$e.shapes[I],S=e.selectedId===s.id,L=e.hoverId===s.id,$=e.searchTerm||"",K=!$||(s.name||"").toLowerCase().includes($)||String(Ce[I]||"").toLowerCase().includes($)||String(I).toLowerCase().includes($),P=r==="all"||I===r,te=v&&s.id!==v&&!e.edges.some(Y=>Y.sourceNodeId===v&&Y.targetNodeId===s.id||Y.targetNodeId===v&&Y.sourceNodeId===s.id)||$&&!K||!P;t.save(),t.globalAlpha=te?.08:1,(S||L)&&(t.shadowColor=x,t.shadowBlur=S?20:14),Se(s.x,s.y,s.r,w);let H=parseInt(x.slice(1,3),16),re=parseInt(x.slice(3,5),16),ye=parseInt(x.slice(5,7),16),ze=t.createRadialGradient(s.x-s.r*.3,s.y-s.r*.3,0,s.x,s.y,s.r*1.2);ze.addColorStop(0,"rgba("+Math.min(255,H+70)+","+Math.min(255,re+70)+","+Math.min(255,ye+70)+",0.95)"),ze.addColorStop(1,x),t.fillStyle=ze,t.fill(),t.restore(),S?(t.save(),Se(s.x,s.y,s.r+3,w),t.strokeStyle=x,t.lineWidth=3,t.shadowColor=x,t.shadowBlur=12,t.stroke(),t.restore()):L?(t.save(),Se(s.x,s.y,s.r+2,w),t.strokeStyle=x,t.lineWidth=2,t.stroke(),t.restore()):$&&K?(t.save(),Se(s.x,s.y,s.r+2,w),t.strokeStyle="#e11d48",t.lineWidth=2,t.stroke(),t.restore()):e.multi.indexOf(s.id)>=0&&(t.save(),Se(s.x,s.y,s.r+2,w),t.strokeStyle="#60a5fa",t.lineWidth=2,t.shadowColor="#60a5fa",t.shadowBlur=8,t.stroke(),t.restore());let Le=rt(s.name,16);if((S||L||e.zoom>f||!g&&e.zoom>.6)&&P){let Y=1/e.zoom;t.font="500 "+(12*Y).toFixed(1)+"px -apple-system,Segoe UI,sans-serif";let de=t.measureText(Le).width+16*Y,Be=18*Y,we=s.y+s.r+8*Y,Qe=!0;for(let ve of M)if(s.x-de/2<ve.x+ve.w&&s.x+de/2>ve.x&&we<ve.y+ve.h&&we+Be>ve.y){Qe=!1;break}if(!Qe&&!S&&!L)return;M.push({x:s.x-de/2,y:we,w:de,h:Be}),t.fillStyle=N()?"rgba(30,30,35,0.92)":"rgba(255,255,255,0.92)",t.beginPath(),t.roundRect?t.roundRect(s.x-de/2,we,de,Be,4*Y):t.rect(s.x-de/2,we,de,Be),t.fill(),t.strokeStyle=N()?"rgba(255,255,255,0.08)":"rgba(0,0,0,0.08)",t.lineWidth=1*Y,t.stroke(),t.fillStyle=N()?S||L?"#eee":"#bbb":S||L?"#111":"#444",t.textAlign="center",t.fillText(Le,s.x,we+13*Y)}}),t.restore(),e.marquee){let s=e.marquee,k=Math.min(s.sx,s.ex),I=Math.min(s.sy,s.ey),x=Math.abs(s.ex-s.sx),w=Math.abs(s.ey-s.sy);t.save(),t.setLineDash([4,4]),t.strokeStyle="rgba(96,165,250,0.9)",t.lineWidth=1,t.fillStyle="rgba(96,165,250,0.12)",t.fillRect(k,I,x,w),t.strokeRect(k,I,x,w),t.restore()}if(e.hoverId&&_.current){let s=e.domainById[e.hoverId],k=e.nodes.find(function(I){return I.id===e.hoverId});if(s&&k){let I=e.edges.filter(function(S){return S.sourceNodeId===s.id||S.targetNodeId===s.id}).length,x=k.x*e.zoom+e.panX,w=k.y*e.zoom+e.panY;_.current.style.display="block",_.current.style.left=x+14+"px",_.current.style.top=w-6+"px",_.current.innerHTML="<b>"+u(s.title||s.name||"")+'</b><br/><span style="opacity:.8">'+u(s.kind||"")+" \xB7 "+I+" \u8FDE\u63A5</span>"}}else _.current&&(_.current.style.display="none")},Q=()=>{e.running=!0,e.raf||(e.raf=requestAnimationFrame(Ae))};e.wake=Q,e.render=qe;let Xe=()=>{let r=e.nodes.length;e.tickCount++;let p=.9-Math.min(.4,e.tickCount/1500),g=r>1e3?3e3:r>100?2e3:r>50?1200:800,f=r>100?.002:.005,v=r>1e3?.012:r>100?.005:.01,M=r>1e3?6:r>200?12:24,s={};e.nodes.forEach(x=>s[x.id]=x);for(let x=0;x<r;x++){if(e.dragNode===e.nodes[x])continue;let w=e.nodes[x],S=0,L=0;for(let P=0;P<r;P++){if(x===P)continue;let te=w.x-e.nodes[P].x,H=w.y-e.nodes[P].y,re=Math.sqrt(te*te+H*H)||1,ye=g/(re*re);S+=te/re*ye,L+=H/re*ye}if(e.clustered&&e.typeCenters[w.type]){let P=e.typeCenters[w.type];S+=(P.x-w.x)*.006,L+=(P.y-w.y)*.006}else S-=w.x*v,L-=w.y*v;let $=(w.vx+S)*p,K=(w.vy+L)*p;$=Math.max(-M,Math.min(M,$)),K=Math.max(-M,Math.min(M,K)),w.vx=$,w.vy=K}e.edges.forEach(x=>{let w=s[x.sourceNodeId],S=s[x.targetNodeId];if(!w||!S)return;let L=S.x-w.x,$=S.y-w.y,K=Math.sqrt(L*L+$*$)||1,P=(K-100)*f,te=L/K*P,H=$/K*P;e.dragNode!==w&&(w.vx+=te,w.vy+=H),e.dragNode!==S&&(S.vx-=te,S.vy-=H)});let k=0;e.nodes.forEach(x=>{e.dragNode!==x&&(x.x+=x.vx,x.y+=x.vy,k+=x.vx*x.vx+x.vy*x.vy)}),e.autoFitPending&&e.tickCount>45&&(e.autoFitPending=!1,Fe()),(r?Math.sqrt(k/r):0)<.05&&e.tickCount>60&&!e.dragNode?e.quietTicks=(e.quietTicks|0)+1:e.quietTicks=0},Ae=()=>{if(e.running){try{Xe(),qe()}catch{}if(e.quietTicks>30){e.raf=0;return}e.raf=requestAnimationFrame(Ae)}},Te=(r,u)=>{let p=a.getBoundingClientRect();return{x:(r-p.left-e.panX)/e.zoom,y:(u-p.top-e.panY)/e.zoom}},Re=(r,u,p)=>Math.max(u,Math.min(p,r)),Ue=r=>{e.mouseX=r.clientX,e.mouseY=r.clientY;let u=Te(r.clientX,r.clientY),p=null;for(let g=e.nodes.length-1;g>=0;g--){let f=e.nodes[g];if(z.current!=="all"&&(e.domainById[f.id]&&e.domainById[f.id].kind)!==z.current)continue;let v=f.x-u.x,M=f.y-u.y;if(v*v+M*M<f.r*f.r+36){p=f.id;break}}p!==e.hoverId&&(e.hoverId=p,Q())},Ke=r=>{if(r.button!==0)return;let u=Te(r.clientX,r.clientY),p=null;for(let g=e.nodes.length-1;g>=0;g--){let f=e.nodes[g];if(z.current!=="all"&&(e.domainById[f.id]&&e.domainById[f.id].kind)!==z.current)continue;let v=f.x-u.x,M=f.y-u.y;if(v*v+M*M<f.r*f.r+25){p=f;break}}if(r.shiftKey){e.marquee={sx:r.clientX,sy:r.clientY,ex:r.clientX,ey:r.clientY};return}e.dragStart={x:r.clientX,y:r.clientY,px:e.panX,py:e.panY},e.dragging=!1,e.dragNode=p||null,p&&(e.dragOffset={dx:p.x-u.x,dy:p.y-u.y})},He=r=>{if(e.marquee){e.marquee.ex=r.clientX,e.marquee.ey=r.clientY,Q();return}if(!e.dragStart)return;let u=r.clientX-e.dragStart.x,p=r.clientY-e.dragStart.y;if(Math.abs(u)+Math.abs(p)>3&&(e.dragging=!0),e.dragNode){let g=Te(r.clientX,r.clientY);e.dragNode.x=g.x+e.dragOffset.dx,e.dragNode.y=g.y+e.dragOffset.dy,Q()}else e.dragging&&(e.panX=Re(e.dragStart.px+u,-1e5,1e5),e.panY=Re(e.dragStart.py+p,-1e5,1e5),Q())},Ge=r=>{if(e.marquee){let p=e.marquee;e.marquee=null;let g=a.getBoundingClientRect(),f=Math.min(p.sx,p.ex)-g.left,v=Math.max(p.sx,p.ex)-g.left,M=Math.min(p.sy,p.ey)-g.top,s=Math.max(p.sy,p.ey)-g.top,k=e.nodes.filter(I=>{let x=I.x*e.zoom+e.panX,w=I.y*e.zoom+e.panY;return x>=f&&x<=v&&w>=M&&w<=s}).map(I=>I.id);e.multi=k,X(k),Q();return}if(e.dragStart&&!e.dragging){let p=Te(r.clientX,r.clientY),g=null;for(let f=e.nodes.length-1;f>=0;f--){let v=e.nodes[f];if(z.current!=="all"&&(e.domainById[v.id]&&e.domainById[v.id].kind)!==z.current)continue;let M=v.x-p.x,s=v.y-p.y;if(M*M+s*s<v.r*v.r+20){g=v;break}}g?(e.selectedId=g.id,se(g.id),Q()):(e.selectedId=null,e.hoverId=null,r.shiftKey||(e.multi=[],X([])),se(null),Q())}e.dragStart=null,e.dragging=!1,e.dragNode=null},Ve=r=>{r.preventDefault();let u=Te(r.clientX,r.clientY),p=null;for(let g=e.nodes.length-1;g>=0;g--){let f=e.nodes[g];if(z.current!=="all"&&(e.domainById[f.id]&&e.domainById[f.id].kind)!==z.current)continue;let v=f.x-u.x,M=f.y-u.y;if(v*v+M*M<f.r*f.r+25){p=f;break}}if(p){let g=e.domainById[p.id];g&&V({x:r.clientX,y:r.clientY,id:p.id,path:g.id,title:g.title})}else V(null)},_e=r=>{r.preventDefault();let u=a.getBoundingClientRect(),p=(r.clientX-u.left-e.panX)/e.zoom,g=(r.clientY-u.top-e.panY)/e.zoom,f=Math.max(.3,Math.min(3,e.zoom*(r.deltaY<0?1.1:1/1.1)));e.panX=Re(e.panX+p*(e.zoom-f),-1e5,1e5),e.panY=Re(e.panY+g*(e.zoom-f),-1e5,1e5),e.zoom=f,Q()};a.addEventListener("mousemove",Ue),a.addEventListener("mousedown",Ke),window.addEventListener("mousemove",He),window.addEventListener("mouseup",Ge),a.addEventListener("wheel",_e,{passive:!1}),a.addEventListener("contextmenu",Ve),G.current=()=>{e.selectedId=null,e.hoverId=null,e.multi=[],X([]),Fe(),Q()};for(let r=0;r<200;r++)Xe();return Fe(),Q(),()=>{e.running=!1,e.raf&&cancelAnimationFrame(e.raf),We.disconnect(),a.removeEventListener("mousemove",Ue),a.removeEventListener("mousedown",Ke),window.removeEventListener("mousemove",He),window.removeEventListener("mouseup",Ge),a.removeEventListener("wheel",_e),a.removeEventListener("contextmenu",Ve)}},[n,l]),(0,o.jsxs)("div",{className:"me-graph",ref:W,children:[(0,o.jsxs)("div",{className:"me-graph-toolbar",children:[(0,o.jsxs)("span",{className:"me-graph-count",children:[n.length," ",i("nodes")," \xB7 ",l.length," ",i("edges")]}),(0,o.jsx)("span",{className:"spacer",style:{flex:1}}),(0,o.jsx)("input",{type:"text",className:"mc-btn",style:{padding:"6px 10px",minWidth:140},placeholder:i("search"),value:q,onChange:a=>Oe(a.target.value)}),(0,o.jsx)("button",{type:"button",className:`mc-btn${j?" me-on":""}`,onClick:()=>Me(a=>!a),children:i("timeDim")}),(0,o.jsx)("button",{type:"button",className:"mc-btn",onClick:()=>{let a=T.current;if(a)try{a.toBlob(t=>{t&&fe({url:URL.createObjectURL(t),blob:t})},"image/png")}catch{}},children:i("exportGraph")}),(0,o.jsx)("button",{type:"button",className:"mc-btn",onClick:()=>E.current&&E.current(),children:i("fit")}),(0,o.jsx)("button",{type:"button",className:"mc-btn",onClick:()=>{se(null),oe("all"),G.current&&G.current()},children:i("reset")})]}),(0,o.jsxs)("div",{className:"me-graph-canvas",style:{position:"relative",overflow:"hidden"},children:[(0,o.jsx)("canvas",{ref:T,style:{width:"100%",height:"100%",display:"block",cursor:"grab"}}),(0,o.jsx)("div",{className:"me-graph-tooltip",ref:_,style:{display:"none",position:"absolute",zIndex:4,pointerEvents:"none",background:"rgba(28,28,32,0.88)",backdropFilter:"blur(10px)",WebkitBackdropFilter:"blur(10px)",color:"#eee",borderRadius:8,padding:"7px 10px",fontSize:12,maxWidth:220,boxShadow:"0 8px 24px rgba(0,0,0,.2)"}}),(0,o.jsxs)("div",{className:"me-graph-legend",style:{position:"absolute",left:12,bottom:8,zIndex:2},children:[j?[{c:"#10b981",l:i("timeNew")},{c:"#f59e0b",l:i("timeRecent")},{c:"#f97316",l:i("timeMonth")},{c:"#94a3b8",l:i("timeOld")}].map(a=>(0,o.jsxs)("span",{className:"lg",children:[(0,o.jsx)("span",{className:"mc-kind",style:{background:a.c}}),a.l]},a.c)):Object.keys(Pe).map(a=>(0,o.jsxs)("button",{type:"button",className:`lg${ue===a?" active":""}`,onClick:()=>oe(t=>t===a?"all":a),children:[(0,o.jsx)("span",{className:"mc-kind",style:{background:$e.colors[a]||Pe[a]}}),i(Ce[a])]},a)),!j&&ue!=="all"&&(0,o.jsxs)("button",{type:"button",className:"lg lg-clear",onClick:()=>oe("all"),children:[i("clearFilter")," \u2715"]})]}),Ye&&(0,o.jsx)("div",{className:"mc-empty",style:{position:"absolute",inset:0,zIndex:2,display:"flex",alignItems:"center",justifyContent:"center",backdropFilter:"blur(2px)",WebkitBackdropFilter:"blur(2px)"},children:i("noMatch")}),O&&(0,o.jsx)("div",{className:"me-graph-ctx-back",style:{position:"fixed",inset:0,zIndex:30},onMouseDown:()=>V(null)}),O&&(0,o.jsxs)("div",{className:"me-graph-ctxmenu",style:{position:"fixed",left:O.x,top:O.y,zIndex:31},onMouseDown:a=>a.stopPropagation(),children:[(0,o.jsx)("button",{type:"button",onClick:()=>{ie.current({path:O.path,title:O.title}),V(null)},children:i("openCard")}),(0,o.jsx)("button",{type:"button",onClick:()=>{O.id&&(C.current.selectedId=O.id,se(O.id)),V(null);let a=C.current;a&&a.wake&&a.wake()},children:i("focusNeighbors")}),(0,o.jsx)("button",{type:"button",onClick:()=>{try{navigator.clipboard&&navigator.clipboard.writeText(O.title||"")}catch{}V(null),F(i("copied"))},children:i("copyName")}),(0,o.jsx)("button",{type:"button",style:{color:"#f87171"},onClick:()=>{let a=O.path;V(null),window.confirm(i("deleteConfirm"))&&(async()=>{try{(pe.current?await pe.current(a):!1)?F(i("deleted")):F(i("deleteFail"),!1)}catch{F(i("deleteFail"),!1)}})()},children:i("delete")})]}),J.length>0&&(0,o.jsxs)("div",{style:{position:"absolute",left:10,top:10,zIndex:3,display:"flex",gap:8,alignItems:"center",background:"rgba(28,28,32,0.92)",backdropFilter:"blur(10px)",WebkitBackdropFilter:"blur(10px)",color:"#eee",borderRadius:10,padding:"6px 10px",fontSize:12,boxShadow:"0 10px 30px rgba(0,0,0,.25)"},children:[(0,o.jsxs)("span",{style:{fontWeight:700},children:[J.length," ",i("nodes")]}),(0,o.jsx)("button",{type:"button",className:"mc-btn",onClick:()=>{let t=J.map(D=>d[D]).filter(Boolean).map(D=>D.title||D.name).join(`
|
|
113
|
-
`),
|
|
112
|
+
`));let Ye=new Blob([q],{type:Ie}),ie=await rt(Ye,Se,x);if(!ie.ok){R({ok:!1,msg:ie.aborted?o("exportCancel"):o("exportFail")}),L(!1);return}R({ok:!0,msg:ie.picked?o("exportedTo")+"\uFF1A"+ie.name:o("exportedTo")+"\uFF1A"+o("defaultDownloads")+" \xB7 "+ie.name})}catch(f){R({ok:!1,msg:o("exportFail")+" \xB7 "+(f.message||"")})}finally{L(!1)}W.current&&clearTimeout(W.current),W.current=setTimeout(()=>R(null),2600)},a=async d=>{let x=d.target.files&&d.target.files[0];if(d.target.value="",!!x){try{let f=await x.text(),q=await(await fetch(`${U}/import`,{method:"POST",headers:{"Content-Type":"application/json"},body:f})).json();q.ok?(await te(),R({ok:!0,msg:o("importedVault")+"\uFF1A"+(q.imported||0)+(q.skipped?o("importedSkipped")+q.skipped:"")})):R({ok:!1,msg:q.error||o("importFail")})}catch{R({ok:!1,msg:o("importFail")})}W.current&&clearTimeout(W.current),W.current=setTimeout(()=>R(null),2400)}},N=(0,c.useMemo)(()=>{let d=g.slice();return J==="title"?d.sort((x,f)=>String(x.title||"").localeCompare(String(f.title||""))):J==="hot"?d.sort((x,f)=>(f.weight||f.links||0)-(x.weight||x.links||0)):d.sort((x,f)=>new Date(f.updated||0).getTime()-new Date(x.updated||0).getTime()),d},[g,J]);return(0,e.jsxs)("div",{className:"memory-eternal-root",style:{height:"100%",display:"flex",flexDirection:"column"},children:[(0,e.jsx)("style",{children:we}),ne&&(0,e.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,position:"fixed",left:"50%",transform:"translateX(-50%)",top:22,zIndex:70,background:"rgba(20,22,26,0.97)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",color:"#f5f5f5",borderRadius:12,padding:"10px 20px",fontSize:13.5,fontWeight:600,boxShadow:"0 14px 44px rgba(0,0,0,.5)",pointerEvents:"none",animation:"me-pop .22s ease",borderLeft:"4px solid "+(ne.ok?"#22c55e":"#ef4444"),maxWidth:"90vw"},children:[(0,e.jsx)("span",{style:{color:ne.ok?"#34d399":"#f87171",fontWeight:800,fontSize:15},children:ne.ok?"\u2713":"\u2715"}),(0,e.jsx)("span",{children:ne.msg})]}),s&&(0,e.jsxs)("div",{className:"me-modal-head",children:[(0,e.jsxs)("div",{className:"me-modal-title",children:[(0,e.jsx)("span",{className:"me-wicon",children:(0,e.jsx)(at,{})}),(0,e.jsx)("h2",{children:o("memoryTitle")}),(0,e.jsx)("span",{children:o("memoryHint")})]}),(0,e.jsx)("div",{className:"spacer"}),(0,e.jsx)("button",{type:"button",className:"me-modal-close",onClick:m,"aria-label":o("close"),children:"\u2715"})]}),(0,e.jsxs)("div",{className:"me-modal-body",children:[(0,e.jsxs)("div",{className:"mc-stats",children:[(0,e.jsx)(Ae,{label:o("total"),value:u?u.total:"\u2014"}),(0,e.jsx)(Ae,{label:o("recent"),value:u?u.recent:"\u2014"}),(0,e.jsx)(Ae,{label:o("tags"),value:u?u.tags:"\u2014"}),(0,e.jsx)(Ae,{label:o("cardCount"),value:u?u.byKind?.knowledge??0:"\u2014"})]}),(0,e.jsxs)("div",{className:"mc-toolbar",children:[(0,e.jsx)("input",{type:"text",placeholder:o("searchPlaceholder"),value:V,onChange:d=>O(d.target.value)}),(0,e.jsxs)("div",{className:"mc-tabs",children:[(0,e.jsx)("button",{type:"button",className:`mc-tab${A==="cards"?" active":""}`,onClick:()=>ce("cards"),children:o("cardsTab")}),(0,e.jsx)("button",{type:"button",className:`mc-tab${A==="graph"?" active":""}`,onClick:()=>ce("graph"),children:o("graphTab")})]}),(0,e.jsx)("input",{ref:h,type:"file",accept:".json,application/json",style:{display:"none"},onChange:a}),(0,e.jsx)("button",{type:"button",className:"mc-btn",onClick:()=>h.current&&h.current.click(),children:o("importVault")}),(0,e.jsxs)("label",{className:"mc-btn",style:{display:"inline-flex",alignItems:"center",gap:5,cursor:"pointer"},title:o("location"),children:[(0,e.jsx)("input",{type:"checkbox",checked:$,onChange:d=>ye(d.target.checked)}),o("location")]}),(0,e.jsx)("button",{type:"button",className:"mc-btn",disabled:j,onClick:()=>i("md",$),children:o(j?"exporting":"exportVault")}),(0,e.jsx)("button",{type:"button",className:"mc-btn",disabled:j,onClick:()=>i("json",$),children:o(j?"exporting":"exportJson")}),(0,e.jsxs)("label",{className:"mc-btn",style:{display:"inline-flex",alignItems:"center",gap:5,cursor:"pointer"},title:o("crossVault"),children:[(0,e.jsx)("input",{type:"checkbox",checked:Ce,onChange:d=>re(d.target.checked)}),o("crossVault")]}),(0,e.jsx)("button",{type:"button",className:"mc-btn",onClick:()=>G({tab:"stats"}),children:o("manage")}),(0,e.jsx)("button",{type:"button",className:"mc-btn",onClick:()=>te(),children:o("refresh")})]}),A==="cards"&&(0,e.jsxs)("div",{className:"mc-chips",children:[yt.map(d=>(0,e.jsx)("button",{type:"button",className:`mc-chip${_===d?" active":""}`,onClick:()=>Me(d),children:o(d==="all"?"all":ve[d])},d)),(0,e.jsx)("span",{className:"spacer",style:{flex:1}}),[{key:"recent",label:o("sortRecent")},{key:"title",label:o("sortTitle")},{key:"hot",label:o("sortHot")}].map(d=>(0,e.jsx)("button",{type:"button",className:`mc-chip${J===d.key?" active":""}`,onClick:()=>ue(d.key),children:d.label},d.key))]}),T&&(0,e.jsxs)("div",{className:"mc-empty",children:[o("error"),"\uFF1A",T]}),A==="cards"?z&&!g.length?(0,e.jsx)("div",{className:"mc-empty",children:o("loading")}):g.length===0?(0,e.jsx)("div",{className:"mc-empty",children:o("empty")}):(0,e.jsxs)(e.Fragment,{children:[(0,e.jsx)("div",{className:"mc-grid",children:N.slice(0,fe).map(d=>(0,e.jsx)(kt,{card:d,t:o,query:V.trim(),onOpen:Z,onDelete:be},d.path))}),N.length>fe&&(0,e.jsx)("div",{ref:xe,style:{height:1}})]}):(0,e.jsx)(Mt,{t:o,onOpen:Z,all:Ce}),ee&&(0,e.jsx)(Nt,{t:o,card:ee,onClose:()=>S(null),onDelete:d=>{S(null),be(d)}}),H&&(0,e.jsx)(Ct,{t:o,tab:H.tab,onTab:d=>G({tab:d}),onClose:()=>G(null),onReload:()=>te()})]})]})}var Ae=({label:o,value:s})=>(0,e.jsxs)("div",{className:"mc-stat mc-card",children:[(0,e.jsx)("b",{children:s}),(0,e.jsx)("span",{children:o})]}),kt=({card:o,t:s,onOpen:m,query:u,onDelete:n})=>(0,e.jsxs)("article",{className:"mc-cardrow mc-card",onClick:()=>m(o),children:[(0,e.jsxs)("h4",{children:[(0,e.jsx)("span",{className:"mc-kind",style:{background:We[o.kind]||We.other}}),u?ot(o.title,u):o.title,Tt(o.updated)&&(0,e.jsx)("span",{className:"mc-new",children:s("newBadge")})]}),(0,e.jsx)("p",{children:u?ot(o.summary||"",u):o.summary||""}),o.tags.length>0&&(0,e.jsx)("div",{className:"mc-tags",children:o.tags.slice(0,4).map(g=>(0,e.jsx)("span",{className:"mc-tag",children:g},g))}),(0,e.jsxs)("footer",{children:[(0,e.jsx)("span",{children:s(ve[o.kind])}),(0,e.jsx)("span",{children:it(o.updated)}),(0,e.jsx)("span",{className:"spacer",style:{flex:1}}),(0,e.jsx)("button",{type:"button",className:"mc-card-del",title:s("delete"),onClick:g=>{g.stopPropagation(),window.confirm(s("deleteConfirm"))&&n&&n(o.path)},children:"\u2715"})]})]});function Ct({t:o,tab:s,onTab:m,onClose:u,onReload:n}){let[g,I]=(0,c.useState)(null),[z,P]=(0,c.useState)(null),[T,F]=(0,c.useState)(null),[_,me]=(0,c.useState)(""),[V,ke]=(0,c.useState)(""),A=(0,c.useCallback)(async()=>{try{let h=await fetch(`${U}/todayBrief`).then(j=>j.json());me(h.ok&&h.brief||"")}catch{}},[]),ce=(0,c.useCallback)(async()=>{if(!(!z||!z.merge||!z.merge.length)&&window.confirm(o("mergeAllConfirm"))){ke("merge");try{let h={},j=S=>h[S]===void 0?S:h[S]=j(h[S]),L=(S,H)=>{h[j(S)]=j(H)},$=new Set;for(let S of z.merge)$.add(S.a.path),$.add(S.b.path),L(S.a.path,S.b.path);let ye={};for(let S of $){let H=j(S);(ye[H]=ye[H]||[]).push(S)}let ee=0;for(let S of Object.values(ye)){if(S.length<2)continue;(await fetch(`${U}/merge?paths=${encodeURIComponent(S.join(","))}`).then(G=>G.json())).ok&&ee++}await J(),n&&n()}catch{}ke("")}},[z,J,n,o]),J=(0,c.useCallback)(async()=>{try{let[h,j,L]=await Promise.all([fetch(`${U}/stats`).then($=>$.json()),fetch(`${U}/optimize`).then($=>$.json()),fetch(`${U}/budget`).then($=>$.json())]);h.ok&&I(h),j.ok&&P(j),L.ok&&F(L)}catch{}},[]);(0,c.useEffect)(()=>{J()},[J]);let ue=async(h,j)=>{if(window.confirm(o("mergeConfirm")))try{(await fetch(`${U}/merge?paths=${encodeURIComponent(h+","+j)}`).then($=>$.json())).ok&&(await J(),n&&n())}catch{}},ne=async h=>{if(window.confirm(o("deleteConfirm")))try{(await fetch(`${U}/delete?path=${encodeURIComponent(h)}`).then(L=>L.json())).ok&&(await J(),n&&n())}catch{}},R=["project","knowledge","content","prompt","business","tool","mistake"],W=({title:h,kind:j,updated:L,path:$})=>(0,e.jsxs)("li",{style:{display:"flex",alignItems:"center",gap:8,padding:"3px 4px",borderBottom:"1px solid rgba(127,127,127,0.12)"},children:[(0,e.jsx)("span",{className:"mc-kind",style:{background:Ee.colors[j]||"#666"}}),(0,e.jsx)("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:h}),(0,e.jsx)("span",{style:{opacity:.55,fontSize:11},children:it(L)}),(0,e.jsxs)("button",{type:"button",className:"mc-btn",style:{padding:"2px 8px"},onClick:()=>ne($),children:[o("delete")," \u2715"]})]});return(0,e.jsxs)("div",{className:"me-overlay",onClick:u,children:[(0,e.jsx)("style",{children:we}),(0,e.jsxs)("div",{className:"me-dialog",style:{maxWidth:720,width:"94vw",maxHeight:"86vh"},onClick:h=>h.stopPropagation(),children:[(0,e.jsxs)("div",{className:"me-dialog-head",children:[(0,e.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,e.jsx)("button",{type:"button",className:`mc-tab${s==="stats"?" active":""}`,onClick:()=>m("stats"),children:o("tabUsage")}),(0,e.jsx)("button",{type:"button",className:`mc-tab${s==="optimize"?" active":""}`,onClick:()=>m("optimize"),children:o("tabOptimize")})]}),(0,e.jsx)("div",{className:"spacer",style:{flex:1}}),(0,e.jsx)("button",{type:"button",className:"mc-btn",onClick:u,children:o("close")})]}),(0,e.jsxs)("div",{className:"me-dialog-body",style:{overflow:"auto"},children:[s==="stats"&&(0,e.jsxs)("div",{children:[(0,e.jsxs)("div",{className:"mc-card",style:{marginBottom:10,display:"flex",gap:10,alignItems:"center",flexWrap:"wrap"},children:[(0,e.jsx)("b",{style:{fontSize:12},children:o("todayBriefLabel")}),(0,e.jsx)("button",{type:"button",className:"mc-btn",onClick:A,children:o("todayBrief")}),_&&(0,e.jsx)("pre",{style:{margin:0,fontSize:12,width:"100%",whiteSpace:"pre-wrap",opacity:.85},children:_})]}),g&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)("div",{className:"mc-stats",children:[(0,e.jsxs)("div",{className:"mc-stat mc-card",children:[(0,e.jsx)("b",{children:g.total}),(0,e.jsx)("span",{children:o("total")})]}),(0,e.jsxs)("div",{className:"mc-stat mc-card",children:[(0,e.jsx)("b",{children:g.today}),(0,e.jsx)("span",{children:o("todayAdd")})]}),(0,e.jsxs)("div",{className:"mc-stat mc-card",children:[(0,e.jsx)("b",{children:g.week}),(0,e.jsx)("span",{children:o("weekAdd")})]}),(0,e.jsxs)("div",{className:"mc-stat mc-card",children:[(0,e.jsx)("b",{children:g.tags}),(0,e.jsx)("span",{children:o("tags")})]})]}),(0,e.jsxs)("div",{className:"mc-card",style:{marginBottom:10},children:[(0,e.jsx)("div",{style:{fontSize:12,fontWeight:700,marginBottom:6},children:o("byKind")}),(0,e.jsx)("div",{style:{display:"flex",gap:10,flexWrap:"wrap"},children:R.map(h=>(0,e.jsxs)("span",{style:{fontSize:12},children:[(0,e.jsx)("span",{className:"mc-kind",style:{background:Ee.colors[h]||"#666"}}),o(ve[h]),": ",g.byKind?.[h]||0]},h))})]}),T&&(T.budgetChars||T.recallLimit||T.embedding)&&(0,e.jsxs)("div",{className:"mc-card",style:{marginBottom:10,fontSize:12},children:[(0,e.jsx)("b",{children:o("budgetLabel")}),"\uFF1A",o("budgetChars")," ",(0,e.jsx)("b",{children:T.budgetChars||8e4})," \xB7 ",o("recallLimitLabel")," ",(0,e.jsx)("b",{children:T.recallLimit||5})," \xB7 ",o("embeddingLabel")," ",T.embedding?"ON":"OFF"]}),(0,e.jsxs)("div",{className:"mc-card",children:[(0,e.jsxs)("div",{style:{fontSize:12,fontWeight:700,marginBottom:6},children:[o("todayList"),"\uFF08",g.todayCards?.length||0,"\uFF09"]}),g.todayCards?.length?(0,e.jsx)("ul",{style:{margin:0,padding:0,listStyle:"none"},children:g.todayCards.map(h=>(0,e.jsx)(W,{title:h.title,kind:h.kind,updated:h.updated,path:h.path},h.path))}):(0,e.jsx)("div",{style:{opacity:.6,fontSize:12},children:o("noOptimize")})]})]})]}),s==="optimize"&&(0,e.jsx)("div",{children:z&&(0,e.jsxs)(e.Fragment,{children:[(0,e.jsxs)("div",{className:"mc-card",style:{marginBottom:10,display:"flex",gap:10,alignItems:"center"},children:[(0,e.jsx)("b",{style:{fontSize:12},children:z.merge?.length?o("mergePairs"):o("noOptimize")}),(0,e.jsx)("div",{className:"spacer",style:{flex:1}}),z.merge?.length>0&&(0,e.jsx)("button",{type:"button",className:"mc-btn me-on",disabled:!!V,onClick:ce,children:o(V==="merge"?"exporting":"batchMerge")})]}),(0,e.jsx)("div",{style:{fontSize:12,fontWeight:700,marginBottom:6},children:o("mergePairs")}),z.merge?.length?(0,e.jsx)("ul",{style:{margin:"0 0 12px",padding:0,listStyle:"none"},children:z.merge.map((h,j)=>(0,e.jsxs)("li",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 4px",borderBottom:"1px solid rgba(127,127,127,0.12)",fontSize:12},children:[(0,e.jsxs)("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[h.a.title," \u21C4 ",h.b.title]}),(0,e.jsxs)("span",{style:{opacity:.6},children:[Math.round(h.sim*100),"%"]}),(0,e.jsx)("button",{type:"button",className:"mc-btn",style:{padding:"2px 8px"},onClick:()=>ue(h.a.path,h.b.path),children:o("mergeNow")})]},j))}):(0,e.jsx)("div",{style:{opacity:.6,fontSize:12,marginBottom:12},children:o("noOptimize")}),(0,e.jsxs)("div",{style:{fontSize:12,fontWeight:700,marginBottom:6},children:[o("staleCards"),"\uFF08",z.stale?.length||0,"\uFF09"]}),z.stale?.length?(0,e.jsx)("ul",{style:{margin:0,padding:0,listStyle:"none"},children:z.stale.map(h=>(0,e.jsx)(W,{title:h.title,kind:"other",updated:h.updated,path:h.path},h.path))}):(0,e.jsx)("div",{style:{opacity:.6,fontSize:12},children:o("noOptimize")})]})})]})]})]})}function Nt({t:o,card:s,onClose:m,onDelete:u}){(0,c.useEffect)(()=>{let z=P=>{P.key==="Escape"&&m()};return window.addEventListener("keydown",z),()=>window.removeEventListener("keydown",z)},[m]);let[n,g]=(0,c.useState)(!1),I=(s.text||"").length>460;return(0,e.jsxs)("div",{className:"me-overlay",onClick:m,children:[(0,e.jsx)("style",{children:we}),(0,e.jsxs)("div",{className:"me-dialog",onClick:z=>z.stopPropagation(),children:[(0,e.jsxs)("div",{className:"me-dialog-head",children:[(0,e.jsx)("h3",{children:s.title}),(0,e.jsxs)("div",{style:{display:"flex",gap:8},children:[I&&(0,e.jsx)("button",{type:"button",className:"mc-btn",onClick:()=>g(z=>!z),children:o(n?"collapse":"expand")}),(0,e.jsx)("button",{type:"button",className:"mc-btn",style:{color:"#f87171"},onClick:()=>{window.confirm(o("deleteConfirm"))&&u&&u(s.path)},children:o("delete")}),(0,e.jsx)("button",{type:"button",className:"mc-btn",onClick:m,children:o("close")})]})]}),(0,e.jsx)("div",{className:"me-dialog-body",style:n?{}:{maxHeight:300,overflow:"hidden"},dangerouslySetInnerHTML:{__html:Lt(s.text)}})]})]})}function Mt({t:o,onOpen:s,all:m}){let[u,n]=(0,c.useState)(null),[g,I]=(0,c.useState)(""),z=(0,c.useCallback)(async()=>{try{let F=await(await fetch(`${U}/graph${m?"?all=1":""}`)).json();n(F.ok?F:null),I("")}catch(T){I(String(T&&T.message?T.message:T))}},[m]);(0,c.useEffect)(()=>{let T=!0;return fetch(`${U}/graph${m?"?all=1":""}`).then(F=>F.json()).then(F=>{T&&n(F.ok?F:null)}).catch(F=>{T&&I(String(F&&F.message?F.message:F))}),()=>{T=!1}},[m]);let P=(0,c.useCallback)(async T=>{try{let _=await(await fetch(`${U}/delete?path=${encodeURIComponent(T)}`)).json();return _&&_.ok?(await z(),!0):!1}catch{return!1}},[z]);return(0,e.jsxs)("div",{className:"me-graph",children:[(0,e.jsx)("style",{children:we}),g&&(0,e.jsxs)("div",{className:"mc-empty",children:[o("error"),"\uFF1A",g]}),!u&&!g&&(0,e.jsx)("div",{className:"mc-empty",children:o("loading")}),u&&u.nodes.length===0&&(0,e.jsx)("div",{className:"mc-empty",children:o("emptyGraph")}),u&&u.nodes.length>0&&(0,e.jsx)(It,{nodes:u.nodes,edges:u.edges,onOpen:s,onDelete:P,t:o,countLabel:`${u.nodes.length} ${o("nodes")} \xB7 ${St(u.edges)} ${o("edges")}`})]})}function St(o){let s=new Set;for(let m of o||[])s.add([m.source,m.target].sort().join("|"));return s.size}var Ee={colors:{project:"#3B82F6",knowledge:"#10B981",content:"#F59E0B",prompt:"#A855F7",business:"#EC4899",tool:"#06B6D4",mistake:"#EF4444",other:"#6B7280"},shapes:{project:"circle",knowledge:"circle",content:"rect",prompt:"diamond",business:"hexagon",tool:"circle",mistake:"diamond",other:"circle"}};function It({nodes:o,edges:s,onOpen:m,onDelete:u,t:n,countLabel:g}){let I=(0,c.useRef)(null),z=(0,c.useRef)(null),P=(0,c.useRef)(null),T=(0,c.useRef)(null),F=(0,c.useRef)(null),_=(0,c.useRef)(m);(0,c.useEffect)(()=>{_.current=m},[m]);let me=(0,c.useRef)(u);(0,c.useEffect)(()=>{me.current=u},[u]);let[V,ke]=(0,c.useState)(""),[A,ce]=(0,c.useState)(null),J=(0,c.useRef)("");(0,c.useEffect)(()=>{J.current=V.trim().toLowerCase()},[V]);let[ue,ne]=(0,c.useState)("all"),R=(0,c.useRef)("all"),[W,h]=(0,c.useState)(!1),j=(0,c.useRef)(!1),[L,$]=(0,c.useState)(null);(0,c.useEffect)(()=>{R.current=ue},[ue]),(0,c.useEffect)(()=>{j.current=W},[W]);let ye=(()=>{let i=V.trim().toLowerCase();return!!i&&!o.some(a=>(a.title||a.name||"").toLowerCase().includes(i)||String(a.kind||"").toLowerCase().includes(i)||String(ve[a.kind]||"").toLowerCase().includes(i))})();(0,c.useEffect)(()=>{let i=P.current;i&&i.wake&&i.wake()},[V]),(0,c.useEffect)(()=>{let i=P.current;i&&i.render&&i.render()},[ue,W]);let ee=(0,c.useRef)(null),[S,H]=(0,c.useState)([]),[G,Ce]=(0,c.useState)(null),[re,de]=(0,c.useState)(!1),[fe,Ne]=(0,c.useState)(null),[xe,Fe]=(0,c.useState)(""),te=(0,c.useRef)(null),be=(0,c.useRef)(null),O=(i,a=!0)=>{te.current&&clearTimeout(te.current),Ne({msg:i,ok:a}),te.current=setTimeout(()=>Ne(null),1900)},Me=i=>{Fe(i),be.current&&clearTimeout(be.current),be.current=setTimeout(()=>Fe(""),1600)};(0,c.useEffect)(()=>()=>{te.current&&clearTimeout(te.current),be.current&&clearTimeout(be.current)},[]);let Z=(0,c.useMemo)(()=>o.reduce((i,a)=>(i[a.id]=a,i),{}),[o]);return(0,c.useEffect)(()=>{let i=I.current;if(!i||o.length===0)return;let a=i.getContext("2d");if(!a)return;let N=Math.max(1,window.devicePixelRatio||1),d=()=>document.documentElement.getAttribute("data-theme")==="dark",x={};s.forEach(r=>{x[r.source]=(x[r.source]||0)+1,x[r.target]=(x[r.target]||0)+1});let f=Math.max(1,...Object.values(x)),t={nodes:o.map(r=>({id:r.id,name:r.title||"",type:r.kind||"other",r:9+Math.min(10,(x[r.id]||0)/f*8),x:0,y:0,vx:0,vy:0})),edges:s.map(r=>({sourceNodeId:r.source,targetNodeId:r.target,weight:1})),panX:0,panY:0,zoom:1,running:!0,raf:0,tickCount:0,quietTicks:0,dragNode:null,selectedId:null,mouseX:0,mouseY:0,w:0,h:0,dpr:N,ctx:a,multi:[],marquee:null};t.domain=o,t.domainById=o.reduce((r,b)=>(r[b.id]=b,r),{}),t.nodes.forEach((r,b)=>{let p=b/t.nodes.length*Math.PI*2-Math.PI/2;r.x=Math.cos(p)*60,r.y=Math.sin(p)*60});let q=[...new Set(t.nodes.map(r=>r.type))];t.clustered=q.length>1,t.typeCenters={},q.forEach((r,b)=>{let p=b/q.length*Math.PI*2-Math.PI/2;t.typeCenters[r]={x:Math.cos(p)*160,y:Math.sin(p)*160}}),P.current=t;let Se=()=>{let r=i.clientWidth,b=i.clientHeight;t.w=r,t.h=b,i.width=r*N,i.height=b*N,a.setTransform(N,0,0,N,0,0)};Se();let Ie=new ResizeObserver(Se);Ie.observe(i.parentElement);let Ye=(r,b)=>r&&r.length>b?r.slice(0,b)+"\u2026":r,ie=(r,b,p,y)=>{if(a.beginPath(),y==="rect")a.rect(r-p,b-p*.75,p*2,p*1.5);else if(y==="diamond")a.moveTo(r,b-p),a.lineTo(r+p,b),a.lineTo(r,b+p),a.lineTo(r-p,b),a.closePath();else if(y==="hexagon"){for(let v=0;v<6;v++){let C=Math.PI/3*v-Math.PI/2,B=r+p*Math.cos(C),l=b+p*Math.sin(C);v===0?a.moveTo(B,l):a.lineTo(B,l)}a.closePath()}else a.arc(r,b,p,0,Math.PI*2)},se=()=>{if(!t.nodes.length)return;let r=1/0,b=-1/0,p=1/0,y=-1/0;t.nodes.forEach(M=>{r=Math.min(r,M.x),b=Math.max(b,M.x),p=Math.min(p,M.y),y=Math.max(y,M.y)});let v=36,C=b-r+v*2,B=y-p+v*2,l=Math.min(t.w/C,t.h/B);t.zoom=Math.max(.45,Math.min(2.4,l*1.22)),t.panX=t.w/2-(r+b)/2*t.zoom,t.panY=t.h/2-(p+y)/2*t.zoom};T.current=se;let Ue=()=>{a.clearRect(0,0,t.w,t.h),t.searchTerm=J.current,t.kindFilter=R.current,t.timeMode=j.current;let r=t.kindFilter,b=l=>String(l||"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");a.save(),a.strokeStyle=d()?"rgba(255,255,255,0.04)":"rgba(0,0,0,0.04)",a.lineWidth=.5;for(let l=0;l<t.w;l+=24)a.beginPath(),a.moveTo(l,0),a.lineTo(l,t.h),a.stroke();for(let l=0;l<t.h;l+=24)a.beginPath(),a.moveTo(0,l),a.lineTo(t.w,l),a.stroke();a.restore(),a.save(),a.translate(t.panX,t.panY),a.scale(t.zoom,t.zoom);let p={};t.nodes.forEach(l=>p[l.id]=l);let y=t.nodes.length>40,v=y?1.5:.55,C=t.selectedId||t.hoverId;t.edges.forEach(l=>{let M=p[l.sourceNodeId],E=p[l.targetNodeId];if(!M||!E)return;if(r!=="all"){let Q=t.domainById[l.sourceNodeId]&&t.domainById[l.sourceNodeId].kind,Qe=t.domainById[l.targetNodeId]&&t.domainById[l.targetNodeId].kind;if(Q!==r&&Qe!==r)return}let w=E.x-M.x,k=E.y-M.y,D=Math.sqrt(w*w+k*k)||1,Y=y?12:18,X=-k/D*Y,oe=w/D*Y,K=(M.x+E.x)/2+X,pe=(M.y+E.y)/2+oe,ae=Ee.colors[t.domainById[M.id]&&t.domainById[M.id].kind||"other"],ge=C&&(l.sourceNodeId===C||l.targetNodeId===C),ze=C?ge?.6:.08:y?.14:.24,je=parseInt(ae.slice(1,3),16),De=parseInt(ae.slice(3,5),16),Ze=parseInt(ae.slice(5,7),16);a.strokeStyle="rgba("+je+","+De+","+Ze+","+ze+")",a.lineWidth=ge?1.6+(l.weight||1):.8+(l.weight||1)*.5,a.beginPath(),a.moveTo(M.x,M.y),a.quadraticCurveTo(K,pe,E.x,E.y),a.stroke()});let B=[];if(t.nodes.forEach(l=>{let M=t.domainById[l.id]||{},E=M.kind||"other",w=t.timeMode?zt(M.updated):Ee.colors[E],k=Ee.shapes[E],D=t.selectedId===l.id,Y=t.hoverId===l.id,X=t.searchTerm||"",oe=!X||(l.name||"").toLowerCase().includes(X)||String(ve[E]||"").toLowerCase().includes(X)||String(E).toLowerCase().includes(X),K=r==="all"||E===r,pe=C&&l.id!==C&&!t.edges.some(Q=>Q.sourceNodeId===C&&Q.targetNodeId===l.id||Q.targetNodeId===C&&Q.sourceNodeId===l.id)||X&&!oe||!K;a.save(),a.globalAlpha=pe?.08:1,(D||Y)&&(a.shadowColor=w,a.shadowBlur=D?20:14),ie(l.x,l.y,l.r,k);let ae=parseInt(w.slice(1,3),16),ge=parseInt(w.slice(3,5),16),ze=parseInt(w.slice(5,7),16),je=a.createRadialGradient(l.x-l.r*.3,l.y-l.r*.3,0,l.x,l.y,l.r*1.2);je.addColorStop(0,"rgba("+Math.min(255,ae+70)+","+Math.min(255,ge+70)+","+Math.min(255,ze+70)+",0.95)"),je.addColorStop(1,w),a.fillStyle=je,a.fill(),a.restore(),D?(a.save(),ie(l.x,l.y,l.r+3,k),a.strokeStyle=w,a.lineWidth=3,a.shadowColor=w,a.shadowBlur=12,a.stroke(),a.restore()):Y?(a.save(),ie(l.x,l.y,l.r+2,k),a.strokeStyle=w,a.lineWidth=2,a.stroke(),a.restore()):X&&oe?(a.save(),ie(l.x,l.y,l.r+2,k),a.strokeStyle="#e11d48",a.lineWidth=2,a.stroke(),a.restore()):t.multi.indexOf(l.id)>=0&&(a.save(),ie(l.x,l.y,l.r+2,k),a.strokeStyle="#60a5fa",a.lineWidth=2,a.shadowColor="#60a5fa",a.shadowBlur=8,a.stroke(),a.restore());let De=Ye(l.name,16);if((D||Y||t.zoom>v||!y&&t.zoom>.6)&&K){let Q=1/t.zoom;a.font="500 "+(12*Q).toFixed(1)+"px -apple-system,Segoe UI,sans-serif";let he=a.measureText(De).width+16*Q,Oe=18*Q,Te=l.y+l.r+8*Q,et=!0;for(let Le of B)if(l.x-he/2<Le.x+Le.w&&l.x+he/2>Le.x&&Te<Le.y+Le.h&&Te+Oe>Le.y){et=!1;break}if(!et&&!D&&!Y)return;B.push({x:l.x-he/2,y:Te,w:he,h:Oe}),a.fillStyle=d()?"rgba(30,30,35,0.92)":"rgba(255,255,255,0.92)",a.beginPath(),a.roundRect?a.roundRect(l.x-he/2,Te,he,Oe,4*Q):a.rect(l.x-he/2,Te,he,Oe),a.fill(),a.strokeStyle=d()?"rgba(255,255,255,0.08)":"rgba(0,0,0,0.08)",a.lineWidth=1*Q,a.stroke(),a.fillStyle=d()?D||Y?"#eee":"#bbb":D||Y?"#111":"#444",a.textAlign="center",a.fillText(De,l.x,Te+13*Q)}}),a.restore(),t.marquee){let l=t.marquee,M=Math.min(l.sx,l.ex),E=Math.min(l.sy,l.ey),w=Math.abs(l.ex-l.sx),k=Math.abs(l.ey-l.sy);a.save(),a.setLineDash([4,4]),a.strokeStyle="rgba(96,165,250,0.9)",a.lineWidth=1,a.fillStyle="rgba(96,165,250,0.12)",a.fillRect(M,E,w,k),a.strokeRect(M,E,w,k),a.restore()}if(t.hoverId&&ee.current){let l=t.domainById[t.hoverId],M=t.nodes.find(function(E){return E.id===t.hoverId});if(l&&M){let E=t.edges.filter(function(D){return D.sourceNodeId===l.id||D.targetNodeId===l.id}).length,w=M.x*t.zoom+t.panX,k=M.y*t.zoom+t.panY;ee.current.style.display="block",ee.current.style.left=w+14+"px",ee.current.style.top=k-6+"px",ee.current.innerHTML="<b>"+b(l.title||l.name||"")+'</b><br/><span style="opacity:.8">'+b(l.kind||"")+" \xB7 "+E+" \u8FDE\u63A5</span>"}}else ee.current&&(ee.current.style.display="none")},le=()=>{t.running=!0,t.raf||(t.raf=requestAnimationFrame(Xe))};t.wake=le,t.render=Ue;let qe=()=>{let r=t.nodes.length;t.tickCount++;let p=.9-Math.min(.4,t.tickCount/1500),y=r>1e3?3e3:r>100?2e3:r>50?1200:800,v=r>100?.002:.005,C=r>1e3?.012:r>100?.005:.01,B=r>1e3?6:r>200?12:24,l={};t.nodes.forEach(w=>l[w.id]=w);for(let w=0;w<r;w++){if(t.dragNode===t.nodes[w])continue;let k=t.nodes[w],D=0,Y=0;for(let K=0;K<r;K++){if(w===K)continue;let pe=k.x-t.nodes[K].x,ae=k.y-t.nodes[K].y,ge=Math.sqrt(pe*pe+ae*ae)||1,ze=y/(ge*ge);D+=pe/ge*ze,Y+=ae/ge*ze}if(t.clustered&&t.typeCenters[k.type]){let K=t.typeCenters[k.type];D+=(K.x-k.x)*.006,Y+=(K.y-k.y)*.006}else D-=k.x*C,Y-=k.y*C;let X=(k.vx+D)*p,oe=(k.vy+Y)*p;X=Math.max(-B,Math.min(B,X)),oe=Math.max(-B,Math.min(B,oe)),k.vx=X,k.vy=oe}t.edges.forEach(w=>{let k=l[w.sourceNodeId],D=l[w.targetNodeId];if(!k||!D)return;let Y=D.x-k.x,X=D.y-k.y,oe=Math.sqrt(Y*Y+X*X)||1,K=(oe-100)*v,pe=Y/oe*K,ae=X/oe*K;t.dragNode!==k&&(k.vx+=pe,k.vy+=ae),t.dragNode!==D&&(D.vx-=pe,D.vy-=ae)});let M=0;t.nodes.forEach(w=>{t.dragNode!==w&&(w.x+=w.vx,w.y+=w.vy,M+=w.vx*w.vx+w.vy*w.vy)}),t.autoFitPending&&t.tickCount>45&&(t.autoFitPending=!1,se()),(r?Math.sqrt(M/r):0)<.05&&t.tickCount>60&&!t.dragNode?t.quietTicks=(t.quietTicks|0)+1:t.quietTicks=0},Xe=()=>{if(t.running){try{qe(),Ue()}catch{}if(t.quietTicks>30){t.raf=0;return}t.raf=requestAnimationFrame(Xe)}},Re=(r,b)=>{let p=i.getBoundingClientRect();return{x:(r-p.left-t.panX)/t.zoom,y:(b-p.top-t.panY)/t.zoom}},$e=(r,b,p)=>Math.max(b,Math.min(p,r)),Ke=r=>{t.mouseX=r.clientX,t.mouseY=r.clientY;let b=Re(r.clientX,r.clientY),p=null;for(let y=t.nodes.length-1;y>=0;y--){let v=t.nodes[y];if(R.current!=="all"&&(t.domainById[v.id]&&t.domainById[v.id].kind)!==R.current)continue;let C=v.x-b.x,B=v.y-b.y;if(C*C+B*B<v.r*v.r+36){p=v.id;break}}p!==t.hoverId&&(t.hoverId=p,le())},Ve=r=>{if(r.button!==0)return;let b=Re(r.clientX,r.clientY),p=null;for(let y=t.nodes.length-1;y>=0;y--){let v=t.nodes[y];if(R.current!=="all"&&(t.domainById[v.id]&&t.domainById[v.id].kind)!==R.current)continue;let C=v.x-b.x,B=v.y-b.y;if(C*C+B*B<v.r*v.r+25){p=v;break}}if(r.shiftKey){t.marquee={sx:r.clientX,sy:r.clientY,ex:r.clientX,ey:r.clientY};return}t.dragStart={x:r.clientX,y:r.clientY,px:t.panX,py:t.panY},t.dragging=!1,t.dragNode=p||null,p&&(t.dragOffset={dx:p.x-b.x,dy:p.y-b.y})},He=r=>{if(t.marquee){t.marquee.ex=r.clientX,t.marquee.ey=r.clientY,le();return}if(!t.dragStart)return;let b=r.clientX-t.dragStart.x,p=r.clientY-t.dragStart.y;if(Math.abs(b)+Math.abs(p)>3&&(t.dragging=!0),t.dragNode){let y=Re(r.clientX,r.clientY);t.dragNode.x=y.x+t.dragOffset.dx,t.dragNode.y=y.y+t.dragOffset.dy,le()}else t.dragging&&(t.panX=$e(t.dragStart.px+b,-1e5,1e5),t.panY=$e(t.dragStart.py+p,-1e5,1e5),le())},Ge=r=>{if(t.marquee){let p=t.marquee;t.marquee=null;let y=i.getBoundingClientRect(),v=Math.min(p.sx,p.ex)-y.left,C=Math.max(p.sx,p.ex)-y.left,B=Math.min(p.sy,p.ey)-y.top,l=Math.max(p.sy,p.ey)-y.top,M=t.nodes.filter(E=>{let w=E.x*t.zoom+t.panX,k=E.y*t.zoom+t.panY;return w>=v&&w<=C&&k>=B&&k<=l}).map(E=>E.id);t.multi=M,H(M),le();return}if(t.dragStart&&!t.dragging){let p=Re(r.clientX,r.clientY),y=null;for(let v=t.nodes.length-1;v>=0;v--){let C=t.nodes[v];if(R.current!=="all"&&(t.domainById[C.id]&&t.domainById[C.id].kind)!==R.current)continue;let B=C.x-p.x,l=C.y-p.y;if(B*B+l*l<C.r*C.r+20){y=C;break}}y?(t.selectedId=y.id,ce(y.id),le()):(t.selectedId=null,t.hoverId=null,r.shiftKey||(t.multi=[],H([])),ce(null),le())}t.dragStart=null,t.dragging=!1,t.dragNode=null},_e=r=>{r.preventDefault();let b=Re(r.clientX,r.clientY),p=null;for(let y=t.nodes.length-1;y>=0;y--){let v=t.nodes[y];if(R.current!=="all"&&(t.domainById[v.id]&&t.domainById[v.id].kind)!==R.current)continue;let C=v.x-b.x,B=v.y-b.y;if(C*C+B*B<v.r*v.r+25){p=v;break}}if(p){let y=t.domainById[p.id];y&&$({x:r.clientX,y:r.clientY,id:p.id,path:y.id,title:y.title})}else $(null)},Je=r=>{r.preventDefault();let b=i.getBoundingClientRect(),p=(r.clientX-b.left-t.panX)/t.zoom,y=(r.clientY-b.top-t.panY)/t.zoom,v=Math.max(.3,Math.min(3,t.zoom*(r.deltaY<0?1.1:1/1.1)));t.panX=$e(t.panX+p*(t.zoom-v),-1e5,1e5),t.panY=$e(t.panY+y*(t.zoom-v),-1e5,1e5),t.zoom=v,le()};i.addEventListener("mousemove",Ke),i.addEventListener("mousedown",Ve),window.addEventListener("mousemove",He),window.addEventListener("mouseup",Ge),i.addEventListener("wheel",Je,{passive:!1}),i.addEventListener("contextmenu",_e),F.current=()=>{t.selectedId=null,t.hoverId=null,t.multi=[],H([]),se(),le()};for(let r=0;r<200;r++)qe();return se(),le(),()=>{t.running=!1,t.raf&&cancelAnimationFrame(t.raf),Ie.disconnect(),i.removeEventListener("mousemove",Ke),i.removeEventListener("mousedown",Ve),window.removeEventListener("mousemove",He),window.removeEventListener("mouseup",Ge),i.removeEventListener("wheel",Je),i.removeEventListener("contextmenu",_e)}},[o,s]),(0,e.jsxs)("div",{className:"me-graph",ref:z,children:[(0,e.jsxs)("div",{className:"me-graph-toolbar",children:[(0,e.jsxs)("span",{className:"me-graph-count",children:[o.length," ",n("nodes")," \xB7 ",s.length," ",n("edges")]}),(0,e.jsx)("span",{className:"spacer",style:{flex:1}}),(0,e.jsx)("input",{type:"text",className:"mc-btn",style:{padding:"6px 10px",minWidth:140},placeholder:n("search"),value:V,onChange:i=>ke(i.target.value)}),(0,e.jsx)("button",{type:"button",className:`mc-btn${W?" me-on":""}`,onClick:()=>h(i=>!i),children:n("timeDim")}),(0,e.jsx)("button",{type:"button",className:"mc-btn",onClick:()=>{let i=I.current;if(i)try{i.toBlob(a=>{a&&Ce({url:URL.createObjectURL(a),blob:a})},"image/png")}catch{}},children:n("exportGraph")}),(0,e.jsx)("button",{type:"button",className:"mc-btn",onClick:()=>T.current&&T.current(),children:n("fit")}),(0,e.jsx)("button",{type:"button",className:"mc-btn",onClick:()=>{ce(null),ne("all"),F.current&&F.current()},children:n("reset")})]}),(0,e.jsxs)("div",{className:"me-graph-canvas",style:{position:"relative",overflow:"hidden"},children:[(0,e.jsx)("canvas",{ref:I,style:{width:"100%",height:"100%",display:"block",cursor:"grab"}}),(0,e.jsx)("div",{className:"me-graph-tooltip",ref:ee,style:{display:"none",position:"absolute",zIndex:4,pointerEvents:"none",background:"rgba(28,28,32,0.88)",backdropFilter:"blur(10px)",WebkitBackdropFilter:"blur(10px)",color:"#eee",borderRadius:8,padding:"7px 10px",fontSize:12,maxWidth:220,boxShadow:"0 8px 24px rgba(0,0,0,.2)"}}),(0,e.jsxs)("div",{className:"me-graph-legend",style:{position:"absolute",left:12,bottom:8,zIndex:2},children:[W?[{c:"#10b981",l:n("timeNew")},{c:"#f59e0b",l:n("timeRecent")},{c:"#f97316",l:n("timeMonth")},{c:"#94a3b8",l:n("timeOld")}].map(i=>(0,e.jsxs)("span",{className:"lg",children:[(0,e.jsx)("span",{className:"mc-kind",style:{background:i.c}}),i.l]},i.c)):Object.keys(We).map(i=>(0,e.jsxs)("button",{type:"button",className:`lg${ue===i?" active":""}`,onClick:()=>ne(a=>a===i?"all":i),children:[(0,e.jsx)("span",{className:"mc-kind",style:{background:Ee.colors[i]||We[i]}}),n(ve[i])]},i)),!W&&ue!=="all"&&(0,e.jsxs)("button",{type:"button",className:"lg lg-clear",onClick:()=>ne("all"),children:[n("clearFilter")," \u2715"]})]}),ye&&(0,e.jsx)("div",{className:"mc-empty",style:{position:"absolute",inset:0,zIndex:2,display:"flex",alignItems:"center",justifyContent:"center",backdropFilter:"blur(2px)",WebkitBackdropFilter:"blur(2px)"},children:n("noMatch")}),L&&(0,e.jsx)("div",{className:"me-graph-ctx-back",style:{position:"fixed",inset:0,zIndex:30},onMouseDown:()=>$(null)}),L&&(0,e.jsxs)("div",{className:"me-graph-ctxmenu",style:{position:"fixed",left:L.x,top:L.y,zIndex:31},onMouseDown:i=>i.stopPropagation(),children:[(0,e.jsx)("button",{type:"button",onClick:()=>{_.current({path:L.path,title:L.title}),$(null)},children:n("openCard")}),(0,e.jsx)("button",{type:"button",onClick:()=>{L.id&&(P.current.selectedId=L.id,ce(L.id)),$(null);let i=P.current;i&&i.wake&&i.wake()},children:n("focusNeighbors")}),(0,e.jsx)("button",{type:"button",onClick:()=>{try{navigator.clipboard&&navigator.clipboard.writeText(L.title||"")}catch{}$(null),O(n("copied"))},children:n("copyName")}),(0,e.jsx)("button",{type:"button",style:{color:"#f87171"},onClick:()=>{let i=L.path;$(null),window.confirm(n("deleteConfirm"))&&(async()=>{try{(me.current?await me.current(i):!1)?O(n("deleted")):O(n("deleteFail"),!1)}catch{O(n("deleteFail"),!1)}})()},children:n("delete")})]}),S.length>0&&(0,e.jsxs)("div",{style:{position:"absolute",left:10,top:10,zIndex:3,display:"flex",gap:8,alignItems:"center",background:"rgba(28,28,32,0.92)",backdropFilter:"blur(10px)",WebkitBackdropFilter:"blur(10px)",color:"#eee",borderRadius:10,padding:"6px 10px",fontSize:12,boxShadow:"0 10px 30px rgba(0,0,0,.25)"},children:[(0,e.jsxs)("span",{style:{fontWeight:700},children:[S.length," ",n("nodes")]}),(0,e.jsx)("button",{type:"button",className:"mc-btn",onClick:()=>{let a=S.map(f=>Z[f]).filter(Boolean).map(f=>f.title||f.name).join(`
|
|
113
|
+
`),N=new Blob([a],{type:"text/plain;charset=utf-8"}),d=URL.createObjectURL(N),x=document.createElement("a");x.href=d,x.download="memory-selected.txt",document.body.appendChild(x),x.click(),document.body.removeChild(x),setTimeout(()=>URL.revokeObjectURL(d),1e3),O(S.length+n("exportedSel"))},children:n("exportSel")}),(0,e.jsx)("button",{type:"button",className:"mc-btn",onClick:()=>{if(S.length<2){O(n("mergeNeed"),!1);return}let i=S.map(N=>Z[N]?Z[N].id:N);if(!window.confirm(n("mergeConfirm")))return;H([]);let a=P.current;a&&(a.multi=[]),fetch(`${U}/merge?paths=${encodeURIComponent(i.join(","))}`).then(N=>N.json()).then(N=>{N&&N.ok?O(n("merged")):O(n("mergeFail"),!1)}).catch(()=>O(n("mergeFail"),!1))},children:n("merge")}),(0,e.jsx)("button",{type:"button",className:"mc-btn",style:{color:"#f87171"},onClick:()=>{if(!window.confirm(n("deleteConfirm")))return;let i=S.map(N=>Z[N]?Z[N].id:N);H([]);let a=P.current;a&&(a.multi=[]),(async()=>{let N=0;for(let d of i)try{(me.current?await me.current(d):!1)&&N++}catch{}O(N+n("deletedSelected"),N>0)})()},children:n("deleteSelected")}),(0,e.jsx)("button",{type:"button",className:"mc-btn",onClick:()=>{let i=P.current;i&&(i.multi=[]),H([]);let a=P.current;a&&a.render&&a.render()},children:n("clearSelection")})]}),A&&(0,e.jsxs)("div",{className:"me-graph-sidebar",style:{position:"absolute",right:10,top:10,zIndex:3,maxWidth:240,background:"rgba(28,28,32,0.92)",backdropFilter:"blur(10px)",WebkitBackdropFilter:"blur(10px)",color:"#eee",borderRadius:10,padding:12,fontSize:12,boxShadow:"0 10px 30px rgba(0,0,0,.25)"},children:[(0,e.jsx)("div",{style:{fontWeight:700,fontSize:13,marginBottom:4},children:Z[A]?Z[A].title||Z[A].name:A}),(0,e.jsx)("div",{style:{opacity:.8,marginBottom:8},children:Z[A]?n(ve[Z[A].kind]||"kindKnowledge"):"\u2014"}),(0,e.jsx)("div",{style:{fontSize:11,opacity:.65,letterSpacing:".04em",marginBottom:6},children:n("graphHint")}),(s.filter(i=>i.source===A||i.target===A)||[]).slice(0,8).map((i,a)=>{let N=i.source===A?i.target:i.source,d=Z[N];return(0,e.jsx)("div",{style:{padding:"4px 6px",cursor:"pointer",borderRadius:6},onMouseDown:x=>{x.preventDefault();let f=P.current;f&&(f.selectedId=N,f.hoverId=N,f.wake&&f.wake()),ce(N)},children:d?(d.title||d.name).slice(0,28):N},a)})]})]}),(0,e.jsx)("div",{className:"me-graph-tip",children:n("graphTip")}),fe&&(0,e.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,position:"fixed",left:"50%",transform:"translateX(-50%)",top:22,zIndex:70,background:"rgba(20,22,26,0.97)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",color:"#f5f5f5",borderRadius:12,padding:"10px 20px",fontSize:13.5,fontWeight:600,boxShadow:"0 14px 44px rgba(0,0,0,.5)",pointerEvents:"none",animation:"me-pop .22s ease",borderLeft:"4px solid "+(fe.ok?"#22c55e":"#ef4444"),maxWidth:"90vw"},children:[(0,e.jsx)("span",{style:{color:fe.ok?"#34d399":"#f87171",fontWeight:800,fontSize:15},children:fe.ok?"\u2713":"\u2715"}),(0,e.jsx)("span",{style:{wordBreak:"break-all"},children:fe.msg})]}),G&&(0,e.jsxs)("div",{className:"me-overlay",onClick:()=>{G.url&&URL.revokeObjectURL(G.url),Ce(null),de(!1)},children:[(0,e.jsx)("style",{children:we}),(0,e.jsxs)("div",{className:"me-dialog",style:{maxWidth:re?"100vw":900,width:re?"100vw":"92vw",maxHeight:re?"100vh":"90vh",height:re?"100vh":void 0,borderRadius:re?0:14},onClick:i=>i.stopPropagation(),children:[(0,e.jsxs)("div",{className:"me-dialog-head",children:[(0,e.jsx)("h3",{children:n("exportGraph")}),(0,e.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,e.jsx)("a",{className:"mc-btn",href:G.url,download:"memory-graph.png",onClick:()=>{Me("download"),O(n("downloaded")+" \xB7 "+n("defaultDownloads"))},style:{textDecoration:"none",display:"inline-flex",alignItems:"center"},children:n(xe==="download"?"done":"download")}),(0,e.jsx)("button",{type:"button",className:"mc-btn",onClick:()=>{Me("save");let i=G.blob;i&&typeof window.showSaveFilePicker=="function"?rt(i,"memory-graph.png",!0).then(a=>{a.ok?O(n("exportedTo")+"\uFF1A"+a.name):a.aborted?O(n("exportCancel")):O(n("exportFail"),!1)}):O(n("saveAsUnsupported"),!1)},children:n(xe==="save"?"done":"saveAs")}),(0,e.jsx)("button",{type:"button",className:"mc-btn",onClick:()=>{Me("full"),de(i=>!i),O(n("fullscreen"))},children:n(xe==="full"?"done":re?"exitFull":"fullscreen")}),(0,e.jsx)("button",{type:"button",className:"mc-btn",onClick:()=>{let i=G.blob;i&&window.ClipboardItem&&navigator.clipboard?navigator.clipboard.write([new window.ClipboardItem({"image/png":i})]).then(()=>{Me("copy"),O(n("copied"))}).catch(()=>{O(n("copyFail"),!1)}):O(n("copyFail"),!1)},children:n(xe==="copy"?"done":"copyImage")}),(0,e.jsx)("button",{type:"button",className:"mc-btn",onClick:()=>{G.url&&URL.revokeObjectURL(G.url),Ce(null),de(!1)},children:n("close")})]})]}),(0,e.jsx)("div",{className:"me-dialog-body",style:{display:"flex",justifyContent:"center",background:re?"var(--dsw-alias-bg-base, #0b0d10)":"var(--dsw-alias-bg-base, #f3f4f6)"},children:(0,e.jsx)("img",{src:G.url,alt:n("exportGraph"),style:{maxWidth:"100%",maxHeight:re?"calc(100vh - 64px)":"70vh",borderRadius:re?0:8,cursor:"zoom-in"},onClick:()=>de(i=>!i)})})]})]})]})}function zt(o){let s=new Date(o||0).getTime();if(!s)return"#94a3b8";let m=(Date.now()-s)/864e5;return m<3?"#10b981":m<14?"#f59e0b":m<30?"#f97316":"#94a3b8"}function Tt(o){let s=new Date(o||0).getTime();return!!s&&(Date.now()-s)/864e5<3}async function rt(o,s,m){if(m&&typeof window.showSaveFilePicker=="function")try{let g=await window.showSaveFilePicker({suggestedName:s}),I=await g.createWritable();return await I.write(o),await I.close(),{ok:!0,picked:!0,name:g.name}}catch(g){return g&&g.name==="AbortError"?{ok:!1,aborted:!0}:{ok:!1,err:String(g.message||g)}}let u=URL.createObjectURL(o),n=document.createElement("a");return n.href=u,n.download=s,document.body.appendChild(n),n.click(),document.body.removeChild(n),setTimeout(()=>URL.revokeObjectURL(u),1e3),{ok:!0,picked:!1,name:s}}function ot(o,s){if(!s||!o)return o;let m=o.toLowerCase(),u=s.toLowerCase(),n=[],g=0;for(;g<o.length;){let I=m.indexOf(u,g);if(I<0){n.push(o.slice(g));break}I>g&&n.push(o.slice(g,I)),n.push((0,e.jsx)("mark",{className:"mc-hl",children:o.slice(I,I+u.length)},I)),g=I+u.length}return n}function Lt(o){if(!o)return"";let s=String(o).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),m=[];return s=s.replace(/```([\w-]*)\n([\s\S]*?)```/g,function(u,n,g){return m.push("<pre><code>"+g+"</code></pre>"),"\0"+(m.length-1)+"\0"}),s=s.replace(/^(#{1,3})\s+(.+)$/gm,function(u,n,g){return"<h"+n.length+">"+g+"</h"+n.length+">"}),s=s.replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>"),s=s.replace(/`([^`\n]+)`/g,"<code>$1</code>"),s=s.replace(/(^|[^*])\*([^*]+)\*/g,"$1<em>$2</em>"),s=s.replace(/\[([^\]]+)\]\(([^)]+)\)/g,function(u,n,g){return/^(https?:|\/)/.test(g)?'<a href="'+g+'" target="_blank" rel="noopener noreferrer">'+n+"</a>":n}),s=s.replace(/^(-)\s+(.+)$/gm,"\u2022 $2"),s=s.replace(/^\s*(>)\s*(.+)$/gm,"<blockquote>$2</blockquote>"),s=s.replace(/\n/g,"<br/>"),s=s.replace(/\u0000(\d+)\u0000/g,function(u,n){return m[n]}),s}function it(o){if(!o)return"";let s=new Date(o);if(Number.isNaN(s.getTime()))return"";let m=new Date,u=s.toDateString()===m.toDateString(),n=I=>String(I).padStart(2,"0"),g=`${n(s.getHours())}:${n(s.getMinutes())}`;return u?g:`${s.getMonth()+1}-${s.getDate()} ${g}`}
|
|
114
114
|
|
|
115
115
|
return module.exports;
|
|
116
116
|
},
|
package/lib/vault.js
CHANGED
|
@@ -270,8 +270,8 @@ export async function appendUpdate(root, rel, updateText, { threshold = 0.62 } =
|
|
|
270
270
|
return { ok: true, path: rel, kind: meta.kind || 'knowledge', updated: now }
|
|
271
271
|
}
|
|
272
272
|
|
|
273
|
-
/** 检索:整词/中文 bigram 命中 path + 正文。返回卡片摘要(带命中度)。minScore
|
|
274
|
-
export async function search(root, query, { limit = 30, minScore = 0 } = {}) {
|
|
273
|
+
/** 检索:整词/中文 bigram 命中 path + 正文。返回卡片摘要(带命中度)。minScore 过滤弱命中;semantic=true 加本地语义分。 */
|
|
274
|
+
export async function search(root, query, { limit = 30, minScore = 0, semantic = false } = {}) {
|
|
275
275
|
const q = String(query || '').trim()
|
|
276
276
|
if (!q) return []
|
|
277
277
|
const cards = await listCards(root)
|
|
@@ -290,6 +290,8 @@ export async function search(root, query, { limit = 30, minScore = 0 } = {}) {
|
|
|
290
290
|
for (const term of wanted) {
|
|
291
291
|
if (haystack.includes(term.toLowerCase())) score += 1
|
|
292
292
|
}
|
|
293
|
+
// 本地语义加分:Jaccard bigram 相似度(无 embedding 依赖),覆盖「同义改写/片段命中」
|
|
294
|
+
if (semantic) score += Math.round(textSimilarity(q, `${card.title} ${card.summary}`) * 6)
|
|
293
295
|
if (score > 0 && score >= minScore) {
|
|
294
296
|
out.push({ ...card, score })
|
|
295
297
|
}
|
|
@@ -298,6 +300,30 @@ export async function search(root, query, { limit = 30, minScore = 0 } = {}) {
|
|
|
298
300
|
return out.slice(0, limit)
|
|
299
301
|
}
|
|
300
302
|
|
|
303
|
+
/** 当日简报:按 mtime 列出今天新增/更新的卡(供每日回顾)。 */
|
|
304
|
+
export function dailyBrief(cardsToday) {
|
|
305
|
+
if (!cardsToday || cardsToday.length === 0) return '今天还没有新的记忆沉淀。'
|
|
306
|
+
return cardsToday.map((c) => `- ${c.kind}|${c.title}`).join('\n')
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** 生成今日简报文件到 00-System/daily-YYYY-MM-DD.md,幂等(已存在则跳过)。 */
|
|
310
|
+
export async function generateDailyBrief(root) {
|
|
311
|
+
const d = new Date()
|
|
312
|
+
const date = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
|
|
313
|
+
const dir = path.join(root, '00-System')
|
|
314
|
+
const file = path.join(dir, `daily-${date}.md`)
|
|
315
|
+
try {
|
|
316
|
+
if (await exists(file)) return { ok: true, existed: true, file }
|
|
317
|
+
const s = await stats(root)
|
|
318
|
+
const content = `---\nkind: prompt\ntitle: 每日回顾 ${date}\ntags: [每日回顾, 统计]\ncreated: ${new Date().toISOString()}\nupdated: ${new Date().toISOString()}\nsource: daily-brief\n---\n# 每日回顾 ${date}\n\n今日新增 ${s.today} · 近 7 天 ${s.week} · 总 ${s.total}\n\n## 今日沉淀\n${dailyBrief(s.todayCards)}\n`
|
|
319
|
+
await fs.mkdir(dir, { recursive: true })
|
|
320
|
+
await fs.writeFile(file, content, 'utf8')
|
|
321
|
+
return { ok: true, existed: false, file }
|
|
322
|
+
} catch (e) {
|
|
323
|
+
return { ok: false, error: String(e.message || e) }
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
301
327
|
/** 导出全部卡片原始 Markdown。 */
|
|
302
328
|
export async function exportCards(root) {
|
|
303
329
|
const cards = await listCards(root)
|
|
@@ -386,9 +412,87 @@ export async function graph(root) {
|
|
|
386
412
|
return { nodes, edges }
|
|
387
413
|
}
|
|
388
414
|
|
|
389
|
-
/**
|
|
390
|
-
export async function
|
|
415
|
+
/** 统计(增强):overview 全量 + 今日/本周新增 + 今日新增卡片明细。 */
|
|
416
|
+
export async function stats(root) {
|
|
417
|
+
const cards = await listCards(root)
|
|
418
|
+
const byKind = {}
|
|
419
|
+
for (const c of cards) byKind[c.kind] = (byKind[c.kind] || 0) + 1
|
|
420
|
+
const now = Date.now()
|
|
421
|
+
const day = now - 86400000
|
|
422
|
+
const week = now - 7 * 86400000
|
|
423
|
+
const today = cards.filter((c) => c.mtime > day)
|
|
424
|
+
const tagSet = new Set()
|
|
425
|
+
for (const c of cards) for (const t of c.tags) tagSet.add(t)
|
|
426
|
+
return {
|
|
427
|
+
total: cards.length,
|
|
428
|
+
today: today.length,
|
|
429
|
+
week: cards.filter((c) => c.mtime > week).length,
|
|
430
|
+
tags: tagSet.size,
|
|
431
|
+
byKind,
|
|
432
|
+
todayCards: today.slice(0, 30).map((c) => ({ path: c.path, title: c.title, kind: c.kind, updated: c.updated, summary: c.summary.slice(0, 80) })),
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/** 跨库聚合图谱:roots = [{name, root}],每个 vault 的子图合并(node id 前缀 profile 名避免冲突)。 */
|
|
437
|
+
export async function graphAll(roots) {
|
|
438
|
+
const nodes = []; const edges = []; const idSet = new Set()
|
|
439
|
+
for (const r of roots) {
|
|
440
|
+
let g
|
|
441
|
+
try { g = await graph(r.root) } catch { continue }
|
|
442
|
+
const pref = r.name ? `${r.name}::` : ''
|
|
443
|
+
const map = new Map()
|
|
444
|
+
for (const n of g.nodes) { const id = pref + n.id; if (!idSet.has(id)) { idSet.add(id); map.set(n.id, id); nodes.push({ ...n, id }) } else map.set(n.id, id) }
|
|
445
|
+
for (const e of g.edges) { const s = map.get(e.source) || (pref + e.source), t = map.get(e.target) || (pref + e.target); if (s && t) edges.push({ source: s, target: t, type: e.type }) }
|
|
446
|
+
}
|
|
447
|
+
return { nodes, edges }
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** 跨库聚合检索:多个 vault 的结果合并(path 前缀 profile 名)。 */
|
|
451
|
+
export async function searchAll(roots, query, opts = {}) {
|
|
452
|
+
const out = []
|
|
453
|
+
for (const r of roots) {
|
|
454
|
+
let hits
|
|
455
|
+
try { hits = await search(r.root, query, opts) } catch { continue }
|
|
456
|
+
const pref = r.name ? `${r.name}::` : ''
|
|
457
|
+
for (const h of hits) out.push({ ...h, path: pref + h.path, score: (h.score || 0) + (r.name ? 0 : 0), profile: r.name || '' })
|
|
458
|
+
}
|
|
459
|
+
out.sort((a, b) => b.score - a.score || b.mtime - a.mtime)
|
|
460
|
+
return out.slice(0, opts.limit || 30)
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/** 整理建议(非破坏性预览):高相似卡对 + 陈旧卡(>90 天未更新且无连线)。 */
|
|
464
|
+
export async function optimizeCandidates(root) {
|
|
391
465
|
const cards = await listCards(root)
|
|
466
|
+
const merge = []
|
|
467
|
+
const bodies = new Map()
|
|
468
|
+
for (const c of cards) {
|
|
469
|
+
try { bodies.set(c.path, (await fs.readFile(path.join(root, c.path), 'utf8')).slice(0, 4000)) } catch { bodies.set(c.path, '') }
|
|
470
|
+
}
|
|
471
|
+
for (let i = 0; i < cards.length; i++) for (let j = i + 1; j < cards.length; j++) {
|
|
472
|
+
const a = cards[i], b = cards[j]
|
|
473
|
+
if (a.kind !== b.kind) continue
|
|
474
|
+
const sim = textSimilarity(bodies.get(a.path) || '', bodies.get(b.path) || '')
|
|
475
|
+
if (sim >= 0.55) merge.push({ a: { path: a.path, title: a.title }, b: { path: b.path, title: b.title }, sim: Math.round(sim * 100) / 100 })
|
|
476
|
+
}
|
|
477
|
+
merge.sort((x, y) => y.sim - x.sim)
|
|
478
|
+
const old = Date.now() - 90 * 86400000
|
|
479
|
+
const stale = cards.filter((c) => c.mtime < old).slice(0, 30).map((c) => ({ path: c.path, title: c.title, updated: c.updated }))
|
|
480
|
+
return { merge: merge.slice(0, 40), stale }
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/** 召回反馈记录:命中是否有用(供相关性调优)。文件存 vault 根 `.feedback.json`。 */
|
|
484
|
+
export async function readFeedback(root) {
|
|
485
|
+
try { return JSON.parse(await fs.readFile(path.join(root, '.feedback.json'), 'utf8')) } catch { return [] }
|
|
486
|
+
}
|
|
487
|
+
export async function addFeedback(root, rec) {
|
|
488
|
+
const list = await readFeedback(root)
|
|
489
|
+
list.unshift({ ts: Date.now(), ...rec })
|
|
490
|
+
await fs.writeFile(path.join(root, '.feedback.json'), JSON.stringify(list.slice(0, 500), null, 2), 'utf8')
|
|
491
|
+
return { ok: true }
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/** 统计:按 kind 计数 + 最近 7 天更新数 + 总标签数。 */
|
|
495
|
+
export async function overview(root) { const cards = await listCards(root)
|
|
392
496
|
const byKind = {}
|
|
393
497
|
for (const c of cards) byKind[c.kind] = (byKind[c.kind] || 0) + 1
|
|
394
498
|
const week = Date.now() - 7 * 86400000
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-memory-eternal",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.6",
|
|
4
4
|
"description": "记忆核心(Memory Eternal):自研的 DeepSeek Harness 记忆插件,不移植任何既有记忆框架——对话结束后自动沉淀知识卡到本地 Markdown Vault(自研去重、自研 CJK 检索、可 git 管理),设置页提供图形化知识库(统计 / 搜索 / 知识图谱 + 侧边栏一键弹窗),Agent 通过 memory_recall 工具按需召回历史上下文。零人工干预。",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|