toon-memory 3.0.0 → 3.2.0

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/dist/cli/setup.js CHANGED
@@ -165,7 +165,8 @@ function detectAgents() {
165
165
  agents.push({
166
166
  name: "claude",
167
167
  global: join3(HOME, ".claude", "settings.json"),
168
- local: join3(projectRoot, ".claude", "settings.json"),
168
+ local: join3(projectRoot, ".mcp.json"),
169
+ hookPath: join3(projectRoot, ".claude", "settings.json"),
169
170
  mcpKey: "mcpServers",
170
171
  format: "json",
171
172
  needsHooks: true,
@@ -202,8 +203,8 @@ function detectAgents() {
202
203
  agents.push({
203
204
  name: "continue",
204
205
  local: join3(projectRoot, ".continue", "config.json"),
205
- mcpKey: "mcpServers",
206
- format: "json",
206
+ mcpKey: "experimental.modelContextProtocolServers",
207
+ format: "continue",
207
208
  needsHooks: false,
208
209
  needsInstructions: false
209
210
  });
@@ -230,14 +231,14 @@ function detectAgents() {
230
231
  agents.push({
231
232
  name: "zed",
232
233
  global: join3(HOME, ".config", "zed", "settings.json"),
233
- mcpKey: "mcp_servers",
234
+ mcpKey: "context_servers",
234
235
  format: "jsonc",
235
236
  needsHooks: false,
236
237
  needsInstructions: false
237
238
  });
238
239
  agents.push({
239
240
  name: "antigravity",
240
- local: join3(projectRoot, ".gemini", "config", "mcp_config.json"),
241
+ local: join3(projectRoot, ".agents", "mcp_config.json"),
241
242
  mcpKey: "mcpServers",
242
243
  format: "json",
243
244
  needsHooks: true,
@@ -255,7 +256,7 @@ function detectAgents() {
255
256
  agents.push({
256
257
  name: "kilocode",
257
258
  global: join3(HOME, ".kilocode", "mcp_settings.json"),
258
- mcpKey: "mcpServers",
259
+ mcpKey: "mcp",
259
260
  format: "json",
260
261
  needsHooks: false,
261
262
  needsInstructions: true,
@@ -263,9 +264,9 @@ function detectAgents() {
263
264
  });
264
265
  agents.push({
265
266
  name: "openclaw",
266
- local: join3(projectRoot, ".openclaw.json"),
267
- mcpKey: "mcpServers",
268
- format: "json",
267
+ global: join3(HOME, ".openclaw", "openclaw.json"),
268
+ mcpKey: "mcp.servers",
269
+ format: "openclaw",
269
270
  needsHooks: false,
270
271
  needsInstructions: false
271
272
  });
@@ -389,6 +390,11 @@ function installJSONConfig(agent, scope) {
389
390
  type: "local",
390
391
  command: ["npx", "-y", "toon-memory", "mcp"]
391
392
  };
393
+ } else if (agent.name === "kilocode") {
394
+ config[mcpKey]["toon-memory"] = {
395
+ type: "local",
396
+ command: ["npx", "-y", "toon-memory", "mcp"]
397
+ };
392
398
  } else {
393
399
  config[mcpKey]["toon-memory"] = {
394
400
  command: "npx",
@@ -425,11 +431,69 @@ function installZedConfig(agent) {
425
431
  config = {};
426
432
  }
427
433
  }
428
- if (!config.mcp_servers) config.mcp_servers = {};
429
- config.mcp_servers["toon-memory"] = {
434
+ if (!config.context_servers) config.context_servers = {};
435
+ config.context_servers["toon-memory"] = {
436
+ command: "npx",
437
+ args: ["-y", "toon-memory", "mcp"],
438
+ source: "custom"
439
+ };
440
+ writeFileSync3(configPath, JSON.stringify(config, null, 2));
441
+ console.log(` MCP server added to ${configPath}`);
442
+ }
443
+ function installContinueConfig(agent) {
444
+ const configPath = agent.local;
445
+ if (!configPath) return;
446
+ const configDir = dirname3(configPath);
447
+ if (!existsSync5(configDir)) mkdirSync3(configDir, { recursive: true });
448
+ let config = {};
449
+ if (existsSync5(configPath)) {
450
+ try {
451
+ config = JSON.parse(readFileSync5(configPath, "utf-8"));
452
+ } catch {
453
+ config = {};
454
+ }
455
+ }
456
+ if (!config.experimental) config.experimental = {};
457
+ if (!config.experimental.modelContextProtocolServers) {
458
+ config.experimental.modelContextProtocolServers = [];
459
+ }
460
+ const servers = config.experimental.modelContextProtocolServers;
461
+ const existing = servers.findIndex(
462
+ (s) => s.name === "toon-memory"
463
+ );
464
+ const entry = {
465
+ name: "toon-memory",
430
466
  command: "npx",
431
467
  args: ["-y", "toon-memory", "mcp"]
432
468
  };
469
+ if (existing >= 0) {
470
+ servers[existing] = entry;
471
+ } else {
472
+ servers.push(entry);
473
+ }
474
+ writeFileSync3(configPath, JSON.stringify(config, null, 2));
475
+ console.log(` MCP server added to ${configPath}`);
476
+ }
477
+ function installOpenClawConfig(agent) {
478
+ const configPath = agent.global;
479
+ if (!configPath) return;
480
+ const configDir = dirname3(configPath);
481
+ if (!existsSync5(configDir)) mkdirSync3(configDir, { recursive: true });
482
+ let config = {};
483
+ if (existsSync5(configPath)) {
484
+ try {
485
+ config = JSON.parse(readFileSync5(configPath, "utf-8"));
486
+ } catch {
487
+ config = {};
488
+ }
489
+ }
490
+ if (!config.mcp) config.mcp = {};
491
+ if (!config.mcp.servers) config.mcp.servers = {};
492
+ config.mcp.servers["toon-memory"] = {
493
+ command: "npx",
494
+ args: ["-y", "toon-memory", "mcp"],
495
+ enabled: true
496
+ };
433
497
  writeFileSync3(configPath, JSON.stringify(config, null, 2));
434
498
  console.log(` MCP server added to ${configPath}`);
435
499
  }
@@ -442,6 +506,10 @@ function installMCPConfig(agent, scope) {
442
506
  installTOMLConfig(agent);
443
507
  } else if (agent.format === "jsonc") {
444
508
  installZedConfig(agent);
509
+ } else if (agent.format === "continue") {
510
+ installContinueConfig(agent);
511
+ } else if (agent.format === "openclaw") {
512
+ installOpenClawConfig(agent);
445
513
  } else {
446
514
  installJSONConfig(agent, scope);
447
515
  }
@@ -534,7 +602,7 @@ function installHooks(agent) {
534
602
  }
535
603
  }
536
604
  function registerCaptureHookJSON(agent, scriptPath) {
537
- const configPath = agent.local || agent.global;
605
+ const configPath = agent.hookPath || agent.local || agent.global;
538
606
  if (!configPath) return;
539
607
  const configDir = dirname5(configPath);
540
608
  if (!existsSync7(configDir)) mkdirSync5(configDir, { recursive: true });
@@ -588,7 +656,7 @@ command = "${hookPath}"
588
656
  console.log(` Hook registered in ${configPath}`);
589
657
  }
590
658
  function registerHookJSON(agent, hookPath) {
591
- const configPath = agent.format === "jsonc" ? agent.global : agent.local || agent.global;
659
+ const configPath = agent.hookPath || (agent.format === "jsonc" ? agent.global : agent.local || agent.global);
592
660
  if (!configPath) return;
593
661
  const configDir = dirname5(configPath);
594
662
  if (!existsSync7(configDir)) mkdirSync5(configDir, { recursive: true });
@@ -653,18 +721,37 @@ import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as rea
653
721
  import { join as join6 } from "path";
654
722
  function opencodePluginContent() {
655
723
  return `import * as fs from "fs"
724
+ import * as path from "path"
656
725
 
657
726
  export const ToonMemory = async ({ $, directory, worktree }) => {
658
727
  const root = worktree || directory
659
728
  const INS = root + "/.opencode/instructions"
660
729
  const OUT = INS + "/memory-autoload.md"
730
+
661
731
  const dump = async () => {
662
732
  return await $\`npx -y toon-memory dump\`.cwd(root).text()
663
733
  }
734
+
735
+ const recall = async (query) => {
736
+ try {
737
+ const result = await $\`npx -y toon-memory mcp\`.cwd(root)
738
+ .stdin(JSON.stringify({
739
+ jsonrpc: "2.0",
740
+ id: 1,
741
+ method: "tools/call",
742
+ params: { name: "memory_recall", arguments: { query, mode: "flat", compact: true } }
743
+ }))
744
+ .text()
745
+ const parsed = JSON.parse(result)
746
+ return parsed?.result?.content?.[0]?.text || ""
747
+ } catch { return "" }
748
+ }
749
+
664
750
  const write = (text) => {
665
751
  fs.mkdirSync(INS, { recursive: true })
666
752
  fs.writeFileSync(OUT, text)
667
753
  }
754
+
668
755
  return {
669
756
  "session.created": async () => {
670
757
  try {
@@ -679,15 +766,39 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
679
766
  } catch {}
680
767
  },
681
768
  "tool.execute.after": async (input) => {
682
- if (!process.env.TOON_MEMORY_CAPTURE) return
683
- const cap = directory + "/bin/cli/capture.js"
769
+ // Intelligent auto-loading: extract file path from tool result,
770
+ // recall only memory relevant to that file, inject as context.
684
771
  try {
685
- const payload = JSON.stringify({
686
- session_id: input?.session?.id ?? "",
687
- tool_name: input?.tool ?? "",
688
- tool_input: input?.args ?? {},
689
- })
690
- await $\`node \${cap} opencode\`.stdin(payload).quiet()
772
+ const toolName = input?.tool || ""
773
+ const args = input?.args || {}
774
+
775
+ // Extract file path from tool arguments or output
776
+ let filePath = ""
777
+ if (args.file) filePath = args.file
778
+ else if (args.path) filePath = args.path
779
+ else if (args.filePath) filePath = args.filePath
780
+
781
+ // Also try to extract from tool output text
782
+ if (!filePath && input?.output) {
783
+ const outputText = typeof input.output === "string" ? input.output : ""
784
+ const fileMatch = outputText.match(/(?:file|path|source):s*([\\w/.\\-]+)/i)
785
+ if (fileMatch) filePath = fileMatch[1]
786
+ }
787
+
788
+ if (!filePath) return
789
+
790
+ // Build recall query from file path components
791
+ const basename = path.basename(filePath, path.extname(filePath))
792
+ const dirParts = path.dirname(filePath).split(path.sep).filter(Boolean)
793
+ const query = [basename, ...dirParts.slice(-2)].join(" ")
794
+
795
+ const text = await recall(query)
796
+ if (!text || text.includes("(empty)") || text.includes("No results")) return
797
+
798
+ // Inject as context for the next agent turn
799
+ if (typeof input?.setContext === "function") {
800
+ input.setContext("toon-memory:" + filePath, text)
801
+ }
691
802
  } catch {}
692
803
  },
693
804
  }
@@ -863,7 +974,7 @@ function uninstall() {
863
974
  unlinkSync(ocPlugin);
864
975
  console.log(" Removed .opencode/plugins/toon-memory.ts");
865
976
  }
866
- const agyHooks = join7(projectRoot, ".gemini", "config", "hooks.json");
977
+ const agyHooks = join7(projectRoot, ".agents", "hooks.json");
867
978
  if (existsSync9(agyHooks)) {
868
979
  try {
869
980
  const agyCfg = JSON.parse(readFileSync9(agyHooks, "utf-8"));
@@ -1281,6 +1392,1213 @@ function watch(args2) {
1281
1392
  });
1282
1393
  }
1283
1394
 
1395
+ // src/viewer/index.ts
1396
+ import { writeFileSync as writeFileSync11, mkdirSync as mkdirSync10 } from "fs";
1397
+ import { join as join10 } from "path";
1398
+ import { execSync } from "child_process";
1399
+
1400
+ // src/lib/lock.ts
1401
+ import { openSync, closeSync, writeFileSync as writeFileSync9, readFileSync as readFileSync11, unlinkSync as unlinkSync3, existsSync as existsSync11, statSync as statSync2, renameSync } from "fs";
1402
+ var STALE_MS = 15e3;
1403
+ var LOCK_TIMEOUT_MS = 1e4;
1404
+ function isAlive(pid) {
1405
+ if (!pid || pid <= 0) return false;
1406
+ try {
1407
+ process.kill(pid, 0);
1408
+ return true;
1409
+ } catch {
1410
+ return false;
1411
+ }
1412
+ }
1413
+ function tryAcquire(lockFile) {
1414
+ if (existsSync11(lockFile)) {
1415
+ const age = Date.now() - statSync2(lockFile).mtimeMs;
1416
+ let stale = age > STALE_MS;
1417
+ if (!stale) {
1418
+ try {
1419
+ const pid = parseInt(readFileSync11(lockFile, "utf-8").trim(), 10);
1420
+ if (!isAlive(pid)) stale = true;
1421
+ } catch {
1422
+ stale = true;
1423
+ }
1424
+ }
1425
+ if (stale) {
1426
+ try {
1427
+ unlinkSync3(lockFile);
1428
+ } catch {
1429
+ }
1430
+ } else {
1431
+ return false;
1432
+ }
1433
+ }
1434
+ try {
1435
+ const fd = openSync(lockFile, "wx");
1436
+ writeFileSync9(fd, String(process.pid));
1437
+ closeSync(fd);
1438
+ return true;
1439
+ } catch {
1440
+ return false;
1441
+ }
1442
+ }
1443
+ var held = /* @__PURE__ */ new Map();
1444
+ function withLockSync(file, fn) {
1445
+ const lockFile = `${file}.lock`;
1446
+ const depth = held.get(lockFile) ?? 0;
1447
+ if (depth > 0) {
1448
+ held.set(lockFile, depth + 1);
1449
+ try {
1450
+ fn();
1451
+ } finally {
1452
+ const d = (held.get(lockFile) ?? 0) - 1;
1453
+ if (d <= 0) held.delete(lockFile);
1454
+ else held.set(lockFile, d);
1455
+ }
1456
+ return;
1457
+ }
1458
+ const deadline = Date.now() + LOCK_TIMEOUT_MS;
1459
+ while (!tryAcquire(lockFile)) {
1460
+ if (Date.now() > deadline) throw new Error(`toon-memory lock timeout: ${file}`);
1461
+ const t = Date.now() + 10;
1462
+ while (Date.now() < t) {
1463
+ }
1464
+ }
1465
+ held.set(lockFile, 1);
1466
+ try {
1467
+ fn();
1468
+ } finally {
1469
+ const d = (held.get(lockFile) ?? 0) - 1;
1470
+ if (d <= 0) {
1471
+ held.delete(lockFile);
1472
+ try {
1473
+ unlinkSync3(lockFile);
1474
+ } catch {
1475
+ }
1476
+ } else {
1477
+ held.set(lockFile, d);
1478
+ }
1479
+ }
1480
+ }
1481
+ function readUnderLock(file, encoding = "utf-8") {
1482
+ let content = "";
1483
+ withLockSync(file, () => {
1484
+ content = readFileSync11(file, encoding);
1485
+ });
1486
+ return content;
1487
+ }
1488
+
1489
+ // src/mcp/config.ts
1490
+ import { readFileSync as readFileSync12, writeFileSync as writeFileSync10, existsSync as existsSync12, mkdirSync as mkdirSync9 } from "fs";
1491
+ import { join as join9 } from "path";
1492
+ var MEMORY_DIR3 = join9(process.cwd(), ".toon-memory", "memory");
1493
+ var MEMORY_FILE = join9(MEMORY_DIR3, "data.toon");
1494
+ var ARCHIVE_FILE = join9(MEMORY_DIR3, "archive.toon");
1495
+ var OBSERVATIONS_FILE = join9(MEMORY_DIR3, "observations.toon");
1496
+ var CONFIG_FILE = join9(MEMORY_DIR3, "config.json");
1497
+ var ALGORITHM = "aes-256-gcm";
1498
+ function loadConfig() {
1499
+ if (!existsSync12(CONFIG_FILE)) {
1500
+ return { encrypted: false };
1501
+ }
1502
+ try {
1503
+ return JSON.parse(readFileSync12(CONFIG_FILE, "utf-8"));
1504
+ } catch {
1505
+ return { encrypted: false };
1506
+ }
1507
+ }
1508
+ function getKey() {
1509
+ return process.env.TOON_MEMORY_KEY;
1510
+ }
1511
+ function ensureMemoryDir() {
1512
+ if (!existsSync12(MEMORY_DIR3)) mkdirSync9(MEMORY_DIR3, { recursive: true });
1513
+ }
1514
+ function ensureMemoryFile() {
1515
+ ensureMemoryDir();
1516
+ if (!existsSync12(MEMORY_FILE)) {
1517
+ writeFileSync10(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed|links|quality|confidence}:\n");
1518
+ }
1519
+ }
1520
+
1521
+ // src/mcp/crypto.ts
1522
+ import { randomBytes, createCipheriv, createDecipheriv } from "crypto";
1523
+ function decrypt(encryptedData, key) {
1524
+ const keyBuffer = Buffer.from(key, "hex");
1525
+ const parts = encryptedData.split(":");
1526
+ if (parts.length !== 3) {
1527
+ throw new Error("Invalid encrypted data format: expected iv:authTag:ciphertext");
1528
+ }
1529
+ const [ivHex, authTagHex, encrypted] = parts;
1530
+ const iv = Buffer.from(ivHex, "hex");
1531
+ const authTag = Buffer.from(authTagHex, "hex");
1532
+ const decipher = createDecipheriv(ALGORITHM, keyBuffer, iv);
1533
+ decipher.setAuthTag(authTag);
1534
+ let decrypted = decipher.update(encrypted, "hex", "utf8");
1535
+ decrypted += decipher.final("utf8");
1536
+ return decrypted;
1537
+ }
1538
+
1539
+ // src/mcp/memory-io.ts
1540
+ function readMemory() {
1541
+ ensureMemoryFile();
1542
+ const config = loadConfig();
1543
+ const data = readUnderLock(MEMORY_FILE);
1544
+ if (config.encrypted) {
1545
+ const key = getKey();
1546
+ if (!key) throw new Error("Encryption enabled but TOON_MEMORY_KEY is not set. Run 'npx toon-memory init' or set the env var.");
1547
+ return decrypt(data, key);
1548
+ }
1549
+ return data;
1550
+ }
1551
+
1552
+ // src/lib/graph.ts
1553
+ var entryLines = (data) => data.split("\n").filter(
1554
+ (l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")
1555
+ );
1556
+ function parseEntries(data) {
1557
+ const out = [];
1558
+ for (const line of entryLines(data)) {
1559
+ const parts = line.trim().split("|");
1560
+ if (parts.length < 7) continue;
1561
+ const [id, category, key, content, file, tags, date, ttl, accessedRaw, linksRaw] = parts;
1562
+ out.push({
1563
+ id,
1564
+ category,
1565
+ key,
1566
+ content,
1567
+ file: file || "",
1568
+ tags: (tags || "").split(";").map((t) => t.trim()).filter(Boolean),
1569
+ date: date || "",
1570
+ ttl: ttl || "",
1571
+ accessed: accessedRaw ? parseInt(accessedRaw) || 0 : 0,
1572
+ links: (linksRaw || "").split(/[\s;]+/).map((t) => t.trim()).filter(Boolean),
1573
+ lastAccessed: parts.length > 12 ? parts[12] || "" : ""
1574
+ });
1575
+ }
1576
+ return out;
1577
+ }
1578
+ function buildGraph(entries) {
1579
+ const byKey = /* @__PURE__ */ new Map();
1580
+ for (const e of entries) {
1581
+ if (!byKey.has(e.key)) byKey.set(e.key, e);
1582
+ }
1583
+ const adj = /* @__PURE__ */ new Map();
1584
+ const link = (a, b) => {
1585
+ if (a === b) return;
1586
+ if (!byKey.has(a) || !byKey.has(b)) return;
1587
+ if (!adj.has(a)) adj.set(a, /* @__PURE__ */ new Set());
1588
+ adj.get(a).add(b);
1589
+ if (!adj.has(b)) adj.set(b, /* @__PURE__ */ new Set());
1590
+ adj.get(b).add(a);
1591
+ };
1592
+ for (const e of entries) {
1593
+ for (const l of e.links) link(e.key, l);
1594
+ const refs = e.content.match(/\[\[([\w-]+)\]\]/g) || [];
1595
+ for (const r of refs) link(e.key, r.slice(2, -2));
1596
+ }
1597
+ if (entries.some((e) => e.tags.length > 0)) {
1598
+ for (let i = 0; i < entries.length; i++) {
1599
+ const ei = entries[i];
1600
+ if (ei.tags.length === 0) continue;
1601
+ const eTags = new Set(ei.tags);
1602
+ for (let j = i + 1; j < entries.length; j++) {
1603
+ const ej = entries[j];
1604
+ if (ej.tags.length === 0) continue;
1605
+ let shared = 0;
1606
+ for (const t of ej.tags) if (eTags.has(t)) shared++;
1607
+ if (shared >= 2) link(ei.key, ej.key);
1608
+ }
1609
+ }
1610
+ }
1611
+ const adjacency = /* @__PURE__ */ new Map();
1612
+ for (const [k, v] of adj) adjacency.set(k, [...v]);
1613
+ return { adjacency, byKey };
1614
+ }
1615
+
1616
+ // src/viewer/data.ts
1617
+ function buildViewerData() {
1618
+ const data = readMemory();
1619
+ const entries = parseEntries(data);
1620
+ if (entries.length === 0) {
1621
+ console.log("Memory is empty. Nothing to display.");
1622
+ process.exit(0);
1623
+ }
1624
+ const graph = buildGraph(entries);
1625
+ const nodes = entries.map((e) => ({
1626
+ id: e.key,
1627
+ category: e.category,
1628
+ content: e.content.substring(0, 120),
1629
+ tags: e.tags,
1630
+ quality: e.accessed,
1631
+ accessCount: e.accessed,
1632
+ date: e.date,
1633
+ file: e.file,
1634
+ links: e.links,
1635
+ ttl: e.ttl,
1636
+ lastAccessed: e.lastAccessed
1637
+ }));
1638
+ const edges = [];
1639
+ const seen = /* @__PURE__ */ new Set();
1640
+ for (const [key, neighbors] of graph.adjacency) {
1641
+ for (const n of neighbors) {
1642
+ const pair = [key, n].sort().join("::");
1643
+ if (!seen.has(pair)) {
1644
+ seen.add(pair);
1645
+ edges.push({ source: key, target: n });
1646
+ }
1647
+ }
1648
+ }
1649
+ const categories = {};
1650
+ const tagCounts = {};
1651
+ for (const e of entries) {
1652
+ categories[e.category] = (categories[e.category] || 0) + 1;
1653
+ for (const t of e.tags) tagCounts[t] = (tagCounts[t] || 0) + 1;
1654
+ }
1655
+ return { nodes, edges, categories, tagCounts, totalEntries: entries.length };
1656
+ }
1657
+
1658
+ // src/viewer/html.ts
1659
+ function generateHtml(viewerData) {
1660
+ const jsonData = JSON.stringify(viewerData);
1661
+ return `<!DOCTYPE html>
1662
+ <html lang="en">
1663
+ <head>
1664
+ <meta charset="UTF-8">
1665
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1666
+ <title>toon-memory viewer</title>
1667
+ <script src="https://d3js.org/d3.v7.min.js"></script>
1668
+ <style>
1669
+ *{box-sizing:border-box;margin:0;padding:0}
1670
+ :root{
1671
+ --bg:#0a0a0f;--bg2:#12121a;--bg3:#1a1a26;--border:#2a2a3a;
1672
+ --text:#e2e2ee;--muted:#8888a0;--brand:#a78bfa;--brand2:#c084fc;
1673
+ --green:#22c55e;--red:#ef4444;--blue:#3b82f6;--amber:#f59e0b;
1674
+ --pink:#ec4899;--cyan:#06b6d4;
1675
+ }
1676
+ html,body{height:100%;font-family:system-ui,-apple-system,sans-serif;background:var(--bg);color:var(--text);overflow:hidden}
1677
+ .app{display:grid;grid-template-rows:auto 1fr;height:100vh}
1678
+ header{display:flex;align-items:center;justify-content:space-between;padding:0.75rem 1.5rem;border-bottom:1px solid var(--border);background:var(--bg2)}
1679
+ header h1{font-size:1.1rem;font-weight:700;background:linear-gradient(135deg,var(--brand),var(--pink));-webkit-background-clip:text;-webkit-text-fill-color:transparent}
1680
+ header .meta{display:flex;gap:1rem;font-size:0.8rem;color:var(--muted)}
1681
+ header .meta span{display:flex;align-items:center;gap:0.3rem}
1682
+ .main{display:grid;grid-template-columns:var(--sidebar-w,320px) 1fr;overflow:hidden;position:relative}
1683
+ .sidebar{display:flex;flex-direction:column;border-right:1px solid var(--border);overflow:hidden}
1684
+ .sidebar-resizer{width:4px;cursor:col-resize;background:transparent;position:absolute;left:var(--sidebar-w,320px);top:0;bottom:0;z-index:5;transition:background 0.15s}
1685
+ .sidebar-resizer:hover,.sidebar-resizer:active{background:var(--brand)}
1686
+ .sidebar-header{padding:0.75rem 1rem;border-bottom:1px solid var(--border);background:var(--bg2)}
1687
+ .sidebar-header h2{font-size:0.85rem;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:var(--muted);margin-bottom:0.5rem}
1688
+ .search-box{width:100%;padding:0.5rem 0.75rem;border:1px solid var(--border);border-radius:8px;background:var(--bg3);color:var(--text);font-size:0.85rem;outline:none}
1689
+ .search-box:focus{border-color:var(--brand)}
1690
+ .filter-row{display:flex;gap:0.4rem;margin-top:0.5rem;flex-wrap:wrap}
1691
+ .filter-btn{padding:0.2rem 0.5rem;border:1px solid var(--border);border-radius:6px;background:transparent;color:var(--muted);font-size:0.7rem;cursor:pointer;transition:all 0.15s}
1692
+ .filter-btn:hover,.filter-btn.active{border-color:var(--brand);color:var(--brand);background:rgba(167,139,250,0.1)}
1693
+ .entries-list{flex:1;overflow-y:auto;padding:0.5rem}
1694
+ .entry-item{padding:0.6rem 0.75rem;border:1px solid var(--border);border-radius:8px;margin-bottom:0.4rem;cursor:pointer;transition:all 0.15s}
1695
+ .entry-item:hover{border-color:var(--brand);background:rgba(167,139,250,0.05)}
1696
+ .entry-item.selected{border-color:var(--brand);background:rgba(167,139,250,0.1)}
1697
+ .entry-cat{font-size:0.65rem;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;margin-bottom:0.2rem}
1698
+ .entry-cat.decision{color:var(--brand)}
1699
+ .entry-cat.bug{color:var(--red)}
1700
+ .entry-cat.pattern{color:var(--green)}
1701
+ .entry-cat.knowledge{color:var(--cyan)}
1702
+ .entry-cat.architecture{color:var(--amber)}
1703
+ .entry-key{font-size:0.85rem;font-weight:600;margin-bottom:0.15rem}
1704
+ .entry-preview{font-size:0.75rem;color:var(--muted);line-height:1.4;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
1705
+ .entry-tags{display:flex;gap:0.25rem;margin-top:0.3rem;flex-wrap:wrap}
1706
+ .entry-tag{font-size:0.6rem;padding:0.1em 0.35rem;border-radius:3px;background:var(--bg3);color:var(--muted);font-family:monospace}
1707
+ .viewer-area{display:flex;flex-direction:column;overflow:hidden}
1708
+ .tabs{display:flex;border-bottom:1px solid var(--border);background:var(--bg2);padding:0 1rem}
1709
+ .tab{padding:0.6rem 1rem;font-size:0.8rem;font-weight:500;color:var(--muted);cursor:pointer;border-bottom:2px solid transparent;transition:all 0.15s}
1710
+ .tab:hover{color:var(--text)}
1711
+ .tab.active{color:var(--brand);border-bottom-color:var(--brand)}
1712
+ .tab-content{flex:1;overflow:hidden;position:relative}
1713
+ .tab-panel{display:none;width:100%;height:100%;overflow:auto}
1714
+ .tab-panel.active{display:block}
1715
+ .graph-container{width:100%;height:100%;background:var(--bg);position:relative}
1716
+ .graph-container::before{content:'';position:absolute;inset:0;background-image:radial-gradient(var(--border) 1px,transparent 1px);background-size:24px 24px;opacity:0.3;pointer-events:none;z-index:0}
1717
+ .graph-container svg{width:100%;height:100%;position:relative;z-index:1}
1718
+ .node-circle{cursor:pointer;transition:r 0.2s ease,opacity 0.2s ease,filter 0.2s ease,stroke 0.2s ease}
1719
+ .node-circle:hover{filter:brightness(1.3) drop-shadow(0 0 6px color-mix(in srgb,currentColor 60%,transparent))}
1720
+ .node-circle.glow{filter:drop-shadow(0 0 12px var(--brand)) brightness(1.5)}
1721
+ .node-circle.selected{stroke:var(--brand);stroke-width:3;filter:drop-shadow(0 0 14px var(--brand)) brightness(1.3)}
1722
+ .node-label{font-size:9px;font-family:monospace;fill:var(--text);pointer-events:none;text-anchor:middle;transition:opacity 0.2s ease;font-weight:500;letter-spacing:0.02em}
1723
+ .link{stroke:var(--border);stroke-opacity:0.4;transition:all 0.2s ease;cursor:pointer}
1724
+ .link:hover{stroke-opacity:0.9;stroke-width:3}
1725
+ .link.highlighted{stroke:var(--brand);stroke-opacity:0.9;stroke-width:2.5}
1726
+ .link.faded{stroke-opacity:0.04}
1727
+ .node-ring{fill:none;stroke-width:2;opacity:0;transition:opacity 0.3s ease,r 0.3s ease}
1728
+ .node-ring.visible{opacity:0.6}
1729
+ .stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:1rem;padding:1.5rem}
1730
+ .stat-card{background:var(--bg2);border:1px solid var(--border);border-radius:12px;padding:1.25rem}
1731
+ .stat-card h3{font-size:0.8rem;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:var(--muted);margin-bottom:0.75rem}
1732
+ .stat-big{font-size:2rem;font-weight:800;background:linear-gradient(135deg,var(--brand),var(--pink));-webkit-background-clip:text;-webkit-text-fill-color:transparent}
1733
+ .bar-chart{display:flex;flex-direction:column;gap:0.4rem}
1734
+ .bar-row{display:flex;align-items:center;gap:0.5rem}
1735
+ .bar-label{font-size:0.75rem;color:var(--muted);width:80px;text-align:right;flex-shrink:0}
1736
+ .bar-track{flex:1;height:20px;background:var(--bg3);border-radius:4px;overflow:hidden}
1737
+ .bar-fill{height:100%;border-radius:4px;transition:width 0.6s cubic-bezier(0.16,1,0.3,1)}
1738
+ .bar-value{font-size:0.7rem;color:var(--muted);width:30px}
1739
+ .tag-cloud{display:flex;flex-wrap:wrap;gap:0.4rem}
1740
+ .tag-pill{padding:0.25rem 0.6rem;border-radius:6px;font-size:0.75rem;font-family:monospace;border:1px solid var(--border);color:var(--muted);transition:all 0.15s}
1741
+ .tag-pill:hover{border-color:var(--brand);color:var(--brand)}
1742
+ .detail-panel{padding:1.5rem;max-width:700px}
1743
+ .detail-panel h2{font-size:1.2rem;font-weight:700;margin-bottom:0.5rem}
1744
+ .detail-panel .detail-cat{font-size:0.75rem;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;margin-bottom:1rem}
1745
+ .detail-field{margin-bottom:1rem}
1746
+ .detail-field label{display:block;font-size:0.75rem;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:0.05em;margin-bottom:0.3rem}
1747
+ .detail-field .value{font-size:0.9rem;line-height:1.6}
1748
+ .detail-field .value.mono{font-family:monospace;background:var(--bg3);padding:0.5rem;border-radius:6px;display:block;overflow-x:auto;white-space:pre-wrap}
1749
+ .detail-links{display:flex;gap:0.4rem;flex-wrap:wrap}
1750
+ .detail-link{padding:0.2rem 0.5rem;border:1px solid var(--border);border-radius:6px;font-size:0.75rem;font-family:monospace;color:var(--brand);cursor:pointer;transition:all 0.15s}
1751
+ .detail-link:hover{border-color:var(--brand);background:rgba(167,139,250,0.1)}
1752
+ .empty-detail{display:flex;align-items:center;justify-content:center;height:100%;color:var(--muted);font-size:0.9rem}
1753
+ .graph-legend{position:absolute;bottom:3.5rem;left:0.5rem;background:var(--bg2);border:1px solid var(--border);border-radius:8px;padding:0.75rem;font-size:0.7rem;z-index:10}
1754
+ .legend-item{display:flex;align-items:center;gap:0.4rem;margin-bottom:0.25rem}
1755
+ .legend-dot{width:10px;height:10px;border-radius:50%}
1756
+ .graph-controls{position:absolute;top:1rem;right:1rem;display:flex;gap:0.4rem;z-index:10}
1757
+ .graph-btn{width:32px;height:32px;border:1px solid var(--border);border-radius:6px;background:var(--bg2);color:var(--text);cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:1rem;transition:all 0.15s}
1758
+ .graph-btn:hover{border-color:var(--brand);color:var(--brand)}
1759
+ .tooltip{position:fixed;pointer-events:none;background:rgba(18,18,26,0.92);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);border:1px solid var(--border);border-radius:12px;padding:0.75rem 1rem;font-size:0.75rem;max-width:320px;z-index:1000;box-shadow:0 8px 32px rgba(0,0,0,0.5)}
1760
+ .tooltip .tt-cat{font-size:0.6rem;font-weight:600;text-transform:uppercase;margin-bottom:0.2rem}
1761
+ .tooltip .tt-key{font-weight:600;margin-bottom:0.2rem}
1762
+ .tooltip .tt-content{color:var(--muted);line-height:1.4;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden}
1763
+ .tooltip .tt-score{margin-top:0.3rem;font-size:0.65rem;color:var(--brand)}
1764
+ .tooltip .tt-edge{font-size:0.65rem;color:var(--muted);margin-top:0.3rem;padding-top:0.3rem;border-top:1px solid var(--border)}
1765
+ .timeline-container{padding:1.5rem;overflow-y:auto;height:100%}
1766
+ .timeline-header{font-size:1rem;font-weight:700;margin-bottom:1rem;color:var(--text)}
1767
+ .timeline-track{position:relative;padding-left:2rem}
1768
+ .timeline-line{position:absolute;left:0.5rem;top:0;bottom:0;width:2px;background:var(--border)}
1769
+ .timeline-entry{position:relative;margin-bottom:1rem;padding:0.6rem 0.8rem;border:1px solid var(--border);border-radius:8px;background:var(--bg2);transition:all 0.15s;cursor:pointer}
1770
+ .timeline-entry:hover{border-color:var(--brand)}
1771
+ .timeline-entry::before{content:'';position:absolute;left:-1.75rem;top:0.8rem;width:10px;height:10px;border-radius:50%;border:2px solid var(--border);background:var(--bg)}
1772
+ .timeline-entry .tl-date{font-size:0.65rem;color:var(--muted);margin-bottom:0.2rem}
1773
+ .timeline-entry .tl-cat{font-size:0.6rem;font-weight:600;text-transform:uppercase}
1774
+ .timeline-entry .tl-key{font-size:0.85rem;font-weight:600}
1775
+ .timeline-entry .tl-content{font-size:0.75rem;color:var(--muted);margin-top:0.2rem}
1776
+ .export-btn{padding:0.3rem 0.6rem;border:1px solid var(--border);border-radius:6px;background:var(--bg2);color:var(--text);font-size:0.7rem;cursor:pointer;transition:all 0.15s}
1777
+ .export-btn:hover{border-color:var(--brand);color:var(--brand)}
1778
+ .export-bar{display:flex;gap:0.4rem}
1779
+ .theme-toggle{background:none;border:1px solid var(--border);border-radius:6px;padding:0.3rem 0.6rem;color:var(--text);cursor:pointer;font-size:0.8rem;transition:all 0.15s}
1780
+ .theme-toggle:hover{border-color:var(--brand);color:var(--brand)}
1781
+ .reload-btn{background:none;border:1px solid var(--border);border-radius:6px;padding:0.3rem 0.6rem;color:var(--muted);cursor:pointer;font-size:0.9rem;transition:all 0.15s;line-height:1}
1782
+ .reload-btn:hover{border-color:var(--brand);color:var(--brand)}
1783
+ .minimap{width:150px;height:100px;background:var(--bg2);border:1px solid var(--border);border-radius:8px;overflow:hidden;box-shadow:0 4px 16px rgba(0,0,0,0.3);cursor:pointer}
1784
+ .minimap svg{width:100%;height:100%;display:block}
1785
+ .minimap-viewport{fill:rgba(167,139,250,0.15);stroke:var(--brand);stroke-width:1.5}
1786
+ .graph-right{position:absolute;bottom:1rem;right:1rem;z-index:10;display:flex;flex-direction:column;align-items:flex-end;gap:0.4rem}
1787
+ .physics-panel{position:absolute;top:2.8rem;left:0.5rem;background:var(--bg2);border:1px solid var(--border);border-radius:8px;padding:0.75rem;font-size:0.7rem;z-index:10;min-width:180px}
1788
+ .physics-panel h4{font-size:0.7rem;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:var(--muted);margin-bottom:0.5rem}
1789
+ .graph-toolbar{position:absolute;top:1rem;left:0.5rem;display:flex;gap:0.4rem;z-index:11}
1790
+ .physics-row{display:flex;align-items:center;gap:0.5rem;margin-bottom:0.4rem}
1791
+ .physics-row label{font-size:0.65rem;color:var(--muted);width:60px;flex-shrink:0}
1792
+ .physics-row input[type="range"]{flex:1;height:4px;-webkit-appearance:none;background:var(--bg3);border-radius:2px;outline:none}
1793
+ .physics-row input[type="range"]::-webkit-slider-thumb{-webkit-appearance:none;width:12px;height:12px;border-radius:50%;background:var(--brand);cursor:pointer}
1794
+ .physics-row .physics-val{font-size:0.6rem;color:var(--muted);width:30px;text-align:right}
1795
+ .node-circle.search-match{filter:drop-shadow(0 0 10px var(--brand)) brightness(1.4);animation:searchPulse 1.5s ease-in-out infinite}
1796
+ @keyframes searchPulse{0%,100%{filter:drop-shadow(0 0 8px var(--brand)) brightness(1.2)}50%{filter:drop-shadow(0 0 18px var(--brand)) brightness(1.7)}}
1797
+ .path-btn.active{background:var(--brand);color:#fff;border-color:var(--brand)}
1798
+ .path-info{position:absolute;bottom:0.5rem;left:0.5rem;background:var(--bg2);border:1px solid var(--border);border-radius:8px;padding:0.4rem 0.7rem;font-size:0.7rem;z-index:10;display:none;max-width:500px;word-break:break-all}
1799
+ .node-circle.path-start{stroke:var(--green);stroke-width:3;filter:drop-shadow(0 0 12px var(--green))}
1800
+ .node-circle.path-end{stroke:var(--red);stroke-width:3;filter:drop-shadow(0 0 12px var(--red))}
1801
+ .node-circle.path-node{stroke:var(--brand);stroke-width:2.5;animation:pathNodePulse 1.2s ease-in-out infinite}
1802
+ @keyframes pathNodePulse{0%,100%{filter:drop-shadow(0 0 6px var(--brand))}50%{filter:drop-shadow(0 0 14px var(--brand))}}
1803
+ .link.path-edge{stroke:var(--brand);stroke-opacity:0.9;stroke-width:3}
1804
+ .light{--bg:#f4f4f9;--bg2:#ffffff;--bg3:#e8e8f0;--border:#c8c8d8;--text:#1a1a2e;--muted:#666680;--brand:#7c3aed;--brand2:#9333ea}
1805
+ .light .tooltip{background:rgba(255,255,255,0.95);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);border-color:#c8c8d8;box-shadow:0 8px 32px rgba(0,0,0,0.1)}
1806
+ .light .timeline-entry{background:#fff}
1807
+ .light .graph-btn,.light .export-btn,.light .theme-toggle{background:#fff}
1808
+ .light .minimap{box-shadow:0 4px 16px rgba(0,0,0,0.08)}
1809
+ @media(max-width:768px){.main{grid-template-columns:1fr}.sidebar{display:none}}
1810
+ </style>
1811
+ </head>
1812
+ <body>
1813
+ <div class="app">
1814
+ <header>
1815
+ <h1>toon-memory viewer</h1>
1816
+ <div class="meta">
1817
+ <span id="totalCount"></span>
1818
+ <span id="edgeCount"></span>
1819
+ <span id="categoryCount"></span>
1820
+ <button class="theme-toggle" id="themeToggle" title="Toggle theme">\u2600</button>
1821
+ <button class="reload-btn" id="reloadBtn" title="Reload (r)">\u21BB</button>
1822
+ </div>
1823
+ </header>
1824
+ <div class="main">
1825
+ <div class="sidebar">
1826
+ <div class="sidebar-header">
1827
+ <h2>Entries</h2>
1828
+ <input type="text" class="search-box" id="search" placeholder="Search entries... (/)">
1829
+ <div class="filter-row" id="filters"></div>
1830
+ </div>
1831
+ <div class="entries-list" id="entriesList"></div>
1832
+ </div>
1833
+ <div class="sidebar-resizer" id="sidebarResizer"></div>
1834
+ <div class="viewer-area">
1835
+ <div class="tabs">
1836
+ <div class="tab active" data-tab="graph">Graph</div>
1837
+ <div class="tab" data-tab="stats">Stats</div>
1838
+ <div class="tab" data-tab="timeline">Timeline</div>
1839
+ <div class="tab" data-tab="detail">Detail</div>
1840
+ </div>
1841
+ <div class="tab-content">
1842
+ <div class="tab-panel active" id="panel-graph">
1843
+ <div class="graph-container" id="graphContainer">
1844
+ <div class="graph-legend" id="legend"></div>
1845
+ <div class="graph-right">
1846
+ <div class="export-bar">
1847
+ <button class="export-btn" id="exportPng">PNG</button>
1848
+ <button class="export-btn" id="exportSvg">SVG</button>
1849
+ </div>
1850
+ <div class="minimap" id="minimap"><svg id="minimapSvg"></svg></div>
1851
+ </div>
1852
+ <div class="graph-controls">
1853
+ <button class="graph-btn" id="zoomIn" title="Zoom in (+)">+</button>
1854
+ <button class="graph-btn" id="zoomOut" title="Zoom out (-)">\u2212</button>
1855
+ <button class="graph-btn" id="zoomReset" title="Reset (0)">\u27F2</button>
1856
+ </div>
1857
+ <div class="graph-toolbar">
1858
+ <button class="graph-btn" id="physicsToggle" title="Physics controls">\u2699</button>
1859
+ <button class="graph-btn path-btn" id="pathToggle" title="Find path between two nodes">\u21FF</button>
1860
+ </div>
1861
+ <div class="physics-panel" id="physicsPanel" style="display:none">
1862
+ <h4>Graph Physics</h4>
1863
+ <div class="physics-row"><label>Charge</label><input type="range" id="chargeSlider" min="-300" max="0" value="-120" step="10"><span class="physics-val" id="chargeVal">-120</span></div>
1864
+ <div class="physics-row"><label>Distance</label><input type="range" id="distSlider" min="20" max="200" value="70" step="5"><span class="physics-val" id="distVal">70</span></div>
1865
+ <div class="physics-row"><label>Center</label><input type="range" id="centerSlider" min="0" max="1" value="0.05" step="0.01"><span class="physics-val" id="centerVal">0.05</span></div>
1866
+ </div>
1867
+ <div class="path-info" id="pathInfo"></div>
1868
+ </div>
1869
+ </div>
1870
+ <div class="tab-panel" id="panel-stats">
1871
+ <div class="stats-grid" id="statsGrid"></div>
1872
+ </div>
1873
+ <div class="tab-panel" id="panel-timeline">
1874
+ <div class="timeline-container" id="timelineContainer"></div>
1875
+ </div>
1876
+ <div class="tab-panel" id="panel-detail">
1877
+ <div class="detail-panel" id="detailPanel">
1878
+ <div class="empty-detail">Select an entry from the sidebar or click a node in the graph</div>
1879
+ </div>
1880
+ </div>
1881
+ </div>
1882
+ </div>
1883
+ </div>
1884
+ </div>
1885
+ <div class="tooltip" id="tooltip" style="display:none"></div>
1886
+ <script>
1887
+ const DATA = ${jsonData};
1888
+
1889
+ const COLORS = {
1890
+ decision: '#a78bfa', bug: '#ef4444', pattern: '#22c55e',
1891
+ knowledge: '#06b6d4', architecture: '#f59e0b'
1892
+ };
1893
+
1894
+ let selectedEntry = null;
1895
+ let activeFilter = null;
1896
+ let searchQuery = '';
1897
+
1898
+ // --- Theme Toggle ---
1899
+ const themeToggle = document.getElementById('themeToggle');
1900
+ const savedTheme = localStorage.getItem('toon-viewer-theme') || 'dark';
1901
+ if (savedTheme === 'light') { document.documentElement.classList.add('light'); themeToggle.textContent = '\u263E'; }
1902
+ themeToggle.addEventListener('click', () => {
1903
+ document.documentElement.classList.toggle('light');
1904
+ const isLight = document.documentElement.classList.contains('light');
1905
+ themeToggle.textContent = isLight ? '\u263E' : '\u2600';
1906
+ localStorage.setItem('toon-viewer-theme', isLight ? 'light' : 'dark');
1907
+ });
1908
+
1909
+ // --- Tooltip ---
1910
+ const tooltip = document.getElementById('tooltip');
1911
+ function showTooltip(e, d) {
1912
+ const score = d.quality || 0;
1913
+ tooltip.innerHTML =
1914
+ '<div class="tt-cat" style="color:' + (COLORS[d.category] || 'var(--muted)') + '">' + d.category + '</div>' +
1915
+ '<div class="tt-key">' + escHtml(d.id) + '</div>' +
1916
+ '<div class="tt-content">' + escHtml(d.content) + '</div>' +
1917
+ '<div class="tt-score">Quality: ' + score.toFixed(2) + ' | Access: ' + (d.accessCount || 0) + '</div>';
1918
+ tooltip.style.display = 'block';
1919
+ positionTooltip(e);
1920
+ }
1921
+ function positionTooltip(e) {
1922
+ const x = e.clientX + 12;
1923
+ const y = e.clientY + 12;
1924
+ const rect = tooltip.getBoundingClientRect();
1925
+ tooltip.style.left = (x + rect.width > window.innerWidth ? e.clientX - rect.width - 8 : x) + 'px';
1926
+ tooltip.style.top = (y + rect.height > window.innerHeight ? e.clientY - rect.height - 8 : y) + 'px';
1927
+ }
1928
+ function hideTooltip() { tooltip.style.display = 'none'; }
1929
+ document.addEventListener('mousemove', (e) => { if (tooltip.style.display === 'block') positionTooltip(e); });
1930
+
1931
+ // --- Header ---
1932
+ document.getElementById('totalCount').textContent = DATA.totalEntries + ' entries';
1933
+ document.getElementById('edgeCount').textContent = DATA.edges.length + ' edges';
1934
+ document.getElementById('categoryCount').textContent = Object.keys(DATA.categories).length + ' categories';
1935
+
1936
+ // --- Tabs ---
1937
+ document.querySelectorAll('.tab').forEach(tab => {
1938
+ tab.addEventListener('click', () => {
1939
+ document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
1940
+ document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
1941
+ tab.classList.add('active');
1942
+ document.getElementById('panel-' + tab.dataset.tab).classList.add('active');
1943
+ if (tab.dataset.tab === 'graph') setTimeout(() => graph.resize(), 50);
1944
+ });
1945
+ });
1946
+
1947
+ function switchTab(name) {
1948
+ document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
1949
+ document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
1950
+ document.querySelector('[data-tab="' + name + '"]').classList.add('active');
1951
+ document.getElementById('panel-' + name).classList.add('active');
1952
+ }
1953
+
1954
+ // --- Filters ---
1955
+ const filterContainer = document.getElementById('filters');
1956
+ const allBtn = document.createElement('button');
1957
+ allBtn.className = 'filter-btn active';
1958
+ allBtn.textContent = 'All';
1959
+ allBtn.onclick = () => setFilter(null);
1960
+ filterContainer.appendChild(allBtn);
1961
+ Object.keys(DATA.categories).sort().forEach(cat => {
1962
+ const btn = document.createElement('button');
1963
+ btn.className = 'filter-btn';
1964
+ btn.textContent = cat;
1965
+ btn.dataset.cat = cat;
1966
+ btn.onclick = () => setFilter(cat);
1967
+ filterContainer.appendChild(btn);
1968
+ });
1969
+
1970
+ function setFilter(cat) {
1971
+ activeFilter = cat;
1972
+ document.querySelectorAll('.filter-btn').forEach(b => {
1973
+ b.classList.toggle('active', cat === null ? !b.dataset.cat : b.dataset.cat === cat);
1974
+ });
1975
+ renderEntries();
1976
+ if (graph.highlightSearch) graph.highlightSearch();
1977
+ }
1978
+
1979
+ // --- Search ---
1980
+ document.getElementById('search').addEventListener('input', (e) => {
1981
+ searchQuery = e.target.value.toLowerCase();
1982
+ renderEntries();
1983
+ if (graph.highlightSearch) graph.highlightSearch();
1984
+ if (searchQuery && graph.centerOn) {
1985
+ const first = DATA.nodes.find(n => n.id.toLowerCase().includes(searchQuery) || n.content.toLowerCase().includes(searchQuery) || n.tags.some(t => t.toLowerCase().includes(searchQuery)));
1986
+ if (first) graph.centerOn(first.id);
1987
+ }
1988
+ });
1989
+
1990
+ // --- Entries List ---
1991
+ function renderEntries() {
1992
+ const q = searchQuery;
1993
+ const list = document.getElementById('entriesList');
1994
+ list.innerHTML = '';
1995
+ DATA.nodes
1996
+ .filter(e => !activeFilter || e.category === activeFilter)
1997
+ .filter(e => !q || e.id.toLowerCase().includes(q) || e.content.toLowerCase().includes(q) || e.tags.some(t => t.toLowerCase().includes(q)))
1998
+ .forEach(e => {
1999
+ const div = document.createElement('div');
2000
+ div.className = 'entry-item' + (selectedEntry && selectedEntry.id === e.id ? ' selected' : '');
2001
+ div.innerHTML =
2002
+ '<div class="entry-cat ' + e.category + '">' + e.category + '</div>' +
2003
+ '<div class="entry-key">' + escHtml(e.id) + '</div>' +
2004
+ '<div class="entry-preview">' + escHtml(e.content) + '</div>' +
2005
+ (e.tags.length ? '<div class="entry-tags">' + e.tags.map(t => '<span class="entry-tag">' + escHtml(t) + '</span>').join('') + '</div>' : '');
2006
+ div.onclick = () => selectEntry(e);
2007
+ list.appendChild(div);
2008
+ });
2009
+ }
2010
+
2011
+ function escHtml(s) { return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }
2012
+
2013
+ // --- Entry Selection ---
2014
+ function selectEntry(entry) {
2015
+ selectedEntry = entry;
2016
+ renderEntries();
2017
+ showDetail(entry);
2018
+ graph.highlightNode(entry.id);
2019
+ graph.centerOn(entry.id);
2020
+ switchTab('detail');
2021
+ }
2022
+
2023
+ function showDetail(e) {
2024
+ const panel = document.getElementById('detailPanel');
2025
+ const linkedNodes = DATA.edges
2026
+ .filter(ed => (typeof ed.source === 'object' ? ed.source.id : ed.source) === e.id || (typeof ed.target === 'object' ? ed.target.id : ed.target) === e.id)
2027
+ .map(ed => (typeof ed.source === 'object' ? ed.source.id : ed.source) === e.id ? (typeof ed.target === 'object' ? ed.target.id : ed.target) : (typeof ed.source === 'object' ? ed.source.id : ed.source));
2028
+
2029
+ panel.innerHTML =
2030
+ '<div class="detail-cat" style="color:' + (COLORS[e.category] || 'var(--muted)') + '">' + e.category + '</div>' +
2031
+ '<h2>' + escHtml(e.id) + '</h2>' +
2032
+ '<div class="detail-field"><label>Content</label><span class="value mono">' + escHtml(e.content) + '</span></div>' +
2033
+ (e.file ? '<div class="detail-field"><label>File</label><span class="value mono"><a href="#" onclick="event.preventDefault()" style="color:var(--brand);text-decoration:none;cursor:pointer">' + escHtml(e.file) + '</a></span></div>' : '') +
2034
+ (e.date ? '<div class="detail-field"><label>Date</label><span class="value">' + e.date + '</span></div>' : '') +
2035
+ '<div class="detail-field"><label>Quality Score</label><span class="value" style="color:var(--brand);font-weight:700;font-size:1.1rem">' + (e.quality || 0).toFixed(3) + '</span></div>' +
2036
+ '<div class="detail-field"><label>Access Count</label><span class="value">' + (e.accessCount || 0) + '</span></div>' +
2037
+ (e.ttl ? '<div class="detail-field"><label>TTL</label><span class="value">' + e.ttl + '</span></div>' : '') +
2038
+ (e.lastAccessed ? '<div class="detail-field"><label>Last Accessed</label><span class="value">' + e.lastAccessed + '</span></div>' : '') +
2039
+ (e.tags.length ? '<div class="detail-field"><label>Tags</label><div class="entry-tags">' + e.tags.map(t => '<span class="entry-tag">' + escHtml(t) + '</span>').join('') + '</div></div>' : '') +
2040
+ (linkedNodes.length ? '<div class="detail-field"><label>Linked Entries (' + linkedNodes.length + ')</label><div class="detail-links">' + linkedNodes.map(k => '<span class="detail-link" onclick="selectEntryById(\\'' + k + '\\')">' + escHtml(k) + '</span>').join('') + '</div></div>' : '');
2041
+ }
2042
+
2043
+ window.selectEntryById = function(id) {
2044
+ const e = DATA.nodes.find(n => n.id === id);
2045
+ if (e) selectEntry(e);
2046
+ };
2047
+
2048
+ // --- Stats ---
2049
+ function renderStats() {
2050
+ const grid = document.getElementById('statsGrid');
2051
+ const catEntries = Object.entries(DATA.categories).sort((a,b) => b[1] - a[1]);
2052
+ const maxCat = Math.max(...catEntries.map(c => c[1]));
2053
+ const topTags = Object.entries(DATA.tagCounts).sort((a,b) => b[1] - a[1]).slice(0, 20);
2054
+ const maxTag = Math.max(...topTags.map(t => t[1]));
2055
+ const avgQuality = DATA.nodes.reduce((s, n) => s + (n.quality || 0), 0) / DATA.nodes.length;
2056
+ const maxAccess = Math.max(...DATA.nodes.map(n => n.accessCount || 0));
2057
+
2058
+ grid.innerHTML =
2059
+ '<div class="stat-card"><h3>Total Entries</h3><div class="stat-big">' + DATA.totalEntries + '</div></div>' +
2060
+ '<div class="stat-card"><h3>Graph Edges</h3><div class="stat-big">' + DATA.edges.length + '</div></div>' +
2061
+ '<div class="stat-card"><h3>Avg Quality</h3><div class="stat-big">' + avgQuality.toFixed(2) + '</div></div>' +
2062
+ '<div class="stat-card"><h3>Max Access</h3><div class="stat-big">' + maxAccess + '</div></div>' +
2063
+ '<div class="stat-card"><h3>Categories</h3><div class="bar-chart">' +
2064
+ catEntries.map(([cat, count]) =>
2065
+ '<div class="bar-row"><span class="bar-label">' + cat + '</span><div class="bar-track"><div class="bar-fill" style="width:' + (count/maxCat*100) + '%;background:' + (COLORS[cat] || 'var(--brand)') + '"></div></div><span class="bar-value">' + count + '</span></div>'
2066
+ ).join('') +
2067
+ '</div></div>' +
2068
+ '<div class="stat-card"><h3>Top Tags</h3><div class="tag-cloud">' +
2069
+ topTags.map(([tag, count]) =>
2070
+ '<span class="tag-pill">' + escHtml(tag) + ' <small>(' + count + ')</small></span>'
2071
+ ).join('') +
2072
+ '</div></div>';
2073
+ }
2074
+
2075
+ function renderTimeline() {
2076
+ const container = document.getElementById('timelineContainer');
2077
+ const sorted = [...DATA.nodes].sort((a, b) => (b.date || '').localeCompare(a.date || ''));
2078
+ const grouped = {};
2079
+ sorted.forEach(e => {
2080
+ const d = e.date || 'unknown';
2081
+ if (!grouped[d]) grouped[d] = [];
2082
+ grouped[d].push(e);
2083
+ });
2084
+
2085
+ let html = '<div class="timeline-header">Timeline (' + DATA.totalEntries + ' entries)</div><div class="timeline-track"><div class="timeline-line"></div>';
2086
+ for (const [date, entries] of Object.entries(grouped)) {
2087
+ for (const e of entries) {
2088
+ html += '<div class="timeline-entry" onclick="selectEntryById(\\'' + e.id + '\\')" style="border-left:3px solid ' + (COLORS[e.category] || 'var(--border)') + '">' +
2089
+ '<div class="tl-date">' + escHtml(date) + '</div>' +
2090
+ '<div class="tl-cat" style="color:' + (COLORS[e.category] || 'var(--muted)') + '">' + e.category + '</div>' +
2091
+ '<div class="tl-key">' + escHtml(e.id) + '</div>' +
2092
+ '<div class="tl-content">' + escHtml(e.content.substring(0, 100)) + '</div>' +
2093
+ '</div>';
2094
+ }
2095
+ }
2096
+ html += '</div>';
2097
+ container.innerHTML = html;
2098
+ }
2099
+
2100
+ // --- Graph ---
2101
+ const graph = (function() {
2102
+ const container = document.getElementById('graphContainer');
2103
+ const width = container.clientWidth;
2104
+ const height = container.clientHeight;
2105
+ const svg = d3.select(container).append('svg').attr('width', '100%').attr('height', '100%');
2106
+
2107
+ const defs = svg.append('defs');
2108
+ const filter = defs.append('filter').attr('id', 'glow').attr('x', '-50%').attr('y', '-50%').attr('width', '200%').attr('height', '200%');
2109
+ filter.append('feGaussianBlur').attr('stdDeviation', '4').attr('result', 'blur');
2110
+ filter.append('feMerge').selectAll('feMergeNode').data(['blur', 'SourceGraphic']).join('feMergeNode').attr('in', d => d);
2111
+
2112
+ const g = svg.append('g');
2113
+ let currentTransform = d3.zoomIdentity;
2114
+ const zoom = d3.zoom().scaleExtent([0.1, 4]).on('zoom', e => { g.attr('transform', e.transform); currentTransform = e.transform; updateMinimap(); });
2115
+ svg.call(zoom);
2116
+
2117
+ function nodeRadius(d) { return 4 + Math.min((d.accessCount || 0) * 0.8, 8); }
2118
+
2119
+ const connectionCount = new Map();
2120
+ DATA.edges.forEach(e => {
2121
+ const s = typeof e.source === 'object' ? e.source.id : e.source;
2122
+ const t = typeof e.target === 'object' ? e.target.id : e.target;
2123
+ connectionCount.set(s, (connectionCount.get(s) || 0) + 1);
2124
+ connectionCount.set(t, (connectionCount.get(t) || 0) + 1);
2125
+ });
2126
+ function edgeWidth(d) {
2127
+ const s = typeof d.source === 'object' ? d.source.id : d.source;
2128
+ const t = typeof d.target === 'object' ? d.target.id : d.target;
2129
+ const shared = Math.min(connectionCount.get(s) || 1, connectionCount.get(t) || 1);
2130
+ return 0.5 + Math.min(shared * 0.3, 3);
2131
+ }
2132
+
2133
+ function getSharedTags(a, b) {
2134
+ const na = nodeMap.get(a), nb = nodeMap.get(b);
2135
+ if (!na || !nb || !na.tags || !nb.tags) return [];
2136
+ return na.tags.filter(t => nb.tags.includes(t));
2137
+ }
2138
+
2139
+ let chargeStrength = -120;
2140
+ let linkDistance = 70;
2141
+ let centerStrength = 0.05;
2142
+
2143
+ const nodeMap = new Map(DATA.nodes.map(n => [n.id, n]));
2144
+ const simulation = d3.forceSimulation(DATA.nodes)
2145
+ .force('link', d3.forceLink(DATA.edges).id(d => d.id).distance(linkDistance).strength(0.5))
2146
+ .force('charge', d3.forceManyBody().strength(chargeStrength))
2147
+ .force('center', d3.forceCenter(width / 2, height / 2).strength(centerStrength))
2148
+ .force('collision', d3.forceCollide().radius(d => nodeRadius(d) + 4));
2149
+
2150
+ const link = g.append('g').selectAll('line').data(DATA.edges).join('line')
2151
+ .attr('class', 'link')
2152
+ .attr('stroke-width', d => edgeWidth(d))
2153
+ .attr('stroke-linecap', 'round');
2154
+
2155
+ const node = g.append('g').selectAll('circle').data(DATA.nodes).join('circle')
2156
+ .attr('class', 'node-circle')
2157
+ .attr('r', d => nodeRadius(d))
2158
+ .attr('fill', d => COLORS[d.category] || '#888')
2159
+ .attr('stroke', d => { const c = COLORS[d.category] || '#888'; return c; })
2160
+ .attr('stroke-width', 1.5)
2161
+ .attr('stroke-opacity', 0.6)
2162
+ .call(d3.drag()
2163
+ .on('start', (e, d) => { if (!e.active) simulation.alphaTarget(0.3).restart(); d.fx = d.x; d.fy = d.y; })
2164
+ .on('drag', (e, d) => { d.fx = e.x; d.fy = e.y; })
2165
+ .on('end', (e, d) => { if (!e.active) simulation.alphaTarget(0); })
2166
+ )
2167
+ .on('contextmenu', (e, d) => { e.preventDefault(); d.fx = null; d.fy = null; simulation.alpha(0.3).restart(); });
2168
+ const label = g.append('g').selectAll('text').data(DATA.nodes).join('text')
2169
+ .attr('class', 'node-label').attr('dy', d => -(nodeRadius(d) + 4))
2170
+ .text(d => d.id.length > 18 ? d.id.substring(0, 16) + '..' : d.id);
2171
+
2172
+ // Edge tooltips
2173
+ link.on('mouseover', (e, d) => {
2174
+ const s = typeof d.source === 'object' ? d.source.id : d.source;
2175
+ const t = typeof d.target === 'object' ? d.target.id : d.target;
2176
+ const sharedTags = getSharedTags(s, t);
2177
+ const html = '<div class="tt-edge">' +
2178
+ '<span style="color:' + (COLORS[nodeMap.get(s)?.category] || 'var(--muted)') + '">' + escHtml(s) + '</span>' +
2179
+ ' \u2192 ' +
2180
+ '<span style="color:' + (COLORS[nodeMap.get(t)?.category] || 'var(--muted)') + '">' + escHtml(t) + '</span>' +
2181
+ (sharedTags.length ? '<br>Tags: ' + sharedTags.map(tag => '<span class="entry-tag">' + escHtml(tag) + '</span>').join(' ') : '') +
2182
+ '</div>';
2183
+ tooltip.innerHTML = html;
2184
+ tooltip.style.display = 'block';
2185
+ positionTooltip(e);
2186
+ })
2187
+ .on('mouseout', () => { hideTooltip(); });
2188
+
2189
+ node.on('mouseover', (e, d) => {
2190
+ showTooltip(e, d);
2191
+ highlightNode(d.id);
2192
+ })
2193
+ .on('mouseout', () => {
2194
+ hideTooltip();
2195
+ if (!selectedEntry) highlightNode(null);
2196
+ else highlightNode(selectedEntry.id);
2197
+ });
2198
+
2199
+ svg.on('click', () => { selectedEntry = null; highlightNode(null); renderEntries(); });
2200
+
2201
+ simulation.on('tick', () => {
2202
+ link.attr('x1', d => d.source.x).attr('y1', d => d.source.y)
2203
+ .attr('x2', d => d.target.x).attr('y2', d => d.target.y);
2204
+ node.attr('cx', d => d.x).attr('cy', d => d.y);
2205
+ label.attr('x', d => d.x).attr('y', d => d.y);
2206
+ updateMinimap();
2207
+ });
2208
+
2209
+ function highlightNode(id) {
2210
+ const neighbors = new Set();
2211
+ if (id) {
2212
+ DATA.edges.forEach(e => {
2213
+ const s = typeof e.source === 'object' ? e.source.id : e.source;
2214
+ const t = typeof e.target === 'object' ? e.target.id : e.target;
2215
+ if (s === id) neighbors.add(t);
2216
+ if (t === id) neighbors.add(s);
2217
+ });
2218
+ neighbors.add(id);
2219
+ }
2220
+ node.attr('r', d => id ? (d.id === id ? nodeRadius(d) + 4 : neighbors.has(d.id) ? nodeRadius(d) + 1 : 2) : nodeRadius(d))
2221
+ .attr('opacity', d => id ? (neighbors.has(d.id) ? 1 : 0.12) : 1)
2222
+ .classed('glow', d => id && d.id === id);
2223
+ link.classed('highlighted', d => id && ((typeof d.source === 'object' ? d.source.id : d.source) === id || (typeof d.target === 'object' ? d.target.id : d.target) === id));
2224
+ link.attr('opacity', d => id ? (((typeof d.source === 'object' ? d.source.id : d.source) === id || (typeof d.target === 'object' ? d.target.id : d.target) === id) ? 1 : 0.04) : 0.5);
2225
+ label.attr('opacity', d => id ? (neighbors.has(d.id) ? 1 : 0.08) : 1);
2226
+ }
2227
+
2228
+ function highlightSearch() {
2229
+ if (!searchQuery && !activeFilter) { highlightNode(null); return; }
2230
+ const q = searchQuery;
2231
+ const matches = new Set();
2232
+ DATA.nodes.forEach(n => {
2233
+ const match = (!q || n.id.toLowerCase().includes(q) || n.content.toLowerCase().includes(q) || n.tags.some(t => t.toLowerCase().includes(q)));
2234
+ const catMatch = !activeFilter || n.category === activeFilter;
2235
+ if (match && catMatch) matches.add(n.id);
2236
+ });
2237
+ node.attr('r', d => matches.has(d.id) ? nodeRadius(d) + 3 : 2)
2238
+ .attr('opacity', d => matches.has(d.id) ? 1 : 0.06)
2239
+ .classed('glow search-match', d => matches.has(d.id));
2240
+ label.attr('opacity', d => matches.has(d.id) ? 1 : 0.03);
2241
+ link.attr('opacity', 0.03);
2242
+ }
2243
+
2244
+ // Zoom controls
2245
+ document.getElementById('zoomIn').onclick = () => svg.transition().call(zoom.scaleBy, 1.5);
2246
+ document.getElementById('zoomOut').onclick = () => svg.transition().call(zoom.scaleBy, 0.67);
2247
+ document.getElementById('zoomReset').onclick = () => svg.transition().call(zoom.transform, d3.zoomIdentity);
2248
+
2249
+ // Legend
2250
+ const legend = document.getElementById('legend');
2251
+ legend.innerHTML = Object.entries(COLORS).map(([cat, color]) =>
2252
+ '<div class="legend-item"><span class="legend-dot" style="background:' + color + '"></span>' + cat + '</div>'
2253
+ ).join('');
2254
+
2255
+ // Physics controls
2256
+ const physicsToggle = document.getElementById('physicsToggle');
2257
+ const physicsPanel = document.getElementById('physicsPanel');
2258
+ physicsToggle.onclick = () => {
2259
+ physicsPanel.style.display = physicsPanel.style.display === 'none' ? 'block' : 'none';
2260
+ };
2261
+
2262
+ function updatePhysics() {
2263
+ simulation.force('charge').strength(chargeStrength);
2264
+ simulation.force('link').distance(linkDistance);
2265
+ simulation.force('center').strength(centerStrength);
2266
+ simulation.alpha(0.5).restart();
2267
+ }
2268
+
2269
+ document.getElementById('chargeSlider').oninput = (e) => {
2270
+ chargeStrength = parseInt(e.target.value);
2271
+ document.getElementById('chargeVal').textContent = chargeStrength;
2272
+ updatePhysics();
2273
+ };
2274
+ document.getElementById('distSlider').oninput = (e) => {
2275
+ linkDistance = parseInt(e.target.value);
2276
+ document.getElementById('distVal').textContent = linkDistance;
2277
+ updatePhysics();
2278
+ };
2279
+ document.getElementById('centerSlider').oninput = (e) => {
2280
+ centerStrength = parseFloat(e.target.value);
2281
+ document.getElementById('centerVal').textContent = centerStrength;
2282
+ updatePhysics();
2283
+ };
2284
+
2285
+ // Center on a node
2286
+ function centerOn(id) {
2287
+ const n = DATA.nodes.find(d => d.id === id);
2288
+ if (!n || n.x == null) return;
2289
+ const w = container.clientWidth, h = container.clientHeight;
2290
+ svg.transition().duration(400).call(zoom.transform,
2291
+ d3.zoomIdentity.translate(w / 2 - n.x * currentTransform.k, h / 2 - n.y * currentTransform.k).scale(currentTransform.k));
2292
+ }
2293
+
2294
+ // Path finder
2295
+ let pathStart = null, pathActive = false;
2296
+ function findPath(a, b) {
2297
+ const adj = new Map();
2298
+ DATA.edges.forEach(e => {
2299
+ const s = typeof e.source === 'object' ? e.source.id : e.source;
2300
+ const t = typeof e.target === 'object' ? e.target.id : e.target;
2301
+ if (!adj.has(s)) adj.set(s, []);
2302
+ if (!adj.has(t)) adj.set(t, []);
2303
+ adj.get(s).push(t);
2304
+ adj.get(t).push(s);
2305
+ });
2306
+ const visited = new Set([a]), parent = new Map([[a, null]]);
2307
+ const queue = [a];
2308
+ while (queue.length) {
2309
+ const cur = queue.shift();
2310
+ if (cur === b) break;
2311
+ for (const nb of (adj.get(cur) || [])) {
2312
+ if (!visited.has(nb)) { visited.add(nb); parent.set(nb, cur); queue.push(nb); }
2313
+ }
2314
+ }
2315
+ if (!parent.has(b)) return null;
2316
+ const path = [];
2317
+ let cur = b;
2318
+ while (cur !== null) { path.unshift(cur); cur = parent.get(cur); }
2319
+ return path;
2320
+ }
2321
+ function highlightPath(path) {
2322
+ link.classed('path-edge', false).attr('opacity', 0.5);
2323
+ node.classed('path-start path-end path-node', false).attr('r', d => nodeRadius(d));
2324
+ if (!path) return;
2325
+ const set = new Set(path);
2326
+ path.forEach((id, i) => {
2327
+ node.filter(d => d.id === id)
2328
+ .classed(i === 0 ? 'path-start' : i === path.length - 1 ? 'path-end' : 'path-node', true)
2329
+ .attr('r', d => nodeRadius(d) + 3);
2330
+ });
2331
+ for (let i = 0; i < path.length - 1; i++) {
2332
+ link.filter(d => {
2333
+ const s = typeof d.source === 'object' ? d.source.id : d.source;
2334
+ const t = typeof d.target === 'object' ? d.target.id : d.target;
2335
+ return (s === path[i] && t === path[i+1]) || (s === path[i+1] && t === path[i]);
2336
+ }).classed('path-edge', true).attr('opacity', 1);
2337
+ }
2338
+ }
2339
+
2340
+ // Minimap
2341
+ const minimapSvg = d3.select('#minimapSvg');
2342
+ const minimapScale = 0.1;
2343
+ const minimapW = 150, minimapH = 100;
2344
+ const minimapG = minimapSvg.append('g');
2345
+ minimapG.append('g').attr('class', 'minimap-links');
2346
+ minimapG.append('g').attr('class', 'minimap-nodes');
2347
+ const minimapViewport = minimapSvg.append('rect').attr('class', 'minimap-viewport').attr('fill', 'rgba(167,139,250,0.12)').attr('stroke', 'var(--brand)').attr('stroke-width', 1.5).attr('rx', 3);
2348
+
2349
+ function getGraphBounds() {
2350
+ const allX = DATA.nodes.map(n => n.x || 0);
2351
+ const allY = DATA.nodes.map(n => n.y || 0);
2352
+ return { minX: Math.min(...allX) - 20, minY: Math.min(...allY) - 20, maxX: Math.max(...allX) + 20, maxY: Math.max(...allY) + 20 };
2353
+ }
2354
+
2355
+ function updateMinimap() {
2356
+ const { minX, minY } = getGraphBounds();
2357
+ minimapG.attr('transform', 'translate(' + (-minX * minimapScale) + ',' + (-minY * minimapScale) + ')');
2358
+
2359
+ minimapG.select('.minimap-links').selectAll('line').data(DATA.edges).join('line')
2360
+ .attr('x1', d => (d.source.x || 0) * minimapScale)
2361
+ .attr('y1', d => (d.source.y || 0) * minimapScale)
2362
+ .attr('x2', d => (d.target.x || 0) * minimapScale)
2363
+ .attr('y2', d => (d.target.y || 0) * minimapScale)
2364
+ .attr('stroke', 'var(--border)').attr('stroke-width', 0.5).attr('stroke-opacity', 0.3);
2365
+
2366
+ minimapG.select('.minimap-nodes').selectAll('circle').data(DATA.nodes).join('circle')
2367
+ .attr('cx', d => (d.x || 0) * minimapScale).attr('cy', d => (d.y || 0) * minimapScale)
2368
+ .attr('r', 1.8).attr('fill', d => COLORS[d.category] || '#888').attr('stroke', 'none');
2369
+
2370
+ const t = currentTransform;
2371
+ const containerW = container.clientWidth;
2372
+ const containerH = container.clientHeight;
2373
+ const vpX = (-t.x / t.k - minX) * minimapScale;
2374
+ const vpY = (-t.y / t.k - minY) * minimapScale;
2375
+ const vpW = (containerW / t.k) * minimapScale;
2376
+ const vpH = (containerH / t.k) * minimapScale;
2377
+ minimapViewport.attr('x', Math.max(0, vpX)).attr('y', Math.max(0, vpY))
2378
+ .attr('width', Math.min(vpW, minimapW)).attr('height', Math.min(vpH, minimapH));
2379
+ }
2380
+
2381
+ minimapSvg.on('click', (e) => {
2382
+ const { minX, minY } = getGraphBounds();
2383
+ const rect = minimapSvg.node().getBoundingClientRect();
2384
+ const mmx = (e.clientX - rect.left) / minimapScale + minX;
2385
+ const mmy = (e.clientY - rect.top) / minimapScale + minY;
2386
+ const w2 = container.clientWidth / 2, h2 = container.clientHeight / 2;
2387
+ svg.transition().duration(300).call(zoom.transform, d3.zoomIdentity.translate(w2 - mmx, h2 - mmy));
2388
+ });
2389
+
2390
+ // Export PNG
2391
+ document.getElementById('exportPng').onclick = () => {
2392
+ const svgEl = container.querySelector('svg');
2393
+ const svgData = new XMLSerializer().serializeToString(svgEl);
2394
+ const canvas = document.createElement('canvas');
2395
+ const ctx = canvas.getContext('2d');
2396
+ const img = new Image();
2397
+ canvas.width = svgEl.clientWidth * 2;
2398
+ canvas.height = svgEl.clientHeight * 2;
2399
+ img.onload = () => {
2400
+ ctx.fillStyle = getComputedStyle(document.documentElement).getPropertyValue('--bg').trim();
2401
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
2402
+ ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
2403
+ const link = document.createElement('a');
2404
+ link.download = 'toon-memory-graph.png';
2405
+ link.href = canvas.toDataURL('image/png');
2406
+ link.click();
2407
+ };
2408
+ img.src = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgData)));
2409
+ };
2410
+
2411
+ // Export SVG
2412
+ document.getElementById('exportSvg').onclick = () => {
2413
+ const svgEl = container.querySelector('svg');
2414
+ const svgData = new XMLSerializer().serializeToString(svgEl);
2415
+ const blob = new Blob([svgData], { type: 'image/svg+xml' });
2416
+ const link = document.createElement('a');
2417
+ link.download = 'toon-memory-graph.svg';
2418
+ link.href = URL.createObjectURL(blob);
2419
+ link.click();
2420
+ };
2421
+
2422
+ // Path toggle
2423
+ document.getElementById('pathToggle').onclick = () => {
2424
+ pathActive = !pathActive;
2425
+ document.getElementById('pathToggle').classList.toggle('active', pathActive);
2426
+ if (!pathActive) { pathStart = null; highlightPath(null); }
2427
+ document.getElementById('pathInfo').style.display = 'none';
2428
+ };
2429
+ function selectEntryGraph(entry) {
2430
+ selectedEntry = entry;
2431
+ renderEntries();
2432
+ showDetail(entry);
2433
+ graph.highlightNode(entry.id);
2434
+ graph.centerOn(entry.id);
2435
+ }
2436
+
2437
+ let clickTimer = null;
2438
+ node.on('click', (e, d) => {
2439
+ e.stopPropagation();
2440
+ if (pathActive) {
2441
+ if (!pathStart) {
2442
+ pathStart = d.id;
2443
+ document.getElementById('pathInfo').textContent = 'Click target node';
2444
+ document.getElementById('pathInfo').style.display = 'block';
2445
+ highlightPath(null);
2446
+ node.classed('path-start', false);
2447
+ node.filter(n => n.id === d.id).classed('path-start', true);
2448
+ } else {
2449
+ const path = findPath(pathStart, d.id);
2450
+ if (path) {
2451
+ const info = document.getElementById('pathInfo');
2452
+ info.innerHTML = 'Path: ' + path.join(' \u2192 ');
2453
+ info.style.display = 'block';
2454
+ highlightPath(path);
2455
+ centerOn(path[Math.floor(path.length / 2)]);
2456
+ } else {
2457
+ document.getElementById('pathInfo').textContent = 'No path found';
2458
+ document.getElementById('pathInfo').style.display = 'block';
2459
+ }
2460
+ pathStart = null;
2461
+ pathActive = false;
2462
+ document.getElementById('pathToggle').classList.remove('active');
2463
+ }
2464
+ return;
2465
+ }
2466
+ if (clickTimer) { clearTimeout(clickTimer); clickTimer = null; return; }
2467
+ clickTimer = setTimeout(() => {
2468
+ clickTimer = null;
2469
+ selectEntryGraph(d);
2470
+ }, 220);
2471
+ });
2472
+ node.on('dblclick', (e, d) => {
2473
+ e.stopPropagation();
2474
+ if (clickTimer) { clearTimeout(clickTimer); clickTimer = null; }
2475
+ selectEntry(d); hideTooltip();
2476
+ });
2477
+
2478
+ return { highlightNode, highlightSearch, centerOn, resize: () => {
2479
+ const w = container.clientWidth;
2480
+ const h = container.clientHeight;
2481
+ simulation.force('center', d3.forceCenter(w / 2, h / 2).strength(centerStrength));
2482
+ simulation.alpha(0.3).restart();
2483
+ }};
2484
+ })();
2485
+
2486
+ // --- Keyboard Shortcuts ---
2487
+ document.addEventListener('keydown', (e) => {
2488
+ if (e.target.tagName === 'INPUT') {
2489
+ if (e.key === 'Escape') { e.target.value = ''; searchQuery = ''; renderEntries(); if (graph.highlightSearch) graph.highlightSearch(); e.target.blur(); }
2490
+ return;
2491
+ }
2492
+ if (e.key === '/') { e.preventDefault(); document.getElementById('search').focus(); }
2493
+ if (e.key === 'Escape') { selectedEntry = null; renderEntries(); graph.highlightNode(null); switchTab('graph'); }
2494
+ if (e.key === '1') switchTab('graph');
2495
+ if (e.key === '2') switchTab('stats');
2496
+ if (e.key === '3') switchTab('timeline');
2497
+ if (e.key === '4') switchTab('detail');
2498
+ });
2499
+
2500
+ // --- Sidebar Resize ---
2501
+ (function() {
2502
+ const resizer = document.getElementById('sidebarResizer');
2503
+ let startX, startW;
2504
+ resizer.addEventListener('mousedown', (e) => {
2505
+ startX = e.clientX;
2506
+ startW = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--sidebar-w')) || 320;
2507
+ document.body.style.cursor = 'col-resize';
2508
+ document.body.style.userSelect = 'none';
2509
+ const onMove = (ev) => {
2510
+ const w = Math.max(160, Math.min(600, startW + ev.clientX - startX));
2511
+ document.documentElement.style.setProperty('--sidebar-w', w + 'px');
2512
+ };
2513
+ const onUp = () => {
2514
+ document.body.style.cursor = '';
2515
+ document.body.style.userSelect = '';
2516
+ document.removeEventListener('mousemove', onMove);
2517
+ document.removeEventListener('mouseup', onUp);
2518
+ };
2519
+ document.addEventListener('mousemove', onMove);
2520
+ document.addEventListener('mouseup', onUp);
2521
+ });
2522
+ })();
2523
+
2524
+ renderStats();
2525
+ renderTimeline();
2526
+ renderEntries();
2527
+
2528
+ document.getElementById('reloadBtn').addEventListener('click', () => location.reload());
2529
+ document.addEventListener('keydown', (e) => {
2530
+ if (e.key === 'r' && !e.metaKey && !e.ctrlKey && !e.target.closest('input,textarea')) location.reload();
2531
+ });
2532
+ </script>
2533
+ </body>
2534
+ </html>`;
2535
+ }
2536
+
2537
+ // src/viewer/index.ts
2538
+ import { createServer } from "http";
2539
+ function openBrowser(url) {
2540
+ const platform = process.platform;
2541
+ try {
2542
+ if (platform === "darwin") execSync(`open "${url}"`);
2543
+ else if (platform === "win32") execSync(`start "" "${url}"`);
2544
+ else execSync(`xdg-open "${url}" || sensible-browser "${url}" || x-www-browser "${url}"`, { stdio: "ignore" });
2545
+ } catch {
2546
+ console.log(`Open in browser: ${url}`);
2547
+ }
2548
+ }
2549
+ function viewer(portArg) {
2550
+ const PORT = parseInt(portArg || process.env.PORT || "3000", 10);
2551
+ let currentHtml = generateHtml(buildViewerData());
2552
+ const server = createServer((_req, res) => {
2553
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
2554
+ res.end(currentHtml);
2555
+ });
2556
+ server.listen(PORT, "127.0.0.1", () => {
2557
+ const url = `http://127.0.0.1:${PORT}`;
2558
+ const data = buildViewerData();
2559
+ console.log(`
2560
+ toon-memory viewer`);
2561
+ console.log(` Entries: ${data.totalEntries} | Edges: ${data.edges.length}`);
2562
+ console.log(` Serving at: ${url}`);
2563
+ console.log(` Press 'r' in terminal to reload | Ctrl+C to stop
2564
+ `);
2565
+ openBrowser(url);
2566
+ });
2567
+ if (process.stdin.isTTY) {
2568
+ process.stdin.setRawMode?.(true);
2569
+ process.stdin.resume();
2570
+ process.stdin.on("data", (buf) => {
2571
+ const key = buf.toString();
2572
+ if (key === "r" || key === "R") {
2573
+ const data = buildViewerData();
2574
+ currentHtml = generateHtml(data);
2575
+ console.log(` Reloaded: ${data.totalEntries} entries, ${data.edges.length} edges`);
2576
+ }
2577
+ if (key === "") process.exit(0);
2578
+ });
2579
+ }
2580
+ server.on("error", (err) => {
2581
+ if (err.code === "EADDRINUSE") {
2582
+ console.error(`Port ${PORT} already in use. Try: PORT=3001 toon-memory viewer`);
2583
+ } else {
2584
+ console.error(`Server error: ${err.message}`);
2585
+ }
2586
+ process.exit(1);
2587
+ });
2588
+ }
2589
+ function viewerExport() {
2590
+ const viewerData = buildViewerData();
2591
+ const html = generateHtml(viewerData);
2592
+ const projectRoot3 = process.cwd();
2593
+ const outDir = join10(projectRoot3, ".toon-memory", "viewer");
2594
+ mkdirSync10(outDir, { recursive: true });
2595
+ const outFile = join10(outDir, "index.html");
2596
+ writeFileSync11(outFile, html, "utf-8");
2597
+ console.log(`Viewer saved: ${outFile}`);
2598
+ console.log(`Entries: ${viewerData.totalEntries} | Edges: ${viewerData.edges.length}`);
2599
+ openBrowser(outFile);
2600
+ }
2601
+
1284
2602
  // src/cli/setup.ts
1285
2603
  var args = process.argv.slice(2);
1286
2604
  if (args[0] === "capture") {
@@ -1341,17 +2659,27 @@ if (args[0] === "watch") {
1341
2659
  watch(args);
1342
2660
  process.exit(0);
1343
2661
  }
1344
- if (args.length === 0) {
2662
+ if (args[0] === "viewer") {
2663
+ const portIdx = args.indexOf("--port");
2664
+ const port = portIdx !== -1 && args[portIdx + 1] ? args[portIdx + 1] : void 0;
2665
+ if (args.includes("--export")) {
2666
+ viewerExport();
2667
+ } else {
2668
+ viewer(port);
2669
+ }
2670
+ } else if (args.length === 0) {
1345
2671
  await interactiveInstall();
1346
2672
  process.exit(0);
1347
- }
1348
- console.log(`Unknown command: '${args[0]}'
2673
+ } else {
2674
+ console.log(`Unknown command: '${args[0]}'
1349
2675
  `);
1350
- printUsage();
1351
- process.exit(1);
2676
+ printUsage();
2677
+ process.exit(1);
2678
+ }
1352
2679
  function printUsage() {
1353
2680
  console.log(`Usage: toon-memory <command> [options]
1354
- Commands: init, status, stats, export, import, watch, uninstall, capture, upgrade, mcp
2681
+ Commands: init, status, stats, export, import, watch, viewer, uninstall, capture, upgrade, mcp
2682
+ viewer [--export] [--port <n>] \u2014 Start an HTTP server with the graph viewer (press 'r' to reload). --export saves static HTML.
1355
2683
  Init: toon-memory init [--agent <name> --agent <name>...] [--scope local|global]
1356
2684
  Without --agent: interactive agent and scope selector.
1357
2685
  With --agent: non-interactive installation (default: scope local).