toon-memory 3.1.0 → 3.3.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
@@ -19,6 +19,9 @@ Persistent memory for this project. Use it to avoid re-investigating things.
19
19
  1. Run memory_stats to see what's in memory.
20
20
  2. If the user asks something that might be in memory, run memory_recall BEFORE reading files.
21
21
 
22
+ ## When asked to see the memory graph
23
+ - Call memory_visualize() to open the interactive graph viewer inline.
24
+
22
25
  ## When making decisions
23
26
  - Before implementing a non-trivial change: memory_remember(category='decision')
24
27
  - When you resolve a complex bug: memory_remember(category='bug')
@@ -30,6 +33,7 @@ Persistent memory for this project. Use it to avoid re-investigating things.
30
33
  var OPENCODE_PASSIVE_INSTRUCTION = `# toon-memory
31
34
 
32
35
  Memory auto-injects via .opencode/instructions/memory-autoload.md; use memory_recall only as fallback.
36
+ When the user asks to see the memory graph, call memory_visualize().
33
37
  `;
34
38
 
35
39
  // src/cli/capture-toggle.ts
@@ -1392,6 +1396,1251 @@ function watch(args2) {
1392
1396
  });
1393
1397
  }
1394
1398
 
1399
+ // src/viewer/index.ts
1400
+ import { writeFileSync as writeFileSync11, mkdirSync as mkdirSync10 } from "fs";
1401
+ import { join as join10 } from "path";
1402
+ import { execSync } from "child_process";
1403
+
1404
+ // src/lib/lock.ts
1405
+ import { openSync, closeSync, writeFileSync as writeFileSync9, readFileSync as readFileSync11, unlinkSync as unlinkSync3, existsSync as existsSync11, statSync as statSync2, renameSync } from "fs";
1406
+ var STALE_MS = 15e3;
1407
+ var LOCK_TIMEOUT_MS = 1e4;
1408
+ function isAlive(pid) {
1409
+ if (!pid || pid <= 0) return false;
1410
+ try {
1411
+ process.kill(pid, 0);
1412
+ return true;
1413
+ } catch {
1414
+ return false;
1415
+ }
1416
+ }
1417
+ function tryAcquire(lockFile) {
1418
+ if (existsSync11(lockFile)) {
1419
+ const age = Date.now() - statSync2(lockFile).mtimeMs;
1420
+ let stale = age > STALE_MS;
1421
+ if (!stale) {
1422
+ try {
1423
+ const pid = parseInt(readFileSync11(lockFile, "utf-8").trim(), 10);
1424
+ if (!isAlive(pid)) stale = true;
1425
+ } catch {
1426
+ stale = true;
1427
+ }
1428
+ }
1429
+ if (stale) {
1430
+ try {
1431
+ unlinkSync3(lockFile);
1432
+ } catch {
1433
+ }
1434
+ } else {
1435
+ return false;
1436
+ }
1437
+ }
1438
+ try {
1439
+ const fd = openSync(lockFile, "wx");
1440
+ writeFileSync9(fd, String(process.pid));
1441
+ closeSync(fd);
1442
+ return true;
1443
+ } catch {
1444
+ return false;
1445
+ }
1446
+ }
1447
+ var held = /* @__PURE__ */ new Map();
1448
+ function withLockSync(file, fn) {
1449
+ const lockFile = `${file}.lock`;
1450
+ const depth = held.get(lockFile) ?? 0;
1451
+ if (depth > 0) {
1452
+ held.set(lockFile, depth + 1);
1453
+ try {
1454
+ fn();
1455
+ } finally {
1456
+ const d = (held.get(lockFile) ?? 0) - 1;
1457
+ if (d <= 0) held.delete(lockFile);
1458
+ else held.set(lockFile, d);
1459
+ }
1460
+ return;
1461
+ }
1462
+ const deadline = Date.now() + LOCK_TIMEOUT_MS;
1463
+ while (!tryAcquire(lockFile)) {
1464
+ if (Date.now() > deadline) throw new Error(`toon-memory lock timeout: ${file}`);
1465
+ const t = Date.now() + 10;
1466
+ while (Date.now() < t) {
1467
+ }
1468
+ }
1469
+ held.set(lockFile, 1);
1470
+ try {
1471
+ fn();
1472
+ } finally {
1473
+ const d = (held.get(lockFile) ?? 0) - 1;
1474
+ if (d <= 0) {
1475
+ held.delete(lockFile);
1476
+ try {
1477
+ unlinkSync3(lockFile);
1478
+ } catch {
1479
+ }
1480
+ } else {
1481
+ held.set(lockFile, d);
1482
+ }
1483
+ }
1484
+ }
1485
+ function readUnderLock(file, encoding = "utf-8") {
1486
+ let content = "";
1487
+ withLockSync(file, () => {
1488
+ content = readFileSync11(file, encoding);
1489
+ });
1490
+ return content;
1491
+ }
1492
+
1493
+ // src/mcp/config.ts
1494
+ import { readFileSync as readFileSync12, writeFileSync as writeFileSync10, existsSync as existsSync12, mkdirSync as mkdirSync9 } from "fs";
1495
+ import { join as join9 } from "path";
1496
+ var MEMORY_DIR3 = join9(process.cwd(), ".toon-memory", "memory");
1497
+ var MEMORY_FILE = join9(MEMORY_DIR3, "data.toon");
1498
+ var ARCHIVE_FILE = join9(MEMORY_DIR3, "archive.toon");
1499
+ var OBSERVATIONS_FILE = join9(MEMORY_DIR3, "observations.toon");
1500
+ var CONFIG_FILE = join9(MEMORY_DIR3, "config.json");
1501
+ var ALGORITHM = "aes-256-gcm";
1502
+ function loadConfig() {
1503
+ if (!existsSync12(CONFIG_FILE)) {
1504
+ return { encrypted: false };
1505
+ }
1506
+ try {
1507
+ return JSON.parse(readFileSync12(CONFIG_FILE, "utf-8"));
1508
+ } catch {
1509
+ return { encrypted: false };
1510
+ }
1511
+ }
1512
+ function getKey() {
1513
+ return process.env.TOON_MEMORY_KEY;
1514
+ }
1515
+ function ensureMemoryDir() {
1516
+ if (!existsSync12(MEMORY_DIR3)) mkdirSync9(MEMORY_DIR3, { recursive: true });
1517
+ }
1518
+ function ensureMemoryFile() {
1519
+ ensureMemoryDir();
1520
+ if (!existsSync12(MEMORY_FILE)) {
1521
+ writeFileSync10(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed|links|quality|confidence}:\n");
1522
+ }
1523
+ }
1524
+
1525
+ // src/mcp/crypto.ts
1526
+ import { randomBytes, createCipheriv, createDecipheriv } from "crypto";
1527
+ function decrypt(encryptedData, key) {
1528
+ const keyBuffer = Buffer.from(key, "hex");
1529
+ const parts = encryptedData.split(":");
1530
+ if (parts.length !== 3) {
1531
+ throw new Error("Invalid encrypted data format: expected iv:authTag:ciphertext");
1532
+ }
1533
+ const [ivHex, authTagHex, encrypted] = parts;
1534
+ const iv = Buffer.from(ivHex, "hex");
1535
+ const authTag = Buffer.from(authTagHex, "hex");
1536
+ const decipher = createDecipheriv(ALGORITHM, keyBuffer, iv);
1537
+ decipher.setAuthTag(authTag);
1538
+ let decrypted = decipher.update(encrypted, "hex", "utf8");
1539
+ decrypted += decipher.final("utf8");
1540
+ return decrypted;
1541
+ }
1542
+
1543
+ // src/mcp/memory-io.ts
1544
+ function readMemory() {
1545
+ ensureMemoryFile();
1546
+ const config = loadConfig();
1547
+ const data = readUnderLock(MEMORY_FILE);
1548
+ if (config.encrypted) {
1549
+ const key = getKey();
1550
+ if (!key) throw new Error("Encryption enabled but TOON_MEMORY_KEY is not set. Run 'npx toon-memory init' or set the env var.");
1551
+ return decrypt(data, key);
1552
+ }
1553
+ return data;
1554
+ }
1555
+
1556
+ // src/lib/graph.ts
1557
+ var entryLines = (data) => data.split("\n").filter(
1558
+ (l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")
1559
+ );
1560
+ function parseEntries(data) {
1561
+ const out = [];
1562
+ for (const line of entryLines(data)) {
1563
+ const parts = line.trim().split("|");
1564
+ if (parts.length < 7) continue;
1565
+ const [id, category, key, content, file, tags, date, ttl, accessedRaw, linksRaw] = parts;
1566
+ out.push({
1567
+ id,
1568
+ category,
1569
+ key,
1570
+ content,
1571
+ file: file || "",
1572
+ tags: (tags || "").split(";").map((t) => t.trim()).filter(Boolean),
1573
+ date: date || "",
1574
+ ttl: ttl || "",
1575
+ accessed: accessedRaw ? parseInt(accessedRaw) || 0 : 0,
1576
+ links: (linksRaw || "").split(/[\s;]+/).map((t) => t.trim()).filter(Boolean),
1577
+ lastAccessed: parts.length > 12 ? parts[12] || "" : ""
1578
+ });
1579
+ }
1580
+ return out;
1581
+ }
1582
+ function buildGraph(entries) {
1583
+ const byKey = /* @__PURE__ */ new Map();
1584
+ for (const e of entries) {
1585
+ if (!byKey.has(e.key)) byKey.set(e.key, e);
1586
+ }
1587
+ const adj = /* @__PURE__ */ new Map();
1588
+ const link = (a, b) => {
1589
+ if (a === b) return;
1590
+ if (!byKey.has(a) || !byKey.has(b)) return;
1591
+ if (!adj.has(a)) adj.set(a, /* @__PURE__ */ new Set());
1592
+ adj.get(a).add(b);
1593
+ if (!adj.has(b)) adj.set(b, /* @__PURE__ */ new Set());
1594
+ adj.get(b).add(a);
1595
+ };
1596
+ for (const e of entries) {
1597
+ for (const l of e.links) link(e.key, l);
1598
+ const refs = e.content.match(/\[\[([\w-]+)\]\]/g) || [];
1599
+ for (const r of refs) link(e.key, r.slice(2, -2));
1600
+ }
1601
+ if (entries.some((e) => e.tags.length > 0)) {
1602
+ for (let i = 0; i < entries.length; i++) {
1603
+ const ei = entries[i];
1604
+ if (ei.tags.length === 0) continue;
1605
+ const eTags = new Set(ei.tags);
1606
+ for (let j = i + 1; j < entries.length; j++) {
1607
+ const ej = entries[j];
1608
+ if (ej.tags.length === 0) continue;
1609
+ let shared = 0;
1610
+ for (const t of ej.tags) if (eTags.has(t)) shared++;
1611
+ if (shared >= 2) link(ei.key, ej.key);
1612
+ }
1613
+ }
1614
+ }
1615
+ const adjacency = /* @__PURE__ */ new Map();
1616
+ for (const [k, v] of adj) adjacency.set(k, [...v]);
1617
+ return { adjacency, byKey };
1618
+ }
1619
+
1620
+ // src/viewer/data.ts
1621
+ function buildViewerData() {
1622
+ const data = readMemory();
1623
+ const entries = parseEntries(data);
1624
+ if (entries.length === 0) {
1625
+ return { nodes: [], edges: [], categories: {}, tagCounts: {}, totalEntries: 0 };
1626
+ }
1627
+ const graph = buildGraph(entries);
1628
+ const nodes = entries.map((e) => ({
1629
+ id: e.key,
1630
+ category: e.category,
1631
+ content: e.content.substring(0, 120),
1632
+ tags: e.tags,
1633
+ quality: e.accessed,
1634
+ accessCount: e.accessed,
1635
+ date: e.date,
1636
+ file: e.file,
1637
+ links: e.links,
1638
+ ttl: e.ttl,
1639
+ lastAccessed: e.lastAccessed
1640
+ }));
1641
+ const edges = [];
1642
+ const seen = /* @__PURE__ */ new Set();
1643
+ for (const [key, neighbors] of graph.adjacency) {
1644
+ for (const n of neighbors) {
1645
+ const pair = [key, n].sort().join("::");
1646
+ if (!seen.has(pair)) {
1647
+ seen.add(pair);
1648
+ edges.push({ source: key, target: n });
1649
+ }
1650
+ }
1651
+ }
1652
+ const categories = {};
1653
+ const tagCounts = {};
1654
+ for (const e of entries) {
1655
+ categories[e.category] = (categories[e.category] || 0) + 1;
1656
+ for (const t of e.tags) tagCounts[t] = (tagCounts[t] || 0) + 1;
1657
+ }
1658
+ return { nodes, edges, categories, tagCounts, totalEntries: entries.length };
1659
+ }
1660
+
1661
+ // src/viewer/html.ts
1662
+ import { readFileSync as readFileSync13 } from "fs";
1663
+ import { resolve, dirname as dirname8 } from "path";
1664
+ import { fileURLToPath } from "url";
1665
+ var d3Src = (() => {
1666
+ try {
1667
+ const dir = dirname8(fileURLToPath(import.meta.url));
1668
+ return readFileSync13(resolve(dir, "../src/viewer/d3.v7.min.js"), "utf-8");
1669
+ } catch {
1670
+ try {
1671
+ const dir = dirname8(fileURLToPath(import.meta.url));
1672
+ return readFileSync13(resolve(dir, "d3.v7.min.js"), "utf-8");
1673
+ } catch {
1674
+ return null;
1675
+ }
1676
+ }
1677
+ })();
1678
+ function generateHtml(viewerData) {
1679
+ const jsonData = JSON.stringify(viewerData);
1680
+ const d3Tag = d3Src ? `<script>${d3Src}</script>` : `<script src="https://d3js.org/d3.v7.min.js"></script>`;
1681
+ return `<!DOCTYPE html>
1682
+ <html lang="en">
1683
+ <head>
1684
+ <meta charset="UTF-8">
1685
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1686
+ <title>toon-memory viewer</title>
1687
+ <script>window.__MCP_UI__=window.__MCP_UI__||{invoke:()=>Promise.resolve({})}</script>
1688
+ ${d3Tag}
1689
+ <style>
1690
+ *{box-sizing:border-box;margin:0;padding:0}
1691
+ :root{
1692
+ --bg:#0a0a0f;--bg2:#12121a;--bg3:#1a1a26;--border:#2a2a3a;
1693
+ --text:#e2e2ee;--muted:#8888a0;--brand:#a78bfa;--brand2:#c084fc;
1694
+ --green:#22c55e;--red:#ef4444;--blue:#3b82f6;--amber:#f59e0b;
1695
+ --pink:#ec4899;--cyan:#06b6d4;
1696
+ }
1697
+ html,body{height:100%;font-family:system-ui,-apple-system,sans-serif;background:var(--bg);color:var(--text);overflow:hidden}
1698
+ .app{display:grid;grid-template-rows:auto 1fr;height:100%}
1699
+ header{display:flex;align-items:center;justify-content:space-between;padding:0.75rem 1.5rem;border-bottom:1px solid var(--border);background:var(--bg2)}
1700
+ 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}
1701
+ header .meta{display:flex;gap:1rem;font-size:0.8rem;color:var(--muted)}
1702
+ header .meta span{display:flex;align-items:center;gap:0.3rem}
1703
+ .main{display:grid;grid-template-columns:var(--sidebar-w,320px) 1fr;overflow:hidden;position:relative}
1704
+ .sidebar{display:flex;flex-direction:column;border-right:1px solid var(--border);overflow:hidden}
1705
+ .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}
1706
+ .sidebar-resizer:hover,.sidebar-resizer:active{background:var(--brand)}
1707
+ .sidebar-header{padding:0.75rem 1rem;border-bottom:1px solid var(--border);background:var(--bg2)}
1708
+ .sidebar-header h2{font-size:0.85rem;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:var(--muted);margin-bottom:0.5rem}
1709
+ .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}
1710
+ .search-box:focus{border-color:var(--brand)}
1711
+ .filter-row{display:flex;gap:0.4rem;margin-top:0.5rem;flex-wrap:wrap}
1712
+ .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}
1713
+ .filter-btn:hover,.filter-btn.active{border-color:var(--brand);color:var(--brand);background:rgba(167,139,250,0.1)}
1714
+ .entries-list{flex:1;overflow-y:auto;padding:0.5rem}
1715
+ .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}
1716
+ .entry-item:hover{border-color:var(--brand);background:rgba(167,139,250,0.05)}
1717
+ .entry-item.selected{border-color:var(--brand);background:rgba(167,139,250,0.1)}
1718
+ .entry-cat{font-size:0.65rem;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;margin-bottom:0.2rem}
1719
+ .entry-cat.decision{color:var(--brand)}
1720
+ .entry-cat.bug{color:var(--red)}
1721
+ .entry-cat.pattern{color:var(--green)}
1722
+ .entry-cat.knowledge{color:var(--cyan)}
1723
+ .entry-cat.architecture{color:var(--amber)}
1724
+ .entry-key{font-size:0.85rem;font-weight:600;margin-bottom:0.15rem}
1725
+ .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}
1726
+ .entry-tags{display:flex;gap:0.25rem;margin-top:0.3rem;flex-wrap:wrap}
1727
+ .entry-tag{font-size:0.6rem;padding:0.1em 0.35rem;border-radius:3px;background:var(--bg3);color:var(--muted);font-family:monospace}
1728
+ .viewer-area{display:flex;flex-direction:column;overflow:hidden}
1729
+ .tabs{display:flex;border-bottom:1px solid var(--border);background:var(--bg2);padding:0 1rem}
1730
+ .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}
1731
+ .tab:hover{color:var(--text)}
1732
+ .tab.active{color:var(--brand);border-bottom-color:var(--brand)}
1733
+ .tab-content{flex:1;overflow:hidden;position:relative}
1734
+ .tab-panel{display:none;width:100%;height:100%;overflow:auto}
1735
+ .tab-panel.active{display:block}
1736
+ .graph-container{width:100%;height:100%;min-height:300px;background:var(--bg);position:relative}
1737
+ .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}
1738
+ .graph-container svg{width:100%;height:100%;position:relative;z-index:1}
1739
+ .node-circle{cursor:pointer;transition:r 0.2s ease,opacity 0.2s ease,filter 0.2s ease,stroke 0.2s ease}
1740
+ .node-circle:hover{filter:brightness(1.3) drop-shadow(0 0 6px color-mix(in srgb,currentColor 60%,transparent))}
1741
+ .node-circle.glow{filter:drop-shadow(0 0 12px var(--brand)) brightness(1.5)}
1742
+ .node-circle.selected{stroke:var(--brand);stroke-width:3;filter:drop-shadow(0 0 14px var(--brand)) brightness(1.3)}
1743
+ .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}
1744
+ .link{stroke:var(--border);stroke-opacity:0.4;transition:all 0.2s ease;cursor:pointer}
1745
+ .link:hover{stroke-opacity:0.9;stroke-width:3}
1746
+ .link.highlighted{stroke:var(--brand);stroke-opacity:0.9;stroke-width:2.5}
1747
+ .link.faded{stroke-opacity:0.04}
1748
+ .node-ring{fill:none;stroke-width:2;opacity:0;transition:opacity 0.3s ease,r 0.3s ease}
1749
+ .node-ring.visible{opacity:0.6}
1750
+ .stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:1rem;padding:1.5rem}
1751
+ .stat-card{background:var(--bg2);border:1px solid var(--border);border-radius:12px;padding:1.25rem}
1752
+ .stat-card h3{font-size:0.8rem;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:var(--muted);margin-bottom:0.75rem}
1753
+ .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}
1754
+ .bar-chart{display:flex;flex-direction:column;gap:0.4rem}
1755
+ .bar-row{display:flex;align-items:center;gap:0.5rem}
1756
+ .bar-label{font-size:0.75rem;color:var(--muted);width:80px;text-align:right;flex-shrink:0}
1757
+ .bar-track{flex:1;height:20px;background:var(--bg3);border-radius:4px;overflow:hidden}
1758
+ .bar-fill{height:100%;border-radius:4px;transition:width 0.6s cubic-bezier(0.16,1,0.3,1)}
1759
+ .bar-value{font-size:0.7rem;color:var(--muted);width:30px}
1760
+ .tag-cloud{display:flex;flex-wrap:wrap;gap:0.4rem}
1761
+ .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}
1762
+ .tag-pill:hover{border-color:var(--brand);color:var(--brand)}
1763
+ .detail-panel{padding:1.5rem;max-width:700px}
1764
+ .detail-panel h2{font-size:1.2rem;font-weight:700;margin-bottom:0.5rem}
1765
+ .detail-panel .detail-cat{font-size:0.75rem;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;margin-bottom:1rem}
1766
+ .detail-field{margin-bottom:1rem}
1767
+ .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}
1768
+ .detail-field .value{font-size:0.9rem;line-height:1.6}
1769
+ .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}
1770
+ .detail-links{display:flex;gap:0.4rem;flex-wrap:wrap}
1771
+ .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}
1772
+ .detail-link:hover{border-color:var(--brand);background:rgba(167,139,250,0.1)}
1773
+ .empty-detail{display:flex;align-items:center;justify-content:center;height:100%;color:var(--muted);font-size:0.9rem}
1774
+ .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}
1775
+ .legend-item{display:flex;align-items:center;gap:0.4rem;margin-bottom:0.25rem}
1776
+ .legend-dot{width:10px;height:10px;border-radius:50%}
1777
+ .graph-controls{position:absolute;top:1rem;right:1rem;display:flex;gap:0.4rem;z-index:10}
1778
+ .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}
1779
+ .graph-btn:hover{border-color:var(--brand);color:var(--brand)}
1780
+ .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)}
1781
+ .tooltip .tt-cat{font-size:0.6rem;font-weight:600;text-transform:uppercase;margin-bottom:0.2rem}
1782
+ .tooltip .tt-key{font-weight:600;margin-bottom:0.2rem}
1783
+ .tooltip .tt-content{color:var(--muted);line-height:1.4;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden}
1784
+ .tooltip .tt-score{margin-top:0.3rem;font-size:0.65rem;color:var(--brand)}
1785
+ .tooltip .tt-edge{font-size:0.65rem;color:var(--muted);margin-top:0.3rem;padding-top:0.3rem;border-top:1px solid var(--border)}
1786
+ .timeline-container{padding:1.5rem;overflow-y:auto;height:100%}
1787
+ .timeline-header{font-size:1rem;font-weight:700;margin-bottom:1rem;color:var(--text)}
1788
+ .timeline-track{position:relative;padding-left:2rem}
1789
+ .timeline-line{position:absolute;left:0.5rem;top:0;bottom:0;width:2px;background:var(--border)}
1790
+ .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}
1791
+ .timeline-entry:hover{border-color:var(--brand)}
1792
+ .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)}
1793
+ .timeline-entry .tl-date{font-size:0.65rem;color:var(--muted);margin-bottom:0.2rem}
1794
+ .timeline-entry .tl-cat{font-size:0.6rem;font-weight:600;text-transform:uppercase}
1795
+ .timeline-entry .tl-key{font-size:0.85rem;font-weight:600}
1796
+ .timeline-entry .tl-content{font-size:0.75rem;color:var(--muted);margin-top:0.2rem}
1797
+ .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}
1798
+ .export-btn:hover{border-color:var(--brand);color:var(--brand)}
1799
+ .export-bar{display:flex;gap:0.4rem}
1800
+ .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}
1801
+ .theme-toggle:hover{border-color:var(--brand);color:var(--brand)}
1802
+ .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}
1803
+ .reload-btn:hover{border-color:var(--brand);color:var(--brand)}
1804
+ .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}
1805
+ .minimap svg{width:100%;height:100%;display:block}
1806
+ .minimap-viewport{fill:rgba(167,139,250,0.15);stroke:var(--brand);stroke-width:1.5}
1807
+ .graph-right{position:absolute;bottom:1rem;right:1rem;z-index:10;display:flex;flex-direction:column;align-items:flex-end;gap:0.4rem}
1808
+ .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}
1809
+ .physics-panel h4{font-size:0.7rem;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:var(--muted);margin-bottom:0.5rem}
1810
+ .graph-toolbar{position:absolute;top:1rem;left:0.5rem;display:flex;gap:0.4rem;z-index:11}
1811
+ .physics-row{display:flex;align-items:center;gap:0.5rem;margin-bottom:0.4rem}
1812
+ .physics-row label{font-size:0.65rem;color:var(--muted);width:60px;flex-shrink:0}
1813
+ .physics-row input[type="range"]{flex:1;height:4px;-webkit-appearance:none;background:var(--bg3);border-radius:2px;outline:none}
1814
+ .physics-row input[type="range"]::-webkit-slider-thumb{-webkit-appearance:none;width:12px;height:12px;border-radius:50%;background:var(--brand);cursor:pointer}
1815
+ .physics-row .physics-val{font-size:0.6rem;color:var(--muted);width:30px;text-align:right}
1816
+ .node-circle.search-match{filter:drop-shadow(0 0 10px var(--brand)) brightness(1.4);animation:searchPulse 1.5s ease-in-out infinite}
1817
+ @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)}}
1818
+ .path-btn.active{background:var(--brand);color:#fff;border-color:var(--brand)}
1819
+ .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}
1820
+ .node-circle.path-start{stroke:var(--green);stroke-width:3;filter:drop-shadow(0 0 12px var(--green))}
1821
+ .node-circle.path-end{stroke:var(--red);stroke-width:3;filter:drop-shadow(0 0 12px var(--red))}
1822
+ .node-circle.path-node{stroke:var(--brand);stroke-width:2.5;animation:pathNodePulse 1.2s ease-in-out infinite}
1823
+ @keyframes pathNodePulse{0%,100%{filter:drop-shadow(0 0 6px var(--brand))}50%{filter:drop-shadow(0 0 14px var(--brand))}}
1824
+ .link.path-edge{stroke:var(--brand);stroke-opacity:0.9;stroke-width:3}
1825
+ .light{--bg:#f4f4f9;--bg2:#ffffff;--bg3:#e8e8f0;--border:#c8c8d8;--text:#1a1a2e;--muted:#666680;--brand:#7c3aed;--brand2:#9333ea}
1826
+ .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)}
1827
+ .light .timeline-entry{background:#fff}
1828
+ .light .graph-btn,.light .export-btn,.light .theme-toggle{background:#fff}
1829
+ .light .minimap{box-shadow:0 4px 16px rgba(0,0,0,0.08)}
1830
+ @media(max-width:768px){.main{grid-template-columns:1fr}.sidebar{display:none}}
1831
+ </style>
1832
+ </head>
1833
+ <body>
1834
+ <div class="app">
1835
+ <header>
1836
+ <h1>toon-memory viewer</h1>
1837
+ <div class="meta">
1838
+ <span id="totalCount"></span>
1839
+ <span id="edgeCount"></span>
1840
+ <span id="categoryCount"></span>
1841
+ <button class="theme-toggle" id="themeToggle" title="Toggle theme">\u2600</button>
1842
+ <button class="reload-btn" id="reloadBtn" title="Reload (r)">\u21BB</button>
1843
+ </div>
1844
+ </header>
1845
+ <div class="main">
1846
+ <div class="sidebar">
1847
+ <div class="sidebar-header">
1848
+ <h2>Entries</h2>
1849
+ <input type="text" class="search-box" id="search" placeholder="Search entries... (/)">
1850
+ <div class="filter-row" id="filters"></div>
1851
+ </div>
1852
+ <div class="entries-list" id="entriesList"></div>
1853
+ </div>
1854
+ <div class="sidebar-resizer" id="sidebarResizer"></div>
1855
+ <div class="viewer-area">
1856
+ <div class="tabs">
1857
+ <div class="tab active" data-tab="graph">Graph</div>
1858
+ <div class="tab" data-tab="stats">Stats</div>
1859
+ <div class="tab" data-tab="timeline">Timeline</div>
1860
+ <div class="tab" data-tab="detail">Detail</div>
1861
+ </div>
1862
+ <div class="tab-content">
1863
+ <div class="tab-panel active" id="panel-graph">
1864
+ <div class="graph-container" id="graphContainer">
1865
+ <div class="graph-legend" id="legend"></div>
1866
+ <div class="graph-right">
1867
+ <div class="export-bar">
1868
+ <button class="export-btn" id="exportPng">PNG</button>
1869
+ <button class="export-btn" id="exportSvg">SVG</button>
1870
+ </div>
1871
+ <div class="minimap" id="minimap"><svg id="minimapSvg"></svg></div>
1872
+ </div>
1873
+ <div class="graph-controls">
1874
+ <button class="graph-btn" id="zoomIn" title="Zoom in (+)">+</button>
1875
+ <button class="graph-btn" id="zoomOut" title="Zoom out (-)">\u2212</button>
1876
+ <button class="graph-btn" id="zoomReset" title="Reset (0)">\u27F2</button>
1877
+ </div>
1878
+ <div class="graph-toolbar">
1879
+ <button class="graph-btn" id="physicsToggle" title="Physics controls">\u2699</button>
1880
+ <button class="graph-btn path-btn" id="pathToggle" title="Find path between two nodes">\u21FF</button>
1881
+ </div>
1882
+ <div class="physics-panel" id="physicsPanel" style="display:none">
1883
+ <h4>Graph Physics</h4>
1884
+ <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>
1885
+ <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>
1886
+ <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>
1887
+ </div>
1888
+ <div class="path-info" id="pathInfo"></div>
1889
+ </div>
1890
+ </div>
1891
+ <div class="tab-panel" id="panel-stats">
1892
+ <div class="stats-grid" id="statsGrid"></div>
1893
+ </div>
1894
+ <div class="tab-panel" id="panel-timeline">
1895
+ <div class="timeline-container" id="timelineContainer"></div>
1896
+ </div>
1897
+ <div class="tab-panel" id="panel-detail">
1898
+ <div class="detail-panel" id="detailPanel">
1899
+ <div class="empty-detail">Select an entry from the sidebar or click a node in the graph</div>
1900
+ </div>
1901
+ </div>
1902
+ </div>
1903
+ </div>
1904
+ </div>
1905
+ </div>
1906
+ <div class="tooltip" id="tooltip" style="display:none"></div>
1907
+ <script>
1908
+ const DATA = ${jsonData};
1909
+
1910
+ const COLORS = {
1911
+ decision: '#a78bfa', bug: '#ef4444', pattern: '#22c55e',
1912
+ knowledge: '#06b6d4', architecture: '#f59e0b'
1913
+ };
1914
+
1915
+ let selectedEntry = null;
1916
+ let activeFilter = null;
1917
+ let searchQuery = '';
1918
+
1919
+ // --- Theme Toggle ---
1920
+ const themeToggle = document.getElementById('themeToggle');
1921
+ const savedTheme = localStorage.getItem('toon-viewer-theme') || 'dark';
1922
+ if (savedTheme === 'light') { document.documentElement.classList.add('light'); themeToggle.textContent = '\u263E'; }
1923
+ themeToggle.addEventListener('click', () => {
1924
+ document.documentElement.classList.toggle('light');
1925
+ const isLight = document.documentElement.classList.contains('light');
1926
+ themeToggle.textContent = isLight ? '\u263E' : '\u2600';
1927
+ localStorage.setItem('toon-viewer-theme', isLight ? 'light' : 'dark');
1928
+ });
1929
+
1930
+ // --- Tooltip ---
1931
+ const tooltip = document.getElementById('tooltip');
1932
+ function showTooltip(e, d) {
1933
+ const score = d.quality || 0;
1934
+ tooltip.innerHTML =
1935
+ '<div class="tt-cat" style="color:' + (COLORS[d.category] || 'var(--muted)') + '">' + d.category + '</div>' +
1936
+ '<div class="tt-key">' + escHtml(d.id) + '</div>' +
1937
+ '<div class="tt-content">' + escHtml(d.content) + '</div>' +
1938
+ '<div class="tt-score">Quality: ' + score.toFixed(2) + ' | Access: ' + (d.accessCount || 0) + '</div>';
1939
+ tooltip.style.display = 'block';
1940
+ positionTooltip(e);
1941
+ }
1942
+ function positionTooltip(e) {
1943
+ const x = e.clientX + 12;
1944
+ const y = e.clientY + 12;
1945
+ const rect = tooltip.getBoundingClientRect();
1946
+ tooltip.style.left = (x + rect.width > window.innerWidth ? e.clientX - rect.width - 8 : x) + 'px';
1947
+ tooltip.style.top = (y + rect.height > window.innerHeight ? e.clientY - rect.height - 8 : y) + 'px';
1948
+ }
1949
+ function hideTooltip() { tooltip.style.display = 'none'; }
1950
+ document.addEventListener('mousemove', (e) => { if (tooltip.style.display === 'block') positionTooltip(e); });
1951
+
1952
+ // --- Header ---
1953
+ document.getElementById('totalCount').textContent = DATA.totalEntries + ' entries';
1954
+ document.getElementById('edgeCount').textContent = DATA.edges.length + ' edges';
1955
+ document.getElementById('categoryCount').textContent = Object.keys(DATA.categories).length + ' categories';
1956
+
1957
+ // --- Tabs ---
1958
+ document.querySelectorAll('.tab').forEach(tab => {
1959
+ tab.addEventListener('click', () => {
1960
+ document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
1961
+ document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
1962
+ tab.classList.add('active');
1963
+ document.getElementById('panel-' + tab.dataset.tab).classList.add('active');
1964
+ if (tab.dataset.tab === 'graph') setTimeout(() => graph.resize(), 50);
1965
+ });
1966
+ });
1967
+
1968
+ function switchTab(name) {
1969
+ document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
1970
+ document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
1971
+ document.querySelector('[data-tab="' + name + '"]').classList.add('active');
1972
+ document.getElementById('panel-' + name).classList.add('active');
1973
+ }
1974
+
1975
+ // --- Filters ---
1976
+ const filterContainer = document.getElementById('filters');
1977
+ const allBtn = document.createElement('button');
1978
+ allBtn.className = 'filter-btn active';
1979
+ allBtn.textContent = 'All';
1980
+ allBtn.onclick = () => setFilter(null);
1981
+ filterContainer.appendChild(allBtn);
1982
+ Object.keys(DATA.categories).sort().forEach(cat => {
1983
+ const btn = document.createElement('button');
1984
+ btn.className = 'filter-btn';
1985
+ btn.textContent = cat;
1986
+ btn.dataset.cat = cat;
1987
+ btn.onclick = () => setFilter(cat);
1988
+ filterContainer.appendChild(btn);
1989
+ });
1990
+
1991
+ function setFilter(cat) {
1992
+ activeFilter = cat;
1993
+ document.querySelectorAll('.filter-btn').forEach(b => {
1994
+ b.classList.toggle('active', cat === null ? !b.dataset.cat : b.dataset.cat === cat);
1995
+ });
1996
+ renderEntries();
1997
+ if (graph.highlightSearch) graph.highlightSearch();
1998
+ }
1999
+
2000
+ // --- Search ---
2001
+ document.getElementById('search').addEventListener('input', (e) => {
2002
+ searchQuery = e.target.value.toLowerCase();
2003
+ renderEntries();
2004
+ if (graph.highlightSearch) graph.highlightSearch();
2005
+ if (searchQuery && graph.centerOn) {
2006
+ const first = DATA.nodes.find(n => n.id.toLowerCase().includes(searchQuery) || n.content.toLowerCase().includes(searchQuery) || n.tags.some(t => t.toLowerCase().includes(searchQuery)));
2007
+ if (first) graph.centerOn(first.id);
2008
+ }
2009
+ });
2010
+
2011
+ // --- Entries List ---
2012
+ function renderEntries() {
2013
+ const q = searchQuery;
2014
+ const list = document.getElementById('entriesList');
2015
+ list.innerHTML = '';
2016
+ DATA.nodes
2017
+ .filter(e => !activeFilter || e.category === activeFilter)
2018
+ .filter(e => !q || e.id.toLowerCase().includes(q) || e.content.toLowerCase().includes(q) || e.tags.some(t => t.toLowerCase().includes(q)))
2019
+ .forEach(e => {
2020
+ const div = document.createElement('div');
2021
+ div.className = 'entry-item' + (selectedEntry && selectedEntry.id === e.id ? ' selected' : '');
2022
+ div.innerHTML =
2023
+ '<div class="entry-cat ' + e.category + '">' + e.category + '</div>' +
2024
+ '<div class="entry-key">' + escHtml(e.id) + '</div>' +
2025
+ '<div class="entry-preview">' + escHtml(e.content) + '</div>' +
2026
+ (e.tags.length ? '<div class="entry-tags">' + e.tags.map(t => '<span class="entry-tag">' + escHtml(t) + '</span>').join('') + '</div>' : '');
2027
+ div.onclick = () => selectEntry(e);
2028
+ list.appendChild(div);
2029
+ });
2030
+ }
2031
+
2032
+ function escHtml(s) { return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }
2033
+
2034
+ // --- Entry Selection ---
2035
+ function selectEntry(entry) {
2036
+ selectedEntry = entry;
2037
+ renderEntries();
2038
+ showDetail(entry);
2039
+ graph.highlightNode(entry.id);
2040
+ graph.centerOn(entry.id);
2041
+ switchTab('detail');
2042
+ }
2043
+
2044
+ function showDetail(e) {
2045
+ const panel = document.getElementById('detailPanel');
2046
+ const linkedNodes = DATA.edges
2047
+ .filter(ed => (typeof ed.source === 'object' ? ed.source.id : ed.source) === e.id || (typeof ed.target === 'object' ? ed.target.id : ed.target) === e.id)
2048
+ .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));
2049
+
2050
+ panel.innerHTML =
2051
+ '<div class="detail-cat" style="color:' + (COLORS[e.category] || 'var(--muted)') + '">' + e.category + '</div>' +
2052
+ '<h2>' + escHtml(e.id) + '</h2>' +
2053
+ '<div class="detail-field"><label>Content</label><span class="value mono">' + escHtml(e.content) + '</span></div>' +
2054
+ (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>' : '') +
2055
+ (e.date ? '<div class="detail-field"><label>Date</label><span class="value">' + e.date + '</span></div>' : '') +
2056
+ '<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>' +
2057
+ '<div class="detail-field"><label>Access Count</label><span class="value">' + (e.accessCount || 0) + '</span></div>' +
2058
+ (e.ttl ? '<div class="detail-field"><label>TTL</label><span class="value">' + e.ttl + '</span></div>' : '') +
2059
+ (e.lastAccessed ? '<div class="detail-field"><label>Last Accessed</label><span class="value">' + e.lastAccessed + '</span></div>' : '') +
2060
+ (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>' : '') +
2061
+ (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>' : '');
2062
+ }
2063
+
2064
+ window.selectEntryById = function(id) {
2065
+ const e = DATA.nodes.find(n => n.id === id);
2066
+ if (e) selectEntry(e);
2067
+ };
2068
+
2069
+ // --- Stats ---
2070
+ function renderStats() {
2071
+ const grid = document.getElementById('statsGrid');
2072
+ const catEntries = Object.entries(DATA.categories).sort((a,b) => b[1] - a[1]);
2073
+ const maxCat = Math.max(...catEntries.map(c => c[1]));
2074
+ const topTags = Object.entries(DATA.tagCounts).sort((a,b) => b[1] - a[1]).slice(0, 20);
2075
+ const maxTag = Math.max(...topTags.map(t => t[1]));
2076
+ const avgQuality = DATA.nodes.reduce((s, n) => s + (n.quality || 0), 0) / DATA.nodes.length;
2077
+ const maxAccess = Math.max(...DATA.nodes.map(n => n.accessCount || 0));
2078
+
2079
+ grid.innerHTML =
2080
+ '<div class="stat-card"><h3>Total Entries</h3><div class="stat-big">' + DATA.totalEntries + '</div></div>' +
2081
+ '<div class="stat-card"><h3>Graph Edges</h3><div class="stat-big">' + DATA.edges.length + '</div></div>' +
2082
+ '<div class="stat-card"><h3>Avg Quality</h3><div class="stat-big">' + avgQuality.toFixed(2) + '</div></div>' +
2083
+ '<div class="stat-card"><h3>Max Access</h3><div class="stat-big">' + maxAccess + '</div></div>' +
2084
+ '<div class="stat-card"><h3>Categories</h3><div class="bar-chart">' +
2085
+ catEntries.map(([cat, count]) =>
2086
+ '<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>'
2087
+ ).join('') +
2088
+ '</div></div>' +
2089
+ '<div class="stat-card"><h3>Top Tags</h3><div class="tag-cloud">' +
2090
+ topTags.map(([tag, count]) =>
2091
+ '<span class="tag-pill">' + escHtml(tag) + ' <small>(' + count + ')</small></span>'
2092
+ ).join('') +
2093
+ '</div></div>';
2094
+ }
2095
+
2096
+ function renderTimeline() {
2097
+ const container = document.getElementById('timelineContainer');
2098
+ const sorted = [...DATA.nodes].sort((a, b) => (b.date || '').localeCompare(a.date || ''));
2099
+ const grouped = {};
2100
+ sorted.forEach(e => {
2101
+ const d = e.date || 'unknown';
2102
+ if (!grouped[d]) grouped[d] = [];
2103
+ grouped[d].push(e);
2104
+ });
2105
+
2106
+ let html = '<div class="timeline-header">Timeline (' + DATA.totalEntries + ' entries)</div><div class="timeline-track"><div class="timeline-line"></div>';
2107
+ for (const [date, entries] of Object.entries(grouped)) {
2108
+ for (const e of entries) {
2109
+ html += '<div class="timeline-entry" onclick="selectEntryById(\\'' + e.id + '\\')" style="border-left:3px solid ' + (COLORS[e.category] || 'var(--border)') + '">' +
2110
+ '<div class="tl-date">' + escHtml(date) + '</div>' +
2111
+ '<div class="tl-cat" style="color:' + (COLORS[e.category] || 'var(--muted)') + '">' + e.category + '</div>' +
2112
+ '<div class="tl-key">' + escHtml(e.id) + '</div>' +
2113
+ '<div class="tl-content">' + escHtml(e.content.substring(0, 100)) + '</div>' +
2114
+ '</div>';
2115
+ }
2116
+ }
2117
+ html += '</div>';
2118
+ container.innerHTML = html;
2119
+ }
2120
+
2121
+ // --- Graph ---
2122
+ const graph = (function() {
2123
+ const container = document.getElementById('graphContainer');
2124
+ let _impl = null;
2125
+ const safe = (name, ...args) => { if (_impl && _impl[name]) return _impl[name](...args); };
2126
+ const initGraph = () => {
2127
+ const width = Math.max(container.clientWidth, 400);
2128
+ const height = Math.max(container.clientHeight, 300);
2129
+ const svg = d3.select(container).append('svg').attr('width', '100%').attr('height', '100%');
2130
+
2131
+ const defs = svg.append('defs');
2132
+ const filter = defs.append('filter').attr('id', 'glow').attr('x', '-50%').attr('y', '-50%').attr('width', '200%').attr('height', '200%');
2133
+ filter.append('feGaussianBlur').attr('stdDeviation', '4').attr('result', 'blur');
2134
+ filter.append('feMerge').selectAll('feMergeNode').data(['blur', 'SourceGraphic']).join('feMergeNode').attr('in', d => d);
2135
+
2136
+ const g = svg.append('g');
2137
+ let currentTransform = d3.zoomIdentity;
2138
+ const zoom = d3.zoom().scaleExtent([0.1, 4]).on('zoom', e => { g.attr('transform', e.transform); currentTransform = e.transform; updateMinimap(); });
2139
+ svg.call(zoom);
2140
+
2141
+ function nodeRadius(d) { return 4 + Math.min((d.accessCount || 0) * 0.8, 8); }
2142
+
2143
+ const connectionCount = new Map();
2144
+ DATA.edges.forEach(e => {
2145
+ const s = typeof e.source === 'object' ? e.source.id : e.source;
2146
+ const t = typeof e.target === 'object' ? e.target.id : e.target;
2147
+ connectionCount.set(s, (connectionCount.get(s) || 0) + 1);
2148
+ connectionCount.set(t, (connectionCount.get(t) || 0) + 1);
2149
+ });
2150
+ function edgeWidth(d) {
2151
+ const s = typeof d.source === 'object' ? d.source.id : d.source;
2152
+ const t = typeof d.target === 'object' ? d.target.id : d.target;
2153
+ const shared = Math.min(connectionCount.get(s) || 1, connectionCount.get(t) || 1);
2154
+ return 0.5 + Math.min(shared * 0.3, 3);
2155
+ }
2156
+
2157
+ function getSharedTags(a, b) {
2158
+ const na = nodeMap.get(a), nb = nodeMap.get(b);
2159
+ if (!na || !nb || !na.tags || !nb.tags) return [];
2160
+ return na.tags.filter(t => nb.tags.includes(t));
2161
+ }
2162
+
2163
+ let chargeStrength = -120;
2164
+ let linkDistance = 70;
2165
+ let centerStrength = 0.05;
2166
+
2167
+ const nodeMap = new Map(DATA.nodes.map(n => [n.id, n]));
2168
+ const simulation = d3.forceSimulation(DATA.nodes)
2169
+ .force('link', d3.forceLink(DATA.edges).id(d => d.id).distance(linkDistance).strength(0.5))
2170
+ .force('charge', d3.forceManyBody().strength(chargeStrength))
2171
+ .force('center', d3.forceCenter(width / 2, height / 2).strength(centerStrength))
2172
+ .force('collision', d3.forceCollide().radius(d => nodeRadius(d) + 4));
2173
+
2174
+ const link = g.append('g').selectAll('line').data(DATA.edges).join('line')
2175
+ .attr('class', 'link')
2176
+ .attr('stroke-width', d => edgeWidth(d))
2177
+ .attr('stroke-linecap', 'round');
2178
+
2179
+ const node = g.append('g').selectAll('circle').data(DATA.nodes).join('circle')
2180
+ .attr('class', 'node-circle')
2181
+ .attr('r', d => nodeRadius(d))
2182
+ .attr('fill', d => COLORS[d.category] || '#888')
2183
+ .attr('stroke', d => { const c = COLORS[d.category] || '#888'; return c; })
2184
+ .attr('stroke-width', 1.5)
2185
+ .attr('stroke-opacity', 0.6)
2186
+ .call(d3.drag()
2187
+ .on('start', (e, d) => { if (!e.active) simulation.alphaTarget(0.3).restart(); d.fx = d.x; d.fy = d.y; })
2188
+ .on('drag', (e, d) => { d.fx = e.x; d.fy = e.y; })
2189
+ .on('end', (e, d) => { if (!e.active) simulation.alphaTarget(0); })
2190
+ )
2191
+ .on('contextmenu', (e, d) => { e.preventDefault(); d.fx = null; d.fy = null; simulation.alpha(0.3).restart(); });
2192
+ const label = g.append('g').selectAll('text').data(DATA.nodes).join('text')
2193
+ .attr('class', 'node-label').attr('dy', d => -(nodeRadius(d) + 4))
2194
+ .text(d => d.id.length > 18 ? d.id.substring(0, 16) + '..' : d.id);
2195
+
2196
+ // Edge tooltips
2197
+ link.on('mouseover', (e, d) => {
2198
+ const s = typeof d.source === 'object' ? d.source.id : d.source;
2199
+ const t = typeof d.target === 'object' ? d.target.id : d.target;
2200
+ const sharedTags = getSharedTags(s, t);
2201
+ const html = '<div class="tt-edge">' +
2202
+ '<span style="color:' + (COLORS[nodeMap.get(s)?.category] || 'var(--muted)') + '">' + escHtml(s) + '</span>' +
2203
+ ' \u2192 ' +
2204
+ '<span style="color:' + (COLORS[nodeMap.get(t)?.category] || 'var(--muted)') + '">' + escHtml(t) + '</span>' +
2205
+ (sharedTags.length ? '<br>Tags: ' + sharedTags.map(tag => '<span class="entry-tag">' + escHtml(tag) + '</span>').join(' ') : '') +
2206
+ '</div>';
2207
+ tooltip.innerHTML = html;
2208
+ tooltip.style.display = 'block';
2209
+ positionTooltip(e);
2210
+ })
2211
+ .on('mouseout', () => { hideTooltip(); });
2212
+
2213
+ node.on('mouseover', (e, d) => {
2214
+ showTooltip(e, d);
2215
+ highlightNode(d.id);
2216
+ })
2217
+ .on('mouseout', () => {
2218
+ hideTooltip();
2219
+ if (!selectedEntry) highlightNode(null);
2220
+ else highlightNode(selectedEntry.id);
2221
+ });
2222
+
2223
+ svg.on('click', () => { selectedEntry = null; highlightNode(null); renderEntries(); });
2224
+
2225
+ simulation.on('tick', () => {
2226
+ link.attr('x1', d => d.source.x).attr('y1', d => d.source.y)
2227
+ .attr('x2', d => d.target.x).attr('y2', d => d.target.y);
2228
+ node.attr('cx', d => d.x).attr('cy', d => d.y);
2229
+ label.attr('x', d => d.x).attr('y', d => d.y);
2230
+ updateMinimap();
2231
+ });
2232
+
2233
+ function highlightNode(id) {
2234
+ const neighbors = new Set();
2235
+ if (id) {
2236
+ DATA.edges.forEach(e => {
2237
+ const s = typeof e.source === 'object' ? e.source.id : e.source;
2238
+ const t = typeof e.target === 'object' ? e.target.id : e.target;
2239
+ if (s === id) neighbors.add(t);
2240
+ if (t === id) neighbors.add(s);
2241
+ });
2242
+ neighbors.add(id);
2243
+ }
2244
+ node.attr('r', d => id ? (d.id === id ? nodeRadius(d) + 4 : neighbors.has(d.id) ? nodeRadius(d) + 1 : 2) : nodeRadius(d))
2245
+ .attr('opacity', d => id ? (neighbors.has(d.id) ? 1 : 0.12) : 1)
2246
+ .classed('glow', d => id && d.id === id);
2247
+ 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));
2248
+ 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);
2249
+ label.attr('opacity', d => id ? (neighbors.has(d.id) ? 1 : 0.08) : 1);
2250
+ }
2251
+
2252
+ function highlightSearch() {
2253
+ if (!searchQuery && !activeFilter) { highlightNode(null); return; }
2254
+ const q = searchQuery;
2255
+ const matches = new Set();
2256
+ DATA.nodes.forEach(n => {
2257
+ const match = (!q || n.id.toLowerCase().includes(q) || n.content.toLowerCase().includes(q) || n.tags.some(t => t.toLowerCase().includes(q)));
2258
+ const catMatch = !activeFilter || n.category === activeFilter;
2259
+ if (match && catMatch) matches.add(n.id);
2260
+ });
2261
+ node.attr('r', d => matches.has(d.id) ? nodeRadius(d) + 3 : 2)
2262
+ .attr('opacity', d => matches.has(d.id) ? 1 : 0.06)
2263
+ .classed('glow search-match', d => matches.has(d.id));
2264
+ label.attr('opacity', d => matches.has(d.id) ? 1 : 0.03);
2265
+ link.attr('opacity', 0.03);
2266
+ }
2267
+
2268
+ // Zoom controls
2269
+ document.getElementById('zoomIn').onclick = () => svg.transition().call(zoom.scaleBy, 1.5);
2270
+ document.getElementById('zoomOut').onclick = () => svg.transition().call(zoom.scaleBy, 0.67);
2271
+ document.getElementById('zoomReset').onclick = () => svg.transition().call(zoom.transform, d3.zoomIdentity);
2272
+
2273
+ // Legend
2274
+ const legend = document.getElementById('legend');
2275
+ legend.innerHTML = Object.entries(COLORS).map(([cat, color]) =>
2276
+ '<div class="legend-item"><span class="legend-dot" style="background:' + color + '"></span>' + cat + '</div>'
2277
+ ).join('');
2278
+
2279
+ // Physics controls
2280
+ const physicsToggle = document.getElementById('physicsToggle');
2281
+ const physicsPanel = document.getElementById('physicsPanel');
2282
+ physicsToggle.onclick = () => {
2283
+ physicsPanel.style.display = physicsPanel.style.display === 'none' ? 'block' : 'none';
2284
+ };
2285
+
2286
+ function updatePhysics() {
2287
+ simulation.force('charge').strength(chargeStrength);
2288
+ simulation.force('link').distance(linkDistance);
2289
+ simulation.force('center').strength(centerStrength);
2290
+ simulation.alpha(0.5).restart();
2291
+ }
2292
+
2293
+ document.getElementById('chargeSlider').oninput = (e) => {
2294
+ chargeStrength = parseInt(e.target.value);
2295
+ document.getElementById('chargeVal').textContent = chargeStrength;
2296
+ updatePhysics();
2297
+ };
2298
+ document.getElementById('distSlider').oninput = (e) => {
2299
+ linkDistance = parseInt(e.target.value);
2300
+ document.getElementById('distVal').textContent = linkDistance;
2301
+ updatePhysics();
2302
+ };
2303
+ document.getElementById('centerSlider').oninput = (e) => {
2304
+ centerStrength = parseFloat(e.target.value);
2305
+ document.getElementById('centerVal').textContent = centerStrength;
2306
+ updatePhysics();
2307
+ };
2308
+
2309
+ // Center on a node
2310
+ function centerOn(id) {
2311
+ const n = DATA.nodes.find(d => d.id === id);
2312
+ if (!n || n.x == null) return;
2313
+ const w = container.clientWidth, h = container.clientHeight;
2314
+ svg.transition().duration(400).call(zoom.transform,
2315
+ d3.zoomIdentity.translate(w / 2 - n.x * currentTransform.k, h / 2 - n.y * currentTransform.k).scale(currentTransform.k));
2316
+ }
2317
+
2318
+ // Path finder
2319
+ let pathStart = null, pathActive = false;
2320
+ function findPath(a, b) {
2321
+ const adj = new Map();
2322
+ DATA.edges.forEach(e => {
2323
+ const s = typeof e.source === 'object' ? e.source.id : e.source;
2324
+ const t = typeof e.target === 'object' ? e.target.id : e.target;
2325
+ if (!adj.has(s)) adj.set(s, []);
2326
+ if (!adj.has(t)) adj.set(t, []);
2327
+ adj.get(s).push(t);
2328
+ adj.get(t).push(s);
2329
+ });
2330
+ const visited = new Set([a]), parent = new Map([[a, null]]);
2331
+ const queue = [a];
2332
+ while (queue.length) {
2333
+ const cur = queue.shift();
2334
+ if (cur === b) break;
2335
+ for (const nb of (adj.get(cur) || [])) {
2336
+ if (!visited.has(nb)) { visited.add(nb); parent.set(nb, cur); queue.push(nb); }
2337
+ }
2338
+ }
2339
+ if (!parent.has(b)) return null;
2340
+ const path = [];
2341
+ let cur = b;
2342
+ while (cur !== null) { path.unshift(cur); cur = parent.get(cur); }
2343
+ return path;
2344
+ }
2345
+ function highlightPath(path) {
2346
+ link.classed('path-edge', false).attr('opacity', 0.5);
2347
+ node.classed('path-start path-end path-node', false).attr('r', d => nodeRadius(d));
2348
+ if (!path) return;
2349
+ const set = new Set(path);
2350
+ path.forEach((id, i) => {
2351
+ node.filter(d => d.id === id)
2352
+ .classed(i === 0 ? 'path-start' : i === path.length - 1 ? 'path-end' : 'path-node', true)
2353
+ .attr('r', d => nodeRadius(d) + 3);
2354
+ });
2355
+ for (let i = 0; i < path.length - 1; i++) {
2356
+ link.filter(d => {
2357
+ const s = typeof d.source === 'object' ? d.source.id : d.source;
2358
+ const t = typeof d.target === 'object' ? d.target.id : d.target;
2359
+ return (s === path[i] && t === path[i+1]) || (s === path[i+1] && t === path[i]);
2360
+ }).classed('path-edge', true).attr('opacity', 1);
2361
+ }
2362
+ }
2363
+
2364
+ // Minimap
2365
+ const minimapSvg = d3.select('#minimapSvg');
2366
+ const minimapScale = 0.1;
2367
+ const minimapW = 150, minimapH = 100;
2368
+ const minimapG = minimapSvg.append('g');
2369
+ minimapG.append('g').attr('class', 'minimap-links');
2370
+ minimapG.append('g').attr('class', 'minimap-nodes');
2371
+ 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);
2372
+
2373
+ function getGraphBounds() {
2374
+ const allX = DATA.nodes.map(n => n.x || 0);
2375
+ const allY = DATA.nodes.map(n => n.y || 0);
2376
+ return { minX: Math.min(...allX) - 20, minY: Math.min(...allY) - 20, maxX: Math.max(...allX) + 20, maxY: Math.max(...allY) + 20 };
2377
+ }
2378
+
2379
+ function updateMinimap() {
2380
+ const { minX, minY } = getGraphBounds();
2381
+ minimapG.attr('transform', 'translate(' + (-minX * minimapScale) + ',' + (-minY * minimapScale) + ')');
2382
+
2383
+ minimapG.select('.minimap-links').selectAll('line').data(DATA.edges).join('line')
2384
+ .attr('x1', d => (d.source.x || 0) * minimapScale)
2385
+ .attr('y1', d => (d.source.y || 0) * minimapScale)
2386
+ .attr('x2', d => (d.target.x || 0) * minimapScale)
2387
+ .attr('y2', d => (d.target.y || 0) * minimapScale)
2388
+ .attr('stroke', 'var(--border)').attr('stroke-width', 0.5).attr('stroke-opacity', 0.3);
2389
+
2390
+ minimapG.select('.minimap-nodes').selectAll('circle').data(DATA.nodes).join('circle')
2391
+ .attr('cx', d => (d.x || 0) * minimapScale).attr('cy', d => (d.y || 0) * minimapScale)
2392
+ .attr('r', 1.8).attr('fill', d => COLORS[d.category] || '#888').attr('stroke', 'none');
2393
+
2394
+ const t = currentTransform;
2395
+ const containerW = container.clientWidth;
2396
+ const containerH = container.clientHeight;
2397
+ const vpX = (-t.x / t.k - minX) * minimapScale;
2398
+ const vpY = (-t.y / t.k - minY) * minimapScale;
2399
+ const vpW = (containerW / t.k) * minimapScale;
2400
+ const vpH = (containerH / t.k) * minimapScale;
2401
+ minimapViewport.attr('x', Math.max(0, vpX)).attr('y', Math.max(0, vpY))
2402
+ .attr('width', Math.min(vpW, minimapW)).attr('height', Math.min(vpH, minimapH));
2403
+ }
2404
+
2405
+ minimapSvg.on('click', (e) => {
2406
+ const { minX, minY } = getGraphBounds();
2407
+ const rect = minimapSvg.node().getBoundingClientRect();
2408
+ const mmx = (e.clientX - rect.left) / minimapScale + minX;
2409
+ const mmy = (e.clientY - rect.top) / minimapScale + minY;
2410
+ const w2 = container.clientWidth / 2, h2 = container.clientHeight / 2;
2411
+ svg.transition().duration(300).call(zoom.transform, d3.zoomIdentity.translate(w2 - mmx, h2 - mmy));
2412
+ });
2413
+
2414
+ // Export PNG
2415
+ document.getElementById('exportPng').onclick = () => {
2416
+ const svgEl = container.querySelector('svg');
2417
+ const svgData = new XMLSerializer().serializeToString(svgEl);
2418
+ const canvas = document.createElement('canvas');
2419
+ const ctx = canvas.getContext('2d');
2420
+ const img = new Image();
2421
+ canvas.width = svgEl.clientWidth * 2;
2422
+ canvas.height = svgEl.clientHeight * 2;
2423
+ img.onload = () => {
2424
+ ctx.fillStyle = getComputedStyle(document.documentElement).getPropertyValue('--bg').trim();
2425
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
2426
+ ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
2427
+ const link = document.createElement('a');
2428
+ link.download = 'toon-memory-graph.png';
2429
+ link.href = canvas.toDataURL('image/png');
2430
+ link.click();
2431
+ };
2432
+ img.src = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgData)));
2433
+ };
2434
+
2435
+ // Export SVG
2436
+ document.getElementById('exportSvg').onclick = () => {
2437
+ const svgEl = container.querySelector('svg');
2438
+ const svgData = new XMLSerializer().serializeToString(svgEl);
2439
+ const blob = new Blob([svgData], { type: 'image/svg+xml' });
2440
+ const link = document.createElement('a');
2441
+ link.download = 'toon-memory-graph.svg';
2442
+ link.href = URL.createObjectURL(blob);
2443
+ link.click();
2444
+ };
2445
+
2446
+ // Path toggle
2447
+ document.getElementById('pathToggle').onclick = () => {
2448
+ pathActive = !pathActive;
2449
+ document.getElementById('pathToggle').classList.toggle('active', pathActive);
2450
+ if (!pathActive) { pathStart = null; highlightPath(null); }
2451
+ document.getElementById('pathInfo').style.display = 'none';
2452
+ };
2453
+ function selectEntryGraph(entry) {
2454
+ selectedEntry = entry;
2455
+ renderEntries();
2456
+ showDetail(entry);
2457
+ graph.highlightNode(entry.id);
2458
+ graph.centerOn(entry.id);
2459
+ }
2460
+
2461
+ let clickTimer = null;
2462
+ node.on('click', (e, d) => {
2463
+ e.stopPropagation();
2464
+ if (pathActive) {
2465
+ if (!pathStart) {
2466
+ pathStart = d.id;
2467
+ document.getElementById('pathInfo').textContent = 'Click target node';
2468
+ document.getElementById('pathInfo').style.display = 'block';
2469
+ highlightPath(null);
2470
+ node.classed('path-start', false);
2471
+ node.filter(n => n.id === d.id).classed('path-start', true);
2472
+ } else {
2473
+ const path = findPath(pathStart, d.id);
2474
+ if (path) {
2475
+ const info = document.getElementById('pathInfo');
2476
+ info.innerHTML = 'Path: ' + path.join(' \u2192 ');
2477
+ info.style.display = 'block';
2478
+ highlightPath(path);
2479
+ centerOn(path[Math.floor(path.length / 2)]);
2480
+ } else {
2481
+ document.getElementById('pathInfo').textContent = 'No path found';
2482
+ document.getElementById('pathInfo').style.display = 'block';
2483
+ }
2484
+ pathStart = null;
2485
+ pathActive = false;
2486
+ document.getElementById('pathToggle').classList.remove('active');
2487
+ }
2488
+ return;
2489
+ }
2490
+ if (clickTimer) { clearTimeout(clickTimer); clickTimer = null; return; }
2491
+ clickTimer = setTimeout(() => {
2492
+ clickTimer = null;
2493
+ selectEntryGraph(d);
2494
+ }, 220);
2495
+ });
2496
+ node.on('dblclick', (e, d) => {
2497
+ e.stopPropagation();
2498
+ if (clickTimer) { clearTimeout(clickTimer); clickTimer = null; }
2499
+ selectEntry(d); hideTooltip();
2500
+ });
2501
+
2502
+ _impl = { highlightNode, highlightSearch, centerOn, resize: () => {
2503
+ const w = container.clientWidth;
2504
+ const h = container.clientHeight;
2505
+ simulation.force('center', d3.forceCenter(w / 2, h / 2).strength(centerStrength));
2506
+ simulation.alpha(0.3).restart();
2507
+ }};
2508
+ };
2509
+ if (container.clientWidth > 0 && container.clientHeight > 0) {
2510
+ initGraph();
2511
+ } else {
2512
+ const ro = new ResizeObserver(() => {
2513
+ if (container.clientWidth > 0 && container.clientHeight > 0) {
2514
+ ro.disconnect();
2515
+ initGraph();
2516
+ }
2517
+ });
2518
+ ro.observe(container);
2519
+ }
2520
+ return { highlightNode: (...a) => safe('highlightNode', ...a), highlightSearch: (...a) => safe('highlightSearch', ...a), centerOn: (...a) => safe('centerOn', ...a), resize: (...a) => safe('resize', ...a) };
2521
+ })();
2522
+
2523
+ // --- Keyboard Shortcuts ---
2524
+ document.addEventListener('keydown', (e) => {
2525
+ if (e.target.tagName === 'INPUT') {
2526
+ if (e.key === 'Escape') { e.target.value = ''; searchQuery = ''; renderEntries(); if (graph.highlightSearch) graph.highlightSearch(); e.target.blur(); }
2527
+ return;
2528
+ }
2529
+ if (e.key === '/') { e.preventDefault(); document.getElementById('search').focus(); }
2530
+ if (e.key === 'Escape') { selectedEntry = null; renderEntries(); graph.highlightNode(null); switchTab('graph'); }
2531
+ if (e.key === '1') switchTab('graph');
2532
+ if (e.key === '2') switchTab('stats');
2533
+ if (e.key === '3') switchTab('timeline');
2534
+ if (e.key === '4') switchTab('detail');
2535
+ });
2536
+
2537
+ // --- Sidebar Resize ---
2538
+ (function() {
2539
+ const resizer = document.getElementById('sidebarResizer');
2540
+ let startX, startW;
2541
+ resizer.addEventListener('mousedown', (e) => {
2542
+ startX = e.clientX;
2543
+ startW = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--sidebar-w')) || 320;
2544
+ document.body.style.cursor = 'col-resize';
2545
+ document.body.style.userSelect = 'none';
2546
+ const onMove = (ev) => {
2547
+ const w = Math.max(160, Math.min(600, startW + ev.clientX - startX));
2548
+ document.documentElement.style.setProperty('--sidebar-w', w + 'px');
2549
+ };
2550
+ const onUp = () => {
2551
+ document.body.style.cursor = '';
2552
+ document.body.style.userSelect = '';
2553
+ document.removeEventListener('mousemove', onMove);
2554
+ document.removeEventListener('mouseup', onUp);
2555
+ };
2556
+ document.addEventListener('mousemove', onMove);
2557
+ document.addEventListener('mouseup', onUp);
2558
+ });
2559
+ })();
2560
+
2561
+ renderStats();
2562
+ renderTimeline();
2563
+ renderEntries();
2564
+
2565
+ document.getElementById('reloadBtn').addEventListener('click', () => location.reload());
2566
+ document.addEventListener('keydown', (e) => {
2567
+ if (e.key === 'r' && !e.metaKey && !e.ctrlKey && !e.target.closest('input,textarea')) location.reload();
2568
+ });
2569
+
2570
+ // MCP Apps: expose a global so the host can detect the viewer is ready
2571
+ if (window.parent !== window) {
2572
+ console.log('toon-memory viewer running in MCP Apps iframe');
2573
+ }
2574
+ </script>
2575
+ </body>
2576
+ </html>`;
2577
+ }
2578
+
2579
+ // src/viewer/index.ts
2580
+ import { createServer } from "http";
2581
+ function openBrowser(url) {
2582
+ const platform = process.platform;
2583
+ try {
2584
+ if (platform === "darwin") execSync(`open "${url}"`);
2585
+ else if (platform === "win32") execSync(`start "" "${url}"`);
2586
+ else execSync(`xdg-open "${url}" || sensible-browser "${url}" || x-www-browser "${url}"`, { stdio: "ignore" });
2587
+ } catch {
2588
+ console.log(`Open in browser: ${url}`);
2589
+ }
2590
+ }
2591
+ function viewer(portArg) {
2592
+ const PORT = parseInt(portArg || process.env.PORT || "3000", 10);
2593
+ let currentHtml = generateHtml(buildViewerData());
2594
+ const server = createServer((_req, res) => {
2595
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
2596
+ res.end(currentHtml);
2597
+ });
2598
+ server.listen(PORT, "127.0.0.1", () => {
2599
+ const url = `http://127.0.0.1:${PORT}`;
2600
+ const data = buildViewerData();
2601
+ console.log(`
2602
+ toon-memory viewer`);
2603
+ console.log(` Entries: ${data.totalEntries} | Edges: ${data.edges.length}`);
2604
+ console.log(` Serving at: ${url}`);
2605
+ console.log(` Press 'r' in terminal to reload | Ctrl+C to stop
2606
+ `);
2607
+ openBrowser(url);
2608
+ });
2609
+ if (process.stdin.isTTY) {
2610
+ process.stdin.setRawMode?.(true);
2611
+ process.stdin.resume();
2612
+ process.stdin.on("data", (buf) => {
2613
+ const key = buf.toString();
2614
+ if (key === "r" || key === "R") {
2615
+ const data = buildViewerData();
2616
+ currentHtml = generateHtml(data);
2617
+ console.log(` Reloaded: ${data.totalEntries} entries, ${data.edges.length} edges`);
2618
+ }
2619
+ if (key === "") process.exit(0);
2620
+ });
2621
+ }
2622
+ server.on("error", (err) => {
2623
+ if (err.code === "EADDRINUSE") {
2624
+ console.error(`Port ${PORT} already in use. Try: PORT=3001 toon-memory viewer`);
2625
+ } else {
2626
+ console.error(`Server error: ${err.message}`);
2627
+ }
2628
+ process.exit(1);
2629
+ });
2630
+ }
2631
+ function viewerExport() {
2632
+ const viewerData = buildViewerData();
2633
+ const html = generateHtml(viewerData);
2634
+ const projectRoot3 = process.cwd();
2635
+ const outDir = join10(projectRoot3, ".toon-memory", "viewer");
2636
+ mkdirSync10(outDir, { recursive: true });
2637
+ const outFile = join10(outDir, "index.html");
2638
+ writeFileSync11(outFile, html, "utf-8");
2639
+ console.log(`Viewer saved: ${outFile}`);
2640
+ console.log(`Entries: ${viewerData.totalEntries} | Edges: ${viewerData.edges.length}`);
2641
+ openBrowser(outFile);
2642
+ }
2643
+
1395
2644
  // src/cli/setup.ts
1396
2645
  var args = process.argv.slice(2);
1397
2646
  if (args[0] === "capture") {
@@ -1452,17 +2701,27 @@ if (args[0] === "watch") {
1452
2701
  watch(args);
1453
2702
  process.exit(0);
1454
2703
  }
1455
- if (args.length === 0) {
2704
+ if (args[0] === "viewer") {
2705
+ const portIdx = args.indexOf("--port");
2706
+ const port = portIdx !== -1 && args[portIdx + 1] ? args[portIdx + 1] : void 0;
2707
+ if (args.includes("--export")) {
2708
+ viewerExport();
2709
+ } else {
2710
+ viewer(port);
2711
+ }
2712
+ } else if (args.length === 0) {
1456
2713
  await interactiveInstall();
1457
2714
  process.exit(0);
1458
- }
1459
- console.log(`Unknown command: '${args[0]}'
2715
+ } else {
2716
+ console.log(`Unknown command: '${args[0]}'
1460
2717
  `);
1461
- printUsage();
1462
- process.exit(1);
2718
+ printUsage();
2719
+ process.exit(1);
2720
+ }
1463
2721
  function printUsage() {
1464
2722
  console.log(`Usage: toon-memory <command> [options]
1465
- Commands: init, status, stats, export, import, watch, uninstall, capture, upgrade, mcp
2723
+ Commands: init, status, stats, export, import, watch, viewer, uninstall, capture, upgrade, mcp
2724
+ viewer [--export] [--port <n>] \u2014 Start an HTTP server with the graph viewer (press 'r' to reload). --export saves static HTML.
1466
2725
  Init: toon-memory init [--agent <name> --agent <name>...] [--scope local|global]
1467
2726
  Without --agent: interactive agent and scope selector.
1468
2727
  With --agent: non-interactive installation (default: scope local).