@sparkelf/dsh-knowledge-base 0.4.3 → 0.5.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/lib/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createHash, randomBytes, randomUUID } from "node:crypto";
2
2
  import { homedir, tmpdir } from "node:os";
3
- import { appendFile, copyFile, link, lstat, mkdir, mkdtemp, readFile, readdir, readlink, rename, rm, rmdir, stat, symlink, unlink, writeFile } from "node:fs/promises";
3
+ import { appendFile, copyFile, link, lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, rename, rm, rmdir, stat, symlink, unlink, writeFile } from "node:fs/promises";
4
4
  import { constants, existsSync, readFileSync, watch } from "node:fs";
5
5
  import { basename, dirname, extname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
@@ -2909,7 +2909,7 @@ function mergeProjectedGraphs(tree, projectedByScope) {
2909
2909
  *
2910
2910
  * @module @sparkelf/dsh-knowledge-base/graph-canvas
2911
2911
  */
2912
- const GRAPH_CANVAS_HTML = "<!DOCTYPE html>\n<html lang=\"zh-CN\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>知识图谱 · 画布</title>\n<style>\n:root{\n --bg:#fbfbfc;\n --bg-soft:#f6f7f9;\n --surface:#ffffff;\n --ink:#0f1115;\n --ink-2:#3c3f47;\n --secondary:#61666b;\n --muted:#81858c;\n --line:rgba(0,0,0,.10);\n --line-2:rgba(0,0,0,.06);\n --blue:#4176e6;\n --blue-deep:#2555c4;\n --blue-soft:#eef4ff;\n --green:#22c55e;\n --amber:#f59e0b;\n --red:#dc2626;\n --red-deep:#b91c1c;\n --red-soft:rgba(220,38,38,.10);\n --radius:12px;\n --shadow:0 1px 2px rgba(15,17,21,.04), 0 8px 24px rgba(15,17,21,.06);\n --sans:-apple-system,BlinkMacSystemFont,\"Segoe UI\",\"PingFang SC\",\"Hiragino Sans GB\",\"Microsoft YaHei\",sans-serif;\n --mono:\"SF Mono\",\"JetBrains Mono\",Menlo,Consolas,monospace;\n}\n*{box-sizing:border-box}\nhtml,body{height:100%}\nbody{margin:0;background:var(--bg);color:var(--ink);font-family:var(--sans);\n font-size:14px;line-height:1.6;overflow:hidden;-webkit-font-smoothing:antialiased}\nbutton{font-family:inherit;color:inherit}\n\n#stage{position:fixed;left:248px;right:0;top:0;bottom:0;overflow:hidden;cursor:grab;\n background:\n radial-gradient(900px 620px at 50% 38%, #ffffff 0%, rgba(255,255,255,0) 70%),\n var(--bg)}\n#stage::before{content:\"\";position:absolute;inset:0;pointer-events:none;\n background-image:radial-gradient(rgba(15,17,21,.055) 1px, transparent 1px);\n background-size:22px 22px;\n -webkit-mask-image:radial-gradient(ellipse 70% 70% at 50% 45%, #000 0%, transparent 78%);\n mask-image:radial-gradient(ellipse 70% 70% at 50% 45%, #000 0%, transparent 78%)}\n#stage.grabbing{cursor:grabbing}\n#world{position:absolute;left:0;top:0;transform-origin:0 0;will-change:transform}\n#edges{position:absolute;left:0;top:0;overflow:visible;pointer-events:none}\n\n#topbar{position:fixed;left:248px;right:0;top:0;display:flex;align-items:flex-start;justify-content:space-between;\n padding:18px 22px;pointer-events:none;z-index:10}\n#brand h1{margin:0;font-size:16px;font-weight:600;letter-spacing:-.01em}\n#brand p{margin:4px 0 0;font-size:12px;color:var(--muted)}\n#brand b{color:var(--secondary);font-weight:500}\n#hint{font-size:11.5px;color:var(--muted);text-align:right;line-height:1.9;transition:opacity .2s}\n#hint kbd{font-family:var(--mono);font-size:10.5px;border:1px solid var(--line);border-radius:4px;\n padding:1px 5px;color:var(--secondary);background:var(--surface)}\nbody.panel-open #hint{opacity:0}\n\n.card{position:absolute;width:300px;padding:15px 16px 13px;border-radius:var(--radius);cursor:grab;\n user-select:none;background:var(--surface);border:1px solid var(--line);box-shadow:var(--shadow);\n transition:border-color .16s,box-shadow .16s,opacity .16s}\n.card:hover{border-color:rgba(0,0,0,.18)}\n.card.dragging{cursor:grabbing;transition:none}\n.card.selected{border-color:var(--blue);\n box-shadow:0 0 0 2px rgba(65,118,230,.14),0 10px 28px rgba(15,17,21,.10)}\n.card.dim{opacity:.38}\n.card:focus-visible{outline:2px solid var(--blue);outline-offset:3px}\n.chip{font-size:11px;letter-spacing:.02em;color:var(--secondary);background:var(--bg-soft);\n border:1px solid var(--line-2);border-radius:6px;padding:1px 7px}\n.status{display:inline-flex;align-items:center;gap:6px;font-size:11px;color:var(--muted)}\n.dot{width:6px;height:6px;border-radius:50%;background:var(--green)}\n.dot.paused{background:var(--amber)}\n.dot.done{background:#c4c7cc}\n.card h3{margin:0 0 9px;font-size:17px;font-weight:600;line-height:1.35;letter-spacing:-.01em}\n.cover{position:relative;height:124px;margin:0 0 10px}\nbody[data-doc-layout=\"landscape\"] .cover{height:86px;margin-bottom:9px}\nbody[data-doc-layout=\"landscape\"] .doc{width:132px;height:76px;border-radius:5px}\nbody[data-doc-layout=\"landscape\"] .doc-empty{width:140px;height:80px}\n.stack{position:absolute;inset:0}\n.doc{position:absolute;left:50%;top:50%;width:86px;height:116px;border-radius:6px;\n border:1px solid rgba(0,0,0,.08);box-shadow:0 8px 18px rgba(15,17,21,.14);background:#fff;\n object-fit:cover;\n transform:translate(-50%,-50%) translate(var(--dx),var(--dy)) rotate(var(--rot)) scale(var(--sc));\n transition:transform .22s cubic-bezier(.22,1,.36,1)}\n.cover:hover .doc{transform:translate(-50%,-50%) translate(calc(var(--dx) * 1.4),var(--dy)) rotate(calc(var(--rot) * 1.35)) scale(var(--sc))}\n.doc-empty{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:96px;height:120px;\n border:1px dashed var(--line);border-radius:6px;display:flex;align-items:center;justify-content:center;\n color:#b3b7bd;font-size:10.5px;background:var(--bg-soft)}\n.more{position:absolute;right:2px;bottom:0;font-size:10px;color:var(--muted);background:var(--surface);\n border:1px solid var(--line-2);border-radius:999px;padding:0 6px}\n.tags{display:flex;flex-wrap:wrap;gap:5px;margin-top:9px;margin-bottom:2px}\n.tags span{font-size:10px;color:var(--secondary);background:var(--bg-soft);border:1px solid var(--line-2);\n border-radius:999px;padding:1px 7px}\n.one{margin:0;font-size:12.5px;line-height:1.65;color:var(--ink-2);\n display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden}\n\n.dots{display:inline-flex;gap:3px}\n.dots i{width:5px;height:5px;border-radius:50%;background:#dcdfe3}\n.dots i.on{background:var(--ink)}\n\n.edge{fill:none;stroke:rgba(15,17,21,.32);stroke-width:1.2}\n.edge.cross{stroke:rgba(15,17,21,.18);stroke-dasharray:4 6}\n.edge.hot{stroke:var(--blue);stroke-width:1.6}\n.edge.cold{opacity:.22}\n\n.pill{cursor:pointer;pointer-events:auto}\n.pill rect{fill:var(--surface);stroke:var(--line);stroke-width:1;transition:stroke .16s,fill .16s}\n.pill text{font:10.5px var(--sans);fill:var(--secondary);letter-spacing:.01em}\n.pill:hover rect{stroke:rgba(0,0,0,.28)}\n.pill.hot rect{stroke:var(--blue);fill:var(--blue-soft)}\n.pill.hot text{fill:var(--blue-deep)}\n.pill.cold{opacity:.25}\n.pill:focus-visible{outline:none}\n.pill:focus-visible rect{stroke:var(--blue);stroke-width:1.6}\n\n#kg-crumb{position:fixed;left:16px;top:14px;z-index:14;display:flex;align-items:center;gap:6px;\n max-width:calc(100% - 32px);padding:6px 11px;border-radius:999px;overflow:hidden;\n background:color-mix(in srgb,var(--surface) 78%,transparent);backdrop-filter:blur(10px);\n border:1px solid var(--line);pointer-events:auto}\n#kg-crumb .seg{border:0;background:none;padding:0;font-size:12px;color:var(--secondary);\n white-space:nowrap;cursor:pointer}\n#kg-crumb .seg:hover{color:var(--ink)}\n#kg-crumb .sep{color:var(--muted);font-size:11px}\n#kg-crumb b{color:var(--ink);font-weight:600;font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n#controls{position:fixed;left:266px;bottom:18px;display:flex;flex-direction:column;gap:6px;z-index:12}\n#controls button{width:34px;height:34px;border-radius:8px;border:1px solid var(--line);\n background:var(--surface);color:var(--ink-2);font-size:15px;line-height:1;cursor:pointer;\n box-shadow:0 1px 2px rgba(15,17,21,.04);transition:background .15s,color .15s}\n#controls button:hover{background:var(--bg-soft);color:var(--ink)}\n#controls button.on{background:var(--ink);color:#fff;border-color:var(--ink)}\n#controls button:focus-visible{outline:2px solid var(--blue);outline-offset:2px}\n#zoomLabel{position:fixed;left:308px;bottom:23px;font-family:var(--mono);font-size:10.5px;\n color:var(--muted);z-index:12}\n\n#panel{position:fixed;top:0;right:0;width:392px;height:100%;z-index:30;\n background:var(--surface);border-left:1px solid var(--line);\n box-shadow:-8px 0 28px rgba(15,17,21,.06);\n transform:translateX(102%);transition:transform .28s cubic-bezier(.22,1,.36,1);\n display:flex;flex-direction:column}\n#panel.open{transform:none}\n.p-head{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;\n padding:22px 22px 15px;border-bottom:1px solid var(--line-2)}\n.p-kicker{font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:var(--muted)}\n.p-head h2{margin:7px 0 0;font-size:22px;font-weight:600;line-height:1.35;letter-spacing:-.01em}\n#close{width:30px;height:30px;flex:0 0 auto;border-radius:8px;border:1px solid var(--line);\n background:var(--surface);color:var(--muted);font-size:16px;cursor:pointer;line-height:1}\n#close:hover{color:var(--ink);background:var(--bg-soft)}\n.p-body{padding:16px 22px 40px;overflow:auto}\n.p-field{margin:0 0 14px}\n.p-field b{display:block;font-size:11px;letter-spacing:.08em;text-transform:uppercase;\n color:var(--muted);font-weight:500;margin-bottom:3px}\n.p-field span{display:block;font-size:13px;line-height:1.7;color:var(--ink-2)}\n.p-rel-title{margin:24px 0 9px;font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:var(--muted)}\n.rel{display:block;width:100%;text-align:left;background:var(--bg-soft);\n border:1px solid var(--line-2);border-radius:8px;padding:10px 11px;margin:0 0 7px;cursor:pointer;\n transition:background .15s,border-color .15s}\n.rel:hover{background:#f1f3f5;border-color:var(--line)}\n.rel b{display:block;font-size:12.5px;color:var(--ink);margin-bottom:2px;font-weight:600}\n.rel span{display:block;font-size:11.5px;line-height:1.6;color:var(--muted);\n display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden}\n.p-docs{font-size:11.5px;color:var(--muted);margin-top:12px}\n.p-doc-item{display:flex;gap:10px;align-items:center;padding:7px 0;border-bottom:1px solid var(--line-2)}\n.p-doc-item img{width:34px;height:46px;border-radius:3px;border:1px solid var(--line-2);object-fit:cover;flex:0 0 auto}\n.p-doc-item .m b{display:block;font-size:12.5px;font-weight:600;color:var(--ink)}\n.p-doc-item .m span{display:block;font-size:10.5px;color:var(--muted)}\n.p-badges{display:inline-flex;align-items:center;gap:3px;margin-left:5px;vertical-align:middle;flex:0 0 auto}\n.p-badge{display:inline-flex;align-items:center;height:15px;padding:0 4px;border:.5px solid var(--line);border-radius:3px;background:var(--bg-soft);color:var(--ink-2);font:600 9.5px/1 var(--sans);letter-spacing:0;white-space:nowrap;cursor:default}\n.p-badge.ai{border-color:var(--blue);background:var(--blue-soft);color:var(--blue-deep)}\n.p-badge.reviewed{border-color:var(--green);background:rgba(34,197,94,.10)}\n.p-badge.redline{border-color:var(--red);background:var(--red-soft);color:var(--red-deep)}\n.p-doc{font-size:13px;line-height:1.8;color:var(--ink-2)}\n.p-doc h2{font-size:14px;font-weight:600;color:var(--ink);margin:22px 0 6px}\n.p-doc h3{font-size:13px;font-weight:600;color:var(--ink);margin:18px 0 5px}\n.p-doc p{margin:0 0 10px}\n.p-doc ul,.p-doc ol{margin:0 0 10px;padding-left:18px}\n.p-doc li{margin:2px 0}\n.p-doc blockquote{margin:0 0 10px;padding:2px 0 2px 12px;border-left:2px solid var(--line);color:var(--muted)}\n.p-doc code{font-family:var(--mono);font-size:.86em;background:var(--bg-soft);border:1px solid var(--line-2);padding:0 4px;border-radius:4px}\n.p-doc pre{margin:0 0 10px;padding:10px 12px;background:var(--bg-soft);border:1px solid var(--line-2);border-radius:8px;overflow:auto}\n.p-doc pre code{background:none;border:0;padding:0}\n.p-doc strong{color:var(--ink);font-weight:600}\n.p-doc a{color:var(--blue);text-decoration:none}\n\n\n/* ---------- tree ---------- */\n#tree{position:fixed;left:0;top:0;bottom:0;width:248px;z-index:20;display:flex;flex-direction:column;\n background:var(--surface);border-right:1px solid var(--line)}\n.tree-head{padding:18px 16px 13px;border-bottom:1px solid var(--line-2)}\n.tree-title{font-size:14px;font-weight:600}\n.tree-sub{font-size:11px;color:var(--muted);margin-top:2px}\n#treeBody{flex:1;overflow:auto;padding:8px 8px 20px}\n.tree-scope{font-size:10.5px;letter-spacing:.1em;color:var(--muted);padding:12px 10px 5px}\n.tree-group{font-size:11.5px;color:var(--secondary);padding:6px 10px 3px}\n.tree-graph{display:flex;align-items:center;justify-content:space-between;gap:8px;\n padding:5px 10px;border-radius:6px;font-size:12.5px;color:var(--ink-2);cursor:pointer}\n.tree-graph:hover{background:var(--bg-soft)}\n.tree-graph.active{background:var(--blue-soft);color:var(--blue-deep)}\n.tree-graph .n{font-size:10.5px;color:var(--muted);font-variant-numeric:tabular-nums}\n.tree-graph.active .n{color:var(--blue)}\n.tree-topic{padding:4px 10px 4px 24px;font-size:12px;color:var(--muted);border-radius:6px;cursor:pointer;\n white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.tree-topic:hover{background:var(--bg-soft);color:var(--ink)}\n.tree-empty{padding:2px 10px 4px 24px;font-size:11.5px;color:#b3b7bd}\n\n@media (max-width:760px){\n #tree{display:none}\n #stage{left:0}\n #topbar{left:0}\n #controls{left:18px}\n #zoomLabel{left:60px}\n #hint{display:none}\n .only-wide{display:none}\n #brand h1{font-size:15px}\n .card{width:270px}\n #panel{width:100%;height:72%;top:auto;bottom:0;border-left:0;border-top:1px solid var(--line);\n transform:translateY(102%);border-radius:16px 16px 0 0}\n #panel.open{transform:none}\n}\n</style>\n<style>\n:root{\n --bg:#151517; --bg-soft:#232324; --surface:#232324; --ink:#f5f5f7; --ink-2:#cfd3d6;\n --secondary:#adb2b8; --muted:#8a8d95; --line:rgba(255,255,255,.12); --line-2:rgba(255,255,255,.06);\n --blue:#4d93f8; --blue-deep:#9db9ff; --blue-soft:rgba(77,147,248,.14);\n --green:#22c55e; --amber:#f59e0b;\n --red:#f87171; --red-deep:#fca5a5; --red-soft:rgba(248,113,113,.14);\n --shadow:0 1px 2px rgba(0,0,0,.3), 0 10px 30px rgba(0,0,0,.28);\n}\nhtml,body{height:100%}\nbody{display:flex;overflow:hidden;background:var(--bg);color:var(--ink)}\n#rail{width:280px;flex:0 0 280px;background:#141416;border-right:.5px solid rgba(255,255,255,.10);\n display:flex;flex-direction:column;min-height:0}\n.rail-top{height:36px;flex:0 0 36px;display:flex;align-items:center;gap:8px;padding:0 6px 0 12px}\n.rail-brand{display:flex;align-items:center;gap:8px;font-size:14px;font-weight:600;color:var(--ink)}\n.rail-brand svg{width:16px;height:16px;color:var(--secondary)}\n.rail-fold{margin-left:auto;width:28px;height:28px;border:0;background:none;border-radius:6px;\n color:var(--muted);cursor:pointer;display:flex;align-items:center;justify-content:center}\n.rail-fold:hover{background:rgba(255,255,255,.06);color:var(--ink)}\n.rail-search{margin:6px 12px 4px;height:32px;display:flex;align-items:center;gap:8px;padding:0 10px;\n background:#1f1f22;border:.5px solid rgba(255,255,255,.10);border-radius:8px}\n.rail-search svg{width:14px;height:14px;color:var(--muted)}\n.rail-search input{flex:1;min-width:0;background:none;border:0;outline:none;color:var(--ink);font-size:12.5px}\n.rail-search input::placeholder{color:#6f737a}\n.rail-nav{padding:4px 8px;display:flex;flex-direction:column;gap:1px}\n.nav-item{height:34px;display:flex;align-items:center;gap:10px;padding:0 10px;border:0;border-radius:6px;\n background:none;color:var(--secondary);font-size:13.5px;text-align:left;cursor:pointer}\n.nav-item svg{width:15px;height:15px;color:var(--muted)}\n.nav-item:hover{background:rgba(255,255,255,.06)}\n.nav-item.active{background:rgba(255,255,255,.08);color:var(--ink)}\n.nav-item.active svg{color:var(--secondary)}\n.tree-head{height:36px;flex:0 0 36px;display:flex;align-items:center;gap:4px;padding:0 8px 0 12px}\n.rail-tabs{display:flex;align-items:center;gap:18px;height:36px}\n.rail-tab{height:36px;padding:0;border:0;background:none;color:var(--muted);font-size:14px;\n cursor:pointer;position:relative}\n.rail-tab:hover{color:var(--secondary)}\n.rail-tab.active{color:var(--ink)}\n.rail-tab.active::after{content:\"\";position:absolute;left:0;right:0;bottom:0;height:2px;\n border-radius:1px;background:var(--blue)}\n.tree-tools{margin-left:auto;display:flex;align-items:center;gap:2px}\n.tree-tools button{width:28px;height:28px;border:0;background:none;border-radius:6px;\n color:var(--secondary);display:flex;align-items:center;justify-content:center;cursor:pointer}\n.tree-tools button:hover{background:rgba(255,255,255,.06);color:var(--ink)}\n#treeBody{flex:1;min-height:0;overflow:auto;padding:4px 8px 16px}\n.tree-scope{font-size:10.5px;letter-spacing:.1em;color:var(--muted);padding:10px 10px 4px}\n.tree-group{font-size:11.5px;color:var(--secondary);padding:4px 10px 2px}\n.tree-graph{display:flex;justify-content:space-between;align-items:center;height:28px;padding:0 10px;\n border-radius:6px;font-size:12.5px;color:var(--secondary);cursor:pointer}\n.tree-graph:hover{background:rgba(255,255,255,.06)}\n.tree-graph.active{background:var(--blue-soft);color:var(--blue-deep)}\n.tree-graph .n{font-size:10.5px;color:#6f737a;font-variant-numeric:tabular-nums}\n.tree-topic{height:26px;display:flex;align-items:center;padding:0 10px 0 24px;border-radius:6px;\n font-size:12px;color:var(--muted);cursor:pointer;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.tree-topic:hover{background:rgba(255,255,255,.06);color:var(--ink)}\n.tree-empty{padding:2px 10px 4px 24px;font-size:11.5px;color:#5f636a}\n.tree-kb{display:flex;align-items:center;gap:8px;height:28px;padding:0 10px;border-radius:6px;\n font-size:12.5px;color:var(--secondary);cursor:pointer}\n.tree-kb:hover{background:rgba(255,255,255,.06)}\n.tree-kb svg{width:14px;height:14px;color:#d9a441;flex:0 0 auto}\n.tree-kb.file svg{color:#8a8d95}\n.tree-kb .date{margin-left:auto;font-size:10.5px;color:#6f737a}\n#main{flex:1;min-width:0;display:flex;flex-direction:column;position:relative;background:#1a1a1c}\n#mainhead{height:48px;flex:0 0 48px;display:flex;align-items:center;gap:12px;padding:0 18px;\n border-bottom:.5px solid rgba(255,255,255,.10)}\n.crumb{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--muted);min-width:0}\n.crumb b{color:var(--ink);font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.crumb i{font-style:normal;color:#5f636a}\n#headMeta{font-size:11.5px;color:#7f838a;white-space:nowrap}\n.head-actions{margin-left:auto;display:flex;gap:8px}\n.head-actions button{height:28px;padding:0 10px;border:.5px solid rgba(255,255,255,.12);border-radius:6px;\n background:#232324;color:var(--secondary);font-size:12px;cursor:pointer}\n.head-actions button:hover{background:#2c2c2e;color:var(--ink)}\n#stage{position:relative;left:auto;right:auto;top:auto;bottom:auto;flex:1;min-height:0;overflow:hidden;cursor:grab;\n background:radial-gradient(900px 620px at 50% 38%,rgba(255,255,255,.03),transparent 70%),#1a1a1c}\n#stage::before{background-image:radial-gradient(rgba(255,255,255,.055) 1px,transparent 1px)}\n#controls{position:absolute;left:16px;bottom:16px;z-index:12}\n#controls button{background:#232324;border-color:rgba(255,255,255,.12);color:var(--secondary)}\n#controls button:hover{background:#2c2c2e;color:var(--ink)}\n#controls button.on{background:var(--blue);border-color:var(--blue);color:#0b1220}\n#zoomLabel{position:absolute;left:60px;bottom:21px;color:var(--muted)}\n.card{background:#232324;border-color:rgba(255,255,255,.10);\n box-shadow:0 1px 2px rgba(0,0,0,.3),0 10px 30px rgba(0,0,0,.28)}\n.card:hover{border-color:rgba(255,255,255,.20)}\n.card.selected{border-color:var(--blue);box-shadow:0 0 0 2px rgba(77,147,248,.20),0 10px 30px rgba(0,0,0,.35)}\n.card.dim{opacity:.32}\n.card h3{color:var(--ink)}\n.one{color:var(--secondary)}\n.tags span{background:#2c2c2e;border-color:rgba(255,255,255,.08);color:var(--secondary)}\n.doc{border-color:rgba(255,255,255,.12);box-shadow:0 8px 18px rgba(0,0,0,.40)}\n.edge{stroke:rgba(255,255,255,.22)}\n.edge.cross{stroke:rgba(255,255,255,.12)}\n.edge.hot{stroke:var(--blue)}\n.pill rect{fill:#232324;stroke:rgba(255,255,255,.14)}\n.pill text{fill:var(--secondary)}\n.pill.hot rect{fill:rgba(77,147,248,.16);stroke:var(--blue)}\n.pill.hot text{fill:var(--blue-deep)}\n#panel{background:#1e1e21;border-left-color:rgba(255,255,255,.10);box-shadow:-8px 0 28px rgba(0,0,0,.40)}\n.p-head{border-bottom-color:rgba(255,255,255,.06)}\n.p-kicker{color:var(--muted)}\n.p-head h2{color:var(--ink)}\n#close{background:#232324;border-color:rgba(255,255,255,.12);color:var(--muted)}\n#close:hover{background:#2c2c2e;color:var(--ink)}\n.p-field b{color:var(--muted)}\n.p-field span{color:var(--secondary)}\n.p-doc{color:var(--secondary)}\n.p-doc h2,.p-doc h3{color:var(--ink)}\n.p-doc code{background:#2c2c2e;border-color:rgba(255,255,255,.08)}\n.p-doc pre{background:#1a1a1c;border-color:rgba(255,255,255,.08)}\n.rel{background:#262629;border-color:rgba(255,255,255,.07)}\n.rel:hover{background:#2c2c2e;border-color:rgba(255,255,255,.12)}\n.rel b{color:var(--ink)}\n.rel span{color:var(--muted)}\n.p-doc-item{border-bottom-color:rgba(255,255,255,.06)}\n.p-doc-item .m b{color:var(--ink)}\n.p-doc-item .m span{color:var(--muted)}\n#kbView{flex:1;min-height:0;overflow:auto;padding:18px}\n.kb-cards{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:13px}\n.kb-card{display:flex;gap:13px;align-items:center;height:63px;padding:0 13px;border:.5px solid rgba(255,255,255,.10);\n border-radius:10px;background:#232324;text-align:left;cursor:pointer;color:var(--ink)}\n.kb-card:hover{background:#262629}\n.kb-card .plate{width:22px;height:22px;border-radius:6px;display:flex;align-items:center;justify-content:center;font-size:13px;flex:0 0 auto}\n.kb-card b{display:block;font-size:13.5px;color:var(--ink);font-weight:600}\n.kb-card small{display:block;font-size:11.5px;color:var(--muted);margin-top:2px}\n.kb-tabs{display:flex;gap:8px;margin:16px 0 6px;border-bottom:.5px solid rgba(255,255,255,.08)}\n.kb-tab{padding:8px 10px;font-size:12.5px;color:var(--muted);background:none;border:0;cursor:pointer;border-bottom:2px solid transparent}\n.kb-tab.active{color:var(--ink);border-bottom-color:var(--blue)}\n.kb-table{width:100%;border-collapse:collapse;font-size:12.5px}\n.kb-table th{text-align:left;font-weight:500;color:#7f838a;font-size:11px;padding:8px 10px;border-bottom:.5px solid rgba(255,255,255,.08)}\n.kb-table td{padding:9px 10px;border-bottom:.5px solid rgba(255,255,255,.06);color:var(--secondary)}\n.kb-table td.muted{color:var(--muted)}\n.kb-table tr:hover td{background:rgba(255,255,255,.03)}\n[hidden]{display:none !important}\n@media (max-width:900px){#rail{display:none}}\n</style>\n<style>\n/* ---- embedding page: no rail, no page header; the plugin owns both ---- */\n#tree { display: none !important; }\n#stage { left: 0 !important; }\n#controls { left: 18px !important; }\n#zoomLabel { left: 62px !important; }\n#main { width: 100%; }\n#kg-empty { position: absolute; inset: 0; z-index: 8; display: flex; flex-direction: column;\n align-items: center; justify-content: center; gap: 6px; background: #1a1a1c; color: #8a8d95;\n font-family: var(--sans); text-align: center; padding: 24px; }\n#kg-empty strong { font-size: 14px; font-weight: 600; color: #cfd3d6; }\n#kg-empty span { font-size: 12px; }\n</style>\n<style>\n/* ---- host theme bridge ----\n The canvas is a separate document, so it cannot inherit the host's custom\n properties. The parent posts every --dsw-alias-* value below into this page and\n writes it on :root. These fallbacks are only the first-paint values before that\n message lands; the live values always come from the host. */\n:root {\n --bg: var(--dsw-alias-bg-base, #fff);\n --bg-soft: var(--dsw-alias-bg-layer-1, #f6f7f9);\n --surface: var(--dsw-alias-bg-layer-2, #fff);\n --ink: var(--dsw-alias-label-primary, #0f1115);\n --ink-2: var(--dsw-alias-label-secondary, #3c3f47);\n --secondary: var(--dsw-alias-label-secondary, #61666b);\n /* 80% tertiary + 20% primary keeps the third level distinguishable while\n reaching 4.5:1 on the light surface (the raw light tertiary does not). */\n --muted: color-mix(in srgb, var(--dsw-alias-label-tertiary, #81858c) 80%, var(--dsw-alias-label-primary, #0f1115));\n --line: var(--dsw-alias-border-l2, rgba(0, 0, 0, .10));\n --line-2: var(--dsw-alias-border-l1, rgba(0, 0, 0, .06));\n --blue: var(--dsw-alias-state-business-primary, #4176e6);\n /* Accent text needs 4.5:1, and the raw link token is 4.2:1 on white. A 78/22 mix\n with the primary ink keeps the brand hue while clearing the body-text floor. */\n --blue-deep: color-mix(in srgb, var(--dsw-alias-state-business-primary, #4176e6) 78%, var(--dsw-alias-label-primary, #0f1115));\n --blue-soft: color-mix(in srgb, var(--dsw-alias-state-business-primary, #4176e6) 16%, transparent);\n --green: var(--dsw-alias-state-success-primary, #22c55e);\n --amber: var(--dsw-alias-state-warn-primary, #f59e0b);\n --red: var(--dsw-alias-state-error-primary, #dc2626);\n --red-deep: color-mix(in srgb, var(--dsw-alias-state-error-primary, #dc2626) 80%, var(--dsw-alias-label-primary, #0f1115));\n --red-soft: color-mix(in srgb, var(--dsw-alias-state-error-primary, #dc2626) 12%, transparent);\n --shadow: var(--dsw-elevation-panel, 0 1px 2px rgba(0, 0, 0, .10));\n --stage-bg: color-mix(in srgb, var(--dsw-alias-bg-base, #fff) 96%, var(--dsw-alias-label-primary, #0f1115));\n --soft: color-mix(in srgb, var(--dsw-alias-label-primary, #0f1115) 6%, transparent);\n --dot: color-mix(in srgb, var(--dsw-alias-label-primary, #0f1115) 9%, transparent);\n --edge: color-mix(in srgb, var(--dsw-alias-label-primary, #0f1115) 24%, transparent);\n --edge-soft: color-mix(in srgb, var(--dsw-alias-label-primary, #0f1115) 14%, transparent);\n}\n\n#stage {\n background:\n radial-gradient(900px 620px at 50% 38%, color-mix(in srgb, var(--surface) 60%, transparent), transparent 70%),\n var(--stage-bg) !important;\n}\n#stage::before { background-image: radial-gradient(var(--dot) 1px, transparent 1px) !important; }\n#kg-empty { background: var(--stage-bg) !important; color: var(--muted) !important; }\n#kg-empty strong { color: var(--ink) !important; }\n.card:focus-visible, #controls button:focus-visible { outline-color: var(--blue) !important; }\n.p-doc-item img { border-color: var(--line) !important; }\n.card { background: var(--surface) !important; border-color: var(--line) !important; box-shadow: var(--shadow) !important; }\n.card:hover { border-color: color-mix(in srgb, var(--ink) 22%, transparent) !important; }\n.card.selected { border-color: var(--blue) !important; box-shadow: 0 0 0 2px var(--blue-soft), var(--shadow) !important; }\n/* Dimming is focus, not disappearance: 32% made secondary text unreadable. */\n.card.dim { opacity: .55 !important; }\n.card h3 { color: var(--ink) !important; }\n.one { color: var(--secondary) !important; font-size: 13px; line-height: 1.6; }\n.tags span {\n background: var(--soft) !important; border-color: var(--line-2) !important;\n color: var(--secondary) !important; font-size: 11px; padding: 2px 7px;\n}\n.dots i { background: var(--line) !important; }\n.dots i.on { background: var(--ink) !important; }\n.doc { border-color: var(--line) !important; box-shadow: var(--shadow) !important; }\n.doc-empty { border-color: var(--line) !important; color: var(--muted) !important; background: var(--bg-soft) !important; }\n.docGenerated {\n display: flex; flex-direction: column; gap: 3px; padding: 7px 8px;\n background: var(--surface) !important; color: var(--ink);\n border: 1px solid var(--line) !important; border-radius: 6px;\n overflow: hidden;\n}\n.docGenerated .docMark {\n color: var(--blue-deep); font: 600 7.5px/1 var(--mono); letter-spacing: .08em;\n}\n.docGenerated b {\n color: var(--ink); font-size: 8.5px; line-height: 1.25; font-weight: 600;\n overflow-wrap: anywhere; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden;\n}\n.docGenerated i { margin-top: auto; color: var(--muted); font: normal 7px/1 var(--sans); }\n.docGenerated.wide { gap: 4px; padding: 9px 11px; }\n.docGenerated.wide .docMark { font-size: 9px; }\n.docGenerated.wide b { font-size: 12px; -webkit-line-clamp: 2; }\n.docGenerated.wide i { font-size: 8px; }\n.edge { stroke: var(--edge) !important; }\n.edge.cross { stroke: var(--edge-soft) !important; }\n.edge.hot { stroke: var(--blue) !important; }\n.pill rect { fill: var(--surface) !important; stroke: var(--line) !important; }\n.pill text { fill: var(--secondary) !important; }\n.pill.hot rect { fill: var(--blue-soft) !important; stroke: var(--blue) !important; }\n.pill.hot text { fill: var(--blue-deep) !important; }\n#controls button {\n background: var(--surface) !important; border-color: var(--line) !important;\n color: var(--ink-2) !important; box-shadow: var(--shadow) !important;\n}\n#controls button:hover { background: var(--bg-soft) !important; color: var(--ink) !important; }\n#controls button.on { background: var(--blue) !important; border-color: var(--blue) !important; color: var(--bg) !important; }\n#zoomLabel { color: var(--muted) !important; background: none !important; border: 0 !important;\n padding: 2px 4px !important; cursor: pointer; font-family: var(--mono); }\n#zoomLabel:hover { color: var(--ink) !important; }\n#panel { background: var(--surface) !important; border-left-color: var(--line) !important;\n box-shadow: -8px 0 28px color-mix(in srgb, var(--ink) 12%, transparent) !important; }\n#close { background: var(--surface) !important; border-color: var(--line) !important; color: var(--muted) !important; }\n#close:hover { background: var(--bg-soft) !important; color: var(--ink) !important; }\n.p-head { border-bottom-color: var(--line-2) !important; }\n.p-kicker { color: var(--muted) !important; }\n.p-head h2 { color: var(--ink) !important; }\n.p-field b { color: var(--muted) !important; }\n.p-field span, .p-doc { color: var(--secondary) !important; }\n.p-rel-title { color: var(--muted) !important; }\n.rel { background: var(--soft) !important; border-color: var(--line-2) !important; }\n.rel:hover { background: var(--bg-soft) !important; border-color: var(--line) !important; }\n.rel b { color: var(--ink) !important; }\n.rel span { color: var(--secondary) !important; }\n.p-docs { color: var(--muted) !important; }\n.p-doc-item { border-bottom-color: var(--line-2) !important; }\n.p-doc-item .m b { color: var(--ink) !important; }\n.p-doc-item .m span { color: var(--muted) !important; }\n.p-doc-thumb {\n display: flex; align-items: center; justify-content: center; flex: 0 0 auto;\n width: 34px; height: 46px; border-radius: 4px;\n border: 1px solid var(--line); background: var(--soft); color: var(--blue-deep);\n font: 600 8px/1 var(--mono); letter-spacing: .06em;\n}\n.p-doc h2, .p-doc h3 { color: var(--ink) !important; }\n.p-doc code { background: var(--soft) !important; border-color: var(--line-2) !important; }\n.p-doc pre { background: var(--bg) !important; border-color: var(--line-2) !important; }\n</style>\n</head>\n<body data-doc-layout=\"landscape\" data-view=\"graph\">\n<main id=\"main\">\n <div id=\"kg-crumb\" hidden></div>\n <div id=\"stage\">\n <div id=\"world\">\n <svg id=\"edges\" width=\"4200\" height=\"3200\" viewBox=\"0 0 4200 3200\" aria-hidden=\"true\"></svg>\n </div>\n </div>\n <div id=\"controls\" role=\"group\" aria-label=\"画布控制\">\n <button id=\"zin\" aria-label=\"放大\">+</button>\n <button id=\"zout\" aria-label=\"缩小\">−</button>\n <button id=\"fit\" aria-label=\"适应画布\">⤢</button>\n <button id=\"cross\" aria-label=\"显示交叉关系\" title=\"显示交叉关系\">⇄</button>\n <button id=\"relayout\" aria-label=\"重排\" title=\"重排\">↺</button>\n </div>\n <button id=\"zoomLabel\" type=\"button\" aria-label=\"重置缩放为 100%\" title=\"重置缩放为 100%\">100%</button>\n <div id=\"kg-empty\" hidden><strong>还没有可用的图谱</strong><span>在「知识图谱」文件夹里建好主题后,画布会出现在这里。</span></div>\n</main>\n\n<aside id=\"panel\" aria-label=\"主题详情\" aria-hidden=\"true\">\n <div class=\"p-head\">\n <div>\n <div class=\"p-kicker\" id=\"p-kicker\"></div>\n <h2 id=\"p-title\"></h2>\n </div>\n <button id=\"close\" aria-label=\"关闭\">×</button>\n </div>\n <div class=\"p-body\" id=\"p-body\"></div>\n</aside>\n<script>\nconst DATA = { graphs: [] };\n\n(function(){\n \"use strict\";\n const stage = document.getElementById('stage');\n const world = document.getElementById('world');\n const svg = document.getElementById('edges');\n const panel = document.getElementById('panel');\n const zoomLabel = document.getElementById('zoomLabel');\n\n const NS = 'http://www.w3.org/2000/svg';\n let topics = [];\n let links = [];\n let byId = new Map();\n let activeGraph = 0;\n let viewMode = 'graph';\n const cardEl = new Map();\n const view = {x:0, y:0, s:1};\n const CARD_W = 300, H_GAP = 110, V_GAP = 34, PAD = 40;\n const LAND = document.body.dataset.docLayout === 'landscape';\n\n let mode = null;\n let activeTopic = null;\n let activeLink = null;\n let userMoved = false;\n let children = new Map();\n let parentOf = new Map();\n let treeKeys = new Set();\n let pos = new Map();\n let heights = new Map(), subH = new Map();\n let showCross = false;\n let layoutRootId = null;\n\n function esc(s){\n return String(s == null ? '' : s).replace(/[&<>\"]/g, function(c){\n return {'&':'&amp;','<':'&lt;','>':'&gt;','\"':'&quot;'}[c];\n });\n }\n function statusText(s){ return s === 'active' ? '进行中' : s === 'paused' ? '暂停' : '已完成'; }\n // Provenance chips are pure presentation. The host has already permission-filtered\n // the payload, so a badge never gates or hides a document.\n function badgeItems(item){\n const items = [];\n if (item && (item.origin === 'ai' || item.origin === 'mixed')) {\n items.push({kind:'ai', label:'AI 生成', title:item.origin === 'mixed' ? '人工与 AI 混合生成的内容' : 'AI 生成内容;发布时必须保留来源标签'});\n }\n if (item && (item.reviewStatus === 'reviewed' || item.reviewStatus === 'approved')) {\n items.push({kind:'reviewed', label:'已审核', title:item.reviewStatus === 'approved' ? '已审核并批准' : '已审核'});\n }\n if (item && item.authority === 'redline') {\n items.push({kind:'redline', label:'红线', title:'红线:只能订阅,不可内化或覆盖'});\n }\n return items;\n }\n function badgesHtml(item){\n const items = badgeItems(item);\n if (!items.length) return '';\n return '<span class=\"p-badges\" role=\"group\" aria-label=\"内容标签\">' + items.map(function(b){\n return '<span class=\"p-badge ' + b.kind + '\" title=\"' + b.title + '\" aria-label=\"' + b.label + '\">[' + b.label + ']</span>';\n }).join('') + '</span>';\n }\n function linkKey(l){ return l.a + '--' + l.b; }\n function pairKey(a, b){ return a < b ? a + '--' + b : b + '--' + a; }\n\n // ---------- cards ----------\n\n // Documents in the knowledge tree have no stored thumbnail. A generated cover\n // uses the host's own theme variables (set from the parent document), so a light\n // host gets ink-on-white covers and a dark host gets the inverse. No bitmap and\n // no fixed palette: the cover is markup, not an image.\n function coverFor(d, idx, wide, w, h, dx, dy, rot, sc, z){\n const style = 'width:' + w + 'px;height:' + h + 'px;--dx:' + dx + 'px;--dy:' + dy +\n 'px;--rot:' + rot + 'deg;--sc:' + sc + ';z-index:' + z;\n if (d.thumb) {\n const src = (wide && d.thumbWide) ? d.thumbWide : d.thumb;\n return '<img class=\"doc\" src=\"' + src + '\" alt=\"' + esc(d.title) + '\" style=\"' + style + '\">';\n }\n const ext = String(d.file || 'doc').split('.').pop().slice(0, 4).toUpperCase();\n return '<div class=\"doc docGenerated' + (wide ? ' wide' : '') + '\" style=\"' + style + '\" title=\"' + esc(d.title) + '\">' +\n '<span class=\"docMark\">' + esc(ext) + '</span>' +\n '<b>' + esc(d.title || d.file || '') + '</b>' +\n '<i>' + esc(d.date || '') + '</i></div>';\n }\n\n // The detail panel renders the same cover inline, at a fixed 34x46 slot.\n function inlineCover(d){\n if (d.thumb) return '<img src=\"' + d.thumb + '\" alt=\"\">';\n const ext = String(d.file || 'doc').split('.').pop().slice(0, 4).toUpperCase();\n return '<span class=\"p-doc-thumb\"><i>' + esc(ext) + '</i></span>';\n }\n\n function buildCard(t){\n const el = document.createElement('article');\n el.className = 'card';\n el.dataset.id = t.id;\n el.tabIndex = 0;\n el.style.left = '0px';\n el.style.top = '0px';\n el.style.visibility = 'hidden';\n el.setAttribute('role', 'button');\n el.setAttribute('aria-label', t.title + ',' + statusText(t.status) + ',深度 ' + t.depth);\n\n const dots = [1,2,3,4,5].map(i =>\n '<i class=\"' + (i <= t.depth ? 'on' : '') + '\"></i>').join('');\n const docs = t.documents || [];\n const shown = docs.slice(0, 4);\n const mid = (shown.length - 1) / 2;\n let docW = 86, docH = 116, step = 31, rotStep = 6.5, dyStep = 2, scStep = 0.03, coverH = 124;\n if (LAND){\n if (shown.length <= 1){ docW = 240; docH = 84; step = 0; rotStep = 0; dyStep = 0; scStep = 0; coverH = 92; }\n else if (shown.length === 2){ docW = 142; docH = 78; step = 58; rotStep = 5; dyStep = 3; scStep = 0.02; coverH = 88; }\n else if (shown.length === 3){ docW = 132; docH = 76; step = 46; rotStep = 4.2; dyStep = 3; scStep = 0.02; coverH = 86; }\n else { docW = 118; docH = 70; step = 42; rotStep = 4; dyStep = 3; scStep = 0.02; coverH = 80; }\n }\n let stack = '';\n shown.forEach(function(d, i){\n const dist = Math.abs(i - mid);\n const dx = (i - mid) * step;\n const dy = dist * dyStep;\n const rot = (i - mid) * rotStep;\n const sc = 1 - dist * scStep;\n const z = 10 - dist;\n stack += coverFor(d, i, shown.length === 1, docW, docH, dx, dy, rot, sc, z);\n });\n if (docs.length > 4) stack += '<span class=\"more\">+' + (docs.length - 4) + '</span>';\n if (!docs.length) stack = '<div class=\"doc-empty\">docs/ 还是空的</div>';\n const tagList = [t.domain].concat(t.tags || []).filter(function(x, i, arr){\n return x && arr.indexOf(x) === i;\n }).slice(0, 4);\n const tags = tagList.map(function(x){ return '<span>' + esc(x) + '</span>'; }).join('');\n\n el.innerHTML =\n '<h3>' + esc(t.title) + badgesHtml(t) + '</h3>' +\n '<div class=\"cover\" style=\"height:' + coverH + 'px\"><div class=\"stack\">' + stack + '</div></div>' +\n '<p class=\"one\">' + esc(t.summary) + '</p>' +\n '<div class=\"tags\">' + tags + '</div>';\n\n el.addEventListener('pointerdown', onCardDown);\n el.addEventListener('keydown', function(e){\n if (e.key === 'Enter' || e.key === ' '){ e.preventDefault(); selectTopic(t.id); }\n });\n world.appendChild(el);\n cardEl.set(t.id, el);\n }\n\n // ---------- spanning tree ----------\n function degree(id){\n return links.filter(function(l){ return l.a === id || l.b === id; }).length;\n }\n function buildTree(rootId){\n children = new Map(); parentOf = new Map(); treeKeys = new Set();\n const visited = new Set([rootId]);\n const queue = [rootId];\n topics.forEach(function(t){ children.set(t.id, []); });\n while (queue.length){\n const id = queue.shift();\n const neighbors = [];\n links.forEach(function(l){\n if (l.a === id && !visited.has(l.b)) neighbors.push(l.b);\n else if (l.b === id && !visited.has(l.a)) neighbors.push(l.a);\n });\n neighbors.sort(function(a, b){ return degree(b) - degree(a); });\n neighbors.forEach(function(n){\n visited.add(n);\n parentOf.set(n, id);\n children.get(id).push(n);\n treeKeys.add(pairKey(id, n));\n queue.push(n);\n });\n }\n topics.forEach(function(t){\n if (!visited.has(t.id)){\n parentOf.set(t.id, rootId);\n children.get(rootId).push(t.id);\n treeKeys.add(pairKey(rootId, t.id));\n visited.add(t.id);\n }\n });\n }\n\n // ---------- mind-map layout ----------\n function calcSub(id){\n const h = heights.get(id) || 200;\n const kids = children.get(id) || [];\n if (!kids.length){ subH.set(id, h); return h; }\n let total = 0;\n kids.forEach(function(k, i){\n total += calcSub(k);\n if (i) total += V_GAP;\n });\n subH.set(id, Math.max(h, total));\n return subH.get(id);\n }\n\n function placeNode(id, x, yTop, dir){\n const h = heights.get(id) || 200;\n const sub = subH.get(id) || h;\n const cy = yTop + sub / 2;\n pos.set(id, {x:x, y:cy - h / 2, dir:dir});\n const kids = children.get(id) || [];\n let cursor = yTop;\n kids.forEach(function(k){\n const kh = subH.get(k) || 200;\n const kx = dir > 0 ? x + CARD_W + H_GAP : x - CARD_W - H_GAP;\n placeNode(k, kx, cursor, dir);\n cursor += kh + V_GAP;\n });\n }\n\n function layout(){\n heights = new Map();\n topics.forEach(function(t){ heights.set(t.id, cardEl.get(t.id).offsetHeight || 200); });\n\n let rootId = topics[0].id, best = -1;\n topics.forEach(function(t){\n const d = degree(t.id);\n if (d > best){ best = d; rootId = t.id; }\n });\n if (byId.has('dsh-enterprise-app')) rootId = 'dsh-enterprise-app';\n layoutRootId = rootId;\n buildTree(rootId);\n calcSub(rootId);\n\n const first = (children.get(rootId) || []).slice();\n first.sort(function(a, b){ return (subH.get(b) || 0) - (subH.get(a) || 0); });\n\n const left = [], right = [];\n let lh = 0, rh = 0;\n first.forEach(function(id){\n if (rh <= lh){ right.push(id); rh += subH.get(id); }\n else { left.push(id); lh += subH.get(id); }\n });\n\n const rootH = heights.get(rootId);\n pos.set(rootId, {x:0, y:-rootH / 2, dir:0});\n\n function placeSide(list, dir){\n let total = 0;\n list.forEach(function(id, i){ total += subH.get(id); if (i) total += V_GAP; });\n let cursor = -total / 2;\n list.forEach(function(id){\n const kh = subH.get(id);\n const x = dir > 0 ? CARD_W + H_GAP : -CARD_W - H_GAP;\n placeNode(id, x, cursor, dir);\n cursor += kh + V_GAP;\n });\n }\n placeSide(left, -1);\n placeSide(right, 1);\n\n let minX = Infinity, minY = Infinity;\n pos.forEach(function(p){ minX = Math.min(minX, p.x); minY = Math.min(minY, p.y); });\n pos.forEach(function(p, id){\n p.x = p.x - minX + PAD;\n p.y = p.y - minY + PAD;\n const t = byId.get(id);\n t.x = p.x; t.y = p.y;\n const el = cardEl.get(id);\n el.style.left = p.x + 'px';\n el.style.top = p.y + 'px';\n el.style.visibility = '';\n });\n }\n\n // ---------- edges & pills ----------\n function center(id){\n const p = pos.get(id), h = heights.get(id) || 200;\n return {x:p.x + CARD_W / 2, y:p.y + h / 2};\n }\n function anchor(id, tx, ty){\n const c = center(id), h = heights.get(id) || 200;\n const dx = tx - c.x, dy = ty - c.y;\n if (!dx && !dy) return c;\n if (Math.abs(dx) * h > Math.abs(dy) * CARD_W){\n const k = (CARD_W / 2) / Math.abs(dx);\n return {x:c.x + dx * k, y:c.y + dy * k};\n }\n const k = (h / 2) / Math.abs(dy);\n return {x:c.x + dx * k, y:c.y + dy * k};\n }\n function qpoint(p0, c, p1, t){\n const u = 1 - t;\n return {x:u*u*p0.x + 2*u*t*c.x + t*t*p1.x, y:u*u*p0.y + 2*u*t*c.y + t*t*p1.y};\n }\n function cpoint(p0, c1, c2, p1, t){\n const u = 1 - t, a = u*u*u, b = 3*u*u*t, c = 3*u*t*t, d = t*t*t;\n return {x:a*p0.x + b*c1.x + c*c2.x + d*p1.x,\n y:a*p0.y + b*c1.y + c*c2.y + d*p1.y};\n }\n function hitsCard(x, y, w, h){\n for (let i = 0; i < topics.length; i++){\n const t = topics[i], th = heights.get(t.id) || 200;\n if (x < t.x + CARD_W + 6 && x + w > t.x - 6 &&\n y < t.y + th + 6 && y + h > t.y - 6) return true;\n }\n return false;\n }\n function freePointOnQuad(p0, c, p1){\n const ts = [0.5, 0.4, 0.6, 0.3, 0.7, 0.22, 0.78];\n for (let i = 0; i < ts.length; i++){\n const p = qpoint(p0, c, p1, ts[i]);\n if (!hitsCard(p.x, p.y)) return p;\n }\n return qpoint(p0, c, p1, 0.5);\n }\n function freePointOnCubic(p0, c1, c2, p1){\n const ts = [0.5, 0.42, 0.58, 0.34, 0.66, 0.26, 0.74];\n for (let i = 0; i < ts.length; i++){\n const p = cpoint(p0, c1, c2, p1, ts[i]);\n if (!hitsCard(p.x, p.y)) return p;\n }\n return cpoint(p0, c1, c2, p1, 0.5);\n }\n\n function overlaps(p, w, placed){\n for (let i = 0; i < placed.length; i++){\n const q = placed[i];\n if (Math.abs(p.x - q.x) < (w + q.w) / 2 + 8 && Math.abs(p.y - q.y) < 24) return true;\n }\n return false;\n }\n function placePill(sample, w, placed){\n const ts = [0.5, 0.56, 0.44, 0.62, 0.38, 0.68, 0.32, 0.74, 0.26, 0.8];\n for (let i = 0; i < ts.length; i++){\n const p = sample(ts[i]);\n if (!hitsCard(p.x - w / 2, p.y - 10, w, 20) && !overlaps(p, w, placed)){\n placed.push({x:p.x, y:p.y, w:w});\n return p;\n }\n }\n const p = sample(0.5);\n placed.push({x:p.x, y:p.y, w:w});\n return p;\n }\n\n function drawEdges(){\n while (svg.firstChild) svg.removeChild(svg.firstChild);\n const placed = [];\n\n links.forEach(function(l){\n const a = byId.get(l.a), b = byId.get(l.b);\n if (!a || !b) return;\n const key = linkKey(l);\n const isTree = treeKeys.has(pairKey(l.a, l.b));\n const isLink = mode === 'link' && activeLink === key;\n const isTopic = mode === 'topic' && (l.a === activeTopic || l.b === activeTopic);\n const hot = isLink || isTopic;\n const cold = !!mode && !hot;\n if (!isTree && !showCross && !hot) return;\n\n let d, sample;\n if (isTree){\n const pid = parentOf.get(l.b) === l.a ? l.a : l.b;\n const cid = pid === l.a ? l.b : l.a;\n const pp = pos.get(pid), pc = center(pid), cc = center(cid);\n const dir = pp.dir || (cc.x >= pc.x ? 1 : -1);\n const x1 = dir > 0 ? pp.x + CARD_W : pp.x;\n const x2 = dir > 0 ? pos.get(cid).x : pos.get(cid).x + CARD_W;\n const y1 = pc.y, y2 = cc.y;\n const bend = Math.max(34, Math.abs(x2 - x1) * 0.42);\n const p0 = {x:x1, y:y1};\n const c1 = {x:x1 + dir * bend, y:y1};\n const c2 = {x:x2 - dir * bend, y:y2};\n const p1 = {x:x2, y:y2};\n d = 'M' + x1 + ',' + y1 + ' C' + c1.x + ',' + c1.y + ' ' + c2.x + ',' + c2.y + ' ' + x2 + ',' + y2;\n sample = function(t){ return cpoint(p0, c1, c2, p1, t); };\n } else {\n const pa = pos.get(l.a), pb = pos.get(l.b);\n let p1, p2, c;\n if (pa.dir === pb.dir && pa.dir !== 0){\n const dir = pa.dir;\n p1 = {x: dir < 0 ? pa.x + CARD_W : pa.x, y: center(l.a).y};\n p2 = {x: dir < 0 ? pb.x + CARD_W : pb.x, y: center(l.b).y};\n const outX = dir < 0 ? Math.max(p1.x, p2.x) + 64 : Math.min(p1.x, p2.x) - 64;\n c = {x: outX, y: (p1.y + p2.y) / 2};\n } else {\n const ca = center(l.a), cb = center(l.b);\n p1 = {x: ca.x, y: pa.y};\n p2 = {x: cb.x, y: pb.y};\n c = {x: (p1.x + p2.x) / 2, y: Math.min(p1.y, p2.y) - 112};\n }\n d = 'M' + p1.x + ',' + p1.y + ' Q' + c.x + ',' + c.y + ' ' + p2.x + ',' + p2.y;\n sample = function(t){ return qpoint(p1, c, p2, t); };\n }\n\n const path = document.createElementNS(NS, 'path');\n path.setAttribute('d', d);\n path.setAttribute('class', 'edge' + (isTree ? '' : ' cross') + (hot ? ' hot' : cold ? ' cold' : ''));\n svg.appendChild(path);\n\n const label = l.label || (a.title + ' ↔ ' + b.title);\n const w = Math.max(42, label.length * 10.8 + 16);\n const pillAt = placePill(sample, w, placed);\n\n const g = document.createElementNS(NS, 'g');\n g.setAttribute('class', 'pill' + (hot ? ' hot' : cold ? ' cold' : ''));\n g.setAttribute('data-key', key);\n g.setAttribute('tabindex', '0');\n g.setAttribute('role', 'button');\n g.setAttribute('aria-label', '关系:' + label);\n\n const rect = document.createElementNS(NS, 'rect');\n rect.setAttribute('x', pillAt.x - w / 2); rect.setAttribute('y', pillAt.y - 10);\n rect.setAttribute('width', w); rect.setAttribute('height', 20);\n rect.setAttribute('rx', 10);\n const text = document.createElementNS(NS, 'text');\n text.setAttribute('x', pillAt.x); text.setAttribute('y', pillAt.y + 3.6);\n text.setAttribute('text-anchor', 'middle');\n text.textContent = label;\n\n g.appendChild(rect); g.appendChild(text);\n g.addEventListener('click', function(e){ e.stopPropagation(); selectLink(key); });\n g.addEventListener('keydown', function(e){\n if (e.key === 'Enter' || e.key === ' '){ e.preventDefault(); selectLink(key); }\n });\n svg.appendChild(g);\n });\n }\n\n // ---------- camera ----------\n function apply(){\n world.style.transform = 'translate(' + view.x + 'px,' + view.y + 'px) scale(' + view.s + ')';\n zoomLabel.textContent = Math.round(view.s * 100) + '%';\n }\n function clampScale(s){ return Math.max(0.22, Math.min(2.0, s)); }\n function zoomAt(px, py, k){\n const s2 = clampScale(view.s * k);\n if (s2 === view.s) return;\n view.x = px - (px - view.x) * (s2 / view.s);\n view.y = py - (py - view.y) * (s2 / view.s);\n view.s = s2;\n apply(); userMoved = true;\n }\n function bbox(){\n let x1 = Infinity, y1 = Infinity, x2 = -Infinity, y2 = -Infinity;\n topics.forEach(function(t){\n const h = heights.get(t.id) || 200;\n x1 = Math.min(x1, t.x); y1 = Math.min(y1, t.y);\n x2 = Math.max(x2, t.x + CARD_W); y2 = Math.max(y2, t.y + h);\n });\n return {x1:x1, y1:y1, x2:x2, y2:y2};\n }\n function fit(animate){\n const b = bbox();\n const pad = 70;\n const vw = stage.clientWidth, vh = stage.clientHeight;\n const s = clampScale(Math.min((vw - pad * 2) / (b.x2 - b.x1), (vh - pad * 2) / (b.y2 - b.y1), 1));\n const nx = (vw - (b.x2 - b.x1) * s) / 2 - b.x1 * s;\n const ny = (vh - (b.y2 - b.y1) * s) / 2 - b.y1 * s;\n if (animate) tweenTo(nx, ny, s); else { view.x = nx; view.y = ny; view.s = s; apply(); }\n userMoved = false;\n }\n let raf = null;\n function tweenTo(x2, y2, s2){\n cancelAnimationFrame(raf);\n const x1 = view.x, y1 = view.y, s1 = view.s, t0 = performance.now(), dur = 320;\n function step(now){\n const p = Math.min(1, (now - t0) / dur);\n const e = 1 - Math.pow(1 - p, 3);\n view.x = x1 + (x2 - x1) * e;\n view.y = y1 + (y2 - y1) * e;\n view.s = s1 + (s2 - s1) * e;\n apply();\n if (p < 1) raf = requestAnimationFrame(step);\n }\n raf = requestAnimationFrame(step);\n }\n function centerOnScale(id, s, animate){\n const t = byId.get(id); if (!t) return;\n const h = heights.get(id) || 200;\n const x = stage.clientWidth / 2 - (t.x + CARD_W / 2) * s;\n const y = stage.clientHeight / 2 - (t.y + h / 2) * s;\n if (animate) tweenTo(x, y, s);\n else { view.x = x; view.y = y; view.s = s; apply(); }\n userMoved = true;\n }\n\n // A topic jump keeps whatever zoom the reader chose; only the explicit reset\n // control and a graph switch change the scale.\n function centerOn(id){\n centerOnScale(id, view.s, true);\n }\n\n function resetZoom(){\n const target = (mode === 'topic' && activeTopic) ? activeTopic : layoutRootId;\n centerOnScale(target, 1, true);\n }\n\n // ---------- pan & zoom ----------\n let panning = false, panMoved = false, px = 0, py = 0;\n stage.addEventListener('pointerdown', function(e){\n if (e.target.closest('.card') || e.target.closest('.pill') || e.target.closest('#panel')) return;\n panning = true; panMoved = false; px = e.clientX; py = e.clientY;\n stage.classList.add('grabbing');\n stage.setPointerCapture(e.pointerId);\n });\n stage.addEventListener('pointermove', function(e){\n if (!panning) return;\n if (Math.abs(e.clientX - px) + Math.abs(e.clientY - py) > 3) panMoved = true;\n view.x += e.clientX - px; view.y += e.clientY - py;\n px = e.clientX; py = e.clientY;\n apply(); userMoved = true;\n });\n function endPan(e){\n if (!panning) return;\n panning = false; stage.classList.remove('grabbing');\n try { stage.releasePointerCapture(e.pointerId); } catch(_){}\n if (!panMoved && mode) closePanel();\n }\n stage.addEventListener('pointerup', endPan);\n stage.addEventListener('pointercancel', endPan);\n stage.addEventListener('wheel', function(e){\n e.preventDefault();\n zoomAt(e.clientX, e.clientY, Math.exp(-e.deltaY * 0.0011));\n }, {passive:false});\n document.getElementById('zin').addEventListener('click', function(){\n zoomAt(stage.clientWidth / 2, stage.clientHeight / 2, 1.22);\n });\n document.getElementById('zout').addEventListener('click', function(){\n zoomAt(stage.clientWidth / 2, stage.clientHeight / 2, 1 / 1.22);\n });\n document.getElementById('fit').addEventListener('click', function(){ fit(true); });\n document.getElementById('zoomLabel').addEventListener('click', resetZoom);\n document.getElementById('relayout').addEventListener('click', function(){\n layout(); fit(true); drawEdges();\n });\n document.getElementById('cross').addEventListener('click', function(){\n showCross = !showCross;\n this.classList.toggle('on', showCross);\n this.setAttribute('aria-pressed', showCross ? 'true' : 'false');\n drawEdges();\n });\n stage.addEventListener('dblclick', function(e){ if (!e.target.closest('.card')) fit(true); });\n\n // ---------- card drag ----------\n let drag = null;\n function onCardDown(e){\n if (e.button !== 0) return;\n e.stopPropagation();\n const id = e.currentTarget.dataset.id;\n const t = byId.get(id);\n const el = cardEl.get(id);\n drag = {id:id, sx:e.clientX, sy:e.clientY, ox:t.x, oy:t.y, moved:false, el:el};\n el.classList.add('dragging');\n window.addEventListener('pointermove', onDragMove);\n window.addEventListener('pointerup', onDragUp);\n }\n function onDragMove(e){\n if (!drag) return;\n const dx = (e.clientX - drag.sx) / view.s;\n const dy = (e.clientY - drag.sy) / view.s;\n if (Math.abs(dx) + Math.abs(dy) > 3) drag.moved = true;\n const t = byId.get(drag.id);\n t.x = drag.ox + dx; t.y = drag.oy + dy;\n const p = pos.get(drag.id); p.x = t.x; p.y = t.y;\n drag.el.style.left = t.x + 'px';\n drag.el.style.top = t.y + 'px';\n drawEdges();\n }\n function onDragUp(){\n window.removeEventListener('pointermove', onDragMove);\n window.removeEventListener('pointerup', onDragUp);\n if (!drag) return;\n drag.el.classList.remove('dragging');\n const id = drag.id, moved = drag.moved;\n drag = null;\n if (!moved) selectTopic(id);\n userMoved = true;\n }\n\n // ---------- selection ----------\n function paint(){\n cardEl.forEach(function(el, cid){\n let sel = false, dim = false;\n if (mode === 'topic'){ sel = cid === activeTopic; dim = !sel; }\n else if (mode === 'link'){\n const l = links.find(function(x){ return linkKey(x) === activeLink; });\n sel = !!l && (cid === l.a || cid === l.b);\n dim = !sel;\n }\n el.classList.toggle('selected', sel);\n el.classList.toggle('dim', dim);\n });\n }\n function notifySelection(topicId){\n try {\n parent.postMessage({\n type: 'kg:selection',\n graphId: (DATA.graphs[activeGraph] || {}).id || null,\n topicId: topicId || null\n }, '*');\n } catch (_) {}\n }\n function selectTopic(id){\n if (mode === 'topic' && activeTopic === id){ closePanel(); return; }\n mode = 'topic'; activeTopic = id; activeLink = null;\n paint(); drawEdges(); openTopicPanel(id); setHash(id);\n notifySelection(id);\n }\n function selectLink(key){\n if (mode === 'link' && activeLink === key){ closePanel(); return; }\n mode = 'link'; activeLink = key; activeTopic = null;\n paint(); drawEdges(); openLinkPanel(key); setHash(key);\n }\n function closePanel(){\n mode = null; activeTopic = null; activeLink = null;\n paint(); drawEdges();\n panel.classList.remove('open');\n panel.setAttribute('aria-hidden', 'true');\n document.body.classList.remove('panel-open');\n setHash(null);\n notifySelection(null);\n }\n document.getElementById('close').addEventListener('click', closePanel);\n document.addEventListener('keydown', function(e){ if (e.key === 'Escape') closePanel(); });\n\n function showPanel(kicker, title, html){\n document.getElementById('p-kicker').textContent = kicker;\n document.getElementById('p-title').textContent = title;\n const body = document.getElementById('p-body');\n body.innerHTML = html;\n body.scrollTop = 0;\n body.querySelectorAll('.rel').forEach(function(btn){\n btn.addEventListener('click', function(){\n const to = btn.dataset.to;\n selectTopic(to); centerOn(to);\n });\n });\n body.querySelectorAll('.p-doc-item[data-doc-path]').forEach(function(item){\n item.addEventListener('click', function(){\n try { parent.postMessage({ type: 'kg:open-document', path: item.dataset.docPath }, '*'); } catch (_) {}\n });\n });\n panel.classList.add('open');\n panel.setAttribute('aria-hidden', 'false');\n document.body.classList.add('panel-open');\n }\n function inline(s){\n s = esc(s);\n s = s.replace(/`([^`]+)`/g, '<code>$1</code>');\n s = s.replace(/\\*\\*([^*]+)\\*\\*/g, '<strong>$1</strong>');\n s = s.replace(/\\[([^\\]]+)\\]\\(([^)]+)\\)/g, '<a href=\"$2\" target=\"_blank\" rel=\"noopener\">$1</a>');\n return s;\n }\n function renderMarkdown(md){\n const lines = String(md || '').split('\\n');\n let html = '', inCode = false, code = [], list = null;\n function closeList(){ if (list){ html += '</' + list + '>'; list = null; } }\n lines.forEach(function(line){\n if (/^```/.test(line)){\n if (inCode){ html += '<pre><code>' + esc(code.join('\\n')) + '</code></pre>'; code = []; inCode = false; }\n else { closeList(); inCode = true; }\n return;\n }\n if (inCode){ code.push(line); return; }\n if (!line.trim()){ closeList(); return; }\n let m;\n if ((m = line.match(/^(#{1,3})\\s+(.*)$/))){\n closeList();\n const lv = Math.min(3, m[1].length);\n html += '<h' + lv + '>' + inline(m[2]) + '</h' + lv + '>';\n } else if ((m = line.match(/^\\s*[-*]\\s+(.*)$/))){\n if (list !== 'ul'){ closeList(); html += '<ul>'; list = 'ul'; }\n html += '<li>' + inline(m[1]) + '</li>';\n } else if ((m = line.match(/^\\s*\\d+\\.\\s+(.*)$/))){\n if (list !== 'ol'){ closeList(); html += '<ol>'; list = 'ol'; }\n html += '<li>' + inline(m[1]) + '</li>';\n } else if ((m = line.match(/^>\\s?(.*)$/))){\n closeList();\n html += '<blockquote>' + inline(m[1]) + '</blockquote>';\n } else {\n closeList();\n html += '<p>' + inline(line) + '</p>';\n }\n });\n if (inCode) html += '<pre><code>' + esc(code.join('\\n')) + '</code></pre>';\n closeList();\n return html;\n }\n function field(k, v){\n return '<div class=\"p-field\"><b>' + k + '</b><span>' + esc(v || '未登记') + '</span></div>';\n }\n function openTopicPanel(id){\n const t = byId.get(id);\n const rels = links.filter(function(l){ return l.a === id || l.b === id; });\n let html = '<div class=\"p-doc\">' + renderMarkdown(t.body || t.summary || '') + '</div>';\n if (t.documents && t.documents.length){\n html += '<div class=\"p-rel-title\">文档 · ' + t.documents.length + ' 篇</div>';\n t.documents.forEach(function(d){\n html += '<div class=\"p-doc-item\" data-doc-path=\"' + esc(d.path) + '\" role=\"button\" tabindex=\"0\" style=\"cursor:pointer\">' + inlineCover(d) + '<div class=\"m\">' +\n '<b>' + esc(d.title) + badgesHtml(d) + '</b><span>' + esc(d.file) + ' · ' + esc(d.date) + '</span></div></div>';\n });\n }\n html += '<div class=\"p-rel-title\">关系 · ' + rels.length + ' 篇</div>';\n rels.forEach(function(l){\n const other = l.a === id ? l.b : l.a;\n const o = byId.get(other);\n html += '<button class=\"rel\" data-to=\"' + esc(other) + '\"><b>' + esc(o ? o.title : other) +\n '</b><span>' + esc(l.body || '') + '</span></button>';\n });\n if (!rels.length) html += '<div class=\"p-docs\">还没有关系文档。孤立的线价值很低。</div>';\n html += '<div class=\"p-docs\">文档:' + ((t.documents || []).length) + ' 个文件</div>';\n showPanel((t.domain ? t.domain + ' · ' : '') + statusText(t.status) + ' · depth ' + t.depth + '/5', t.title, html);\n }\n function openLinkPanel(key){\n const l = links.find(function(x){ return linkKey(x) === key; });\n if (!l) return;\n const a = byId.get(l.a), b = byId.get(l.b);\n let html = field('关系', l.body);\n html += '<div class=\"p-rel-title\">两端</div>';\n html += '<button class=\"rel\" data-to=\"' + esc(l.a) + '\"><b>' + esc(a ? a.title : l.a) +\n '</b><span>' + esc(a ? a.summary : '') + '</span></button>';\n html += '<button class=\"rel\" data-to=\"' + esc(l.b) + '\"><b>' + esc(b ? b.title : l.b) +\n '</b><span>' + esc(b ? b.summary : '') + '</span></button>';\n showPanel('关系文档' + (l.updated ? ' · ' + l.updated : ''),\n (a ? a.title : l.a) + ' ↔ ' + (b ? b.title : l.b), html);\n }\n function setHash(v){\n try { history.replaceState(null, '', v ? '#' + v : location.pathname + location.search); } catch(_){}\n }\n\n // ---------- graph switching ----------\n /** Floating breadcrumb: graph scope / group / graph name. Parent segments close\n the detail panel and return to the graph root; there is no separate list view. */\n function renderCrumb(){\n const el = document.getElementById('kg-crumb');\n if (!el) return;\n const g = DATA.graphs[activeGraph];\n if (!g) { el.hidden = true; return; }\n const parts = ['<button class=\"seg\" data-level=\"0\">知识图谱</button>'];\n if (g.group) parts.push('<span class=\"sep\">/</span><button class=\"seg\" data-level=\"1\">' + esc(g.group) + '</button>');\n parts.push('<span class=\"sep\">/</span><b>' + esc(g.name) + '</b>');\n el.innerHTML = parts.join('');\n el.hidden = false;\n el.querySelectorAll('button[data-level]').forEach(function(btn){\n btn.addEventListener('click', function(){\n closePanel();\n centerOnScale(layoutRootId, view.s, true);\n });\n });\n }\n\n function loadGraph(idx){\n const g = DATA.graphs[idx];\n if (!g) return;\n closePanel();\n activeGraph = idx;\n topics = g.topics;\n links = g.links;\n byId = new Map(topics.map(function(t){ return [t.id, t]; }));\n cardEl.forEach(function(el){ el.remove(); });\n cardEl.clear();\n while (svg.firstChild) svg.removeChild(svg.firstChild);\n heights = new Map(); subH = new Map(); pos = new Map();\n\n topics.forEach(buildCard);\n layout();\n apply();\n renderCrumb();\n\n requestAnimationFrame(function(){\n // First entry and every graph switch start at 1:1. The reader asked for a\n // true-scale canvas; fitting the whole graph on open made every card's\n // 12-13px copy render at 64%. Panning still reaches the rest.\n centerOnScale(layoutRootId, 1, false);\n drawEdges();\n });\n }\n\n // ---------- the embedding host ----------\n const emptyEl = document.getElementById('kg-empty');\n\n // The host's alias tokens, read from the parent document (same origin) and kept\n // live by the panel's postMessage. Reading the parent on boot avoids a flash of\n // the wrong scheme before the first message; the message is still required for\n // a later theme switch.\n const THEME_TOKENS = [\n '--dsw-alias-bg-base', '--dsw-alias-bg-layer-1', '--dsw-alias-bg-layer-2',\n '--dsw-alias-label-primary', '--dsw-alias-label-secondary', '--dsw-alias-label-tertiary',\n '--dsw-alias-border-l1', '--dsw-alias-border-l2',\n '--dsw-alias-state-business-primary', '--dsw-alias-link',\n '--dsw-alias-state-success-primary', '--dsw-alias-state-warn-primary',\n '--dsw-elevation-panel'\n ];\n\n function readHostTheme(){\n try {\n const doc = parent.document;\n const bodyStyle = parent.getComputedStyle(doc.body);\n const rootStyle = parent.getComputedStyle(doc.documentElement);\n const tokens = {};\n THEME_TOKENS.forEach(function(name){\n const value = (bodyStyle.getPropertyValue(name) || rootStyle.getPropertyValue(name) || '').trim();\n if (value !== '') tokens[name] = value;\n });\n return { tokens: tokens, dark: doc.body.hasAttribute('data-ds-dark-theme') };\n } catch (_) {\n return null;\n }\n }\n\n function applyTheme(theme){\n if (!theme || !theme.tokens) return;\n const root = document.documentElement;\n Object.keys(theme.tokens).forEach(function(name){\n root.style.setProperty(name, theme.tokens[name]);\n });\n root.style.colorScheme = theme.dark ? 'dark' : 'light';\n document.body.toggleAttribute('data-ds-dark-theme', !!theme.dark);\n }\n\n applyTheme(readHostTheme());\n\n function showEmpty(show){\n if (emptyEl) emptyEl.hidden = !show;\n const stageEl = document.getElementById('stage');\n if (stageEl) stageEl.style.visibility = show ? 'hidden' : 'visible';\n const controlsEl = document.getElementById('controls');\n if (controlsEl) controlsEl.hidden = show;\n const zoomEl = document.getElementById('zoomLabel');\n if (zoomEl) zoomEl.hidden = show;\n }\n\n function postReady(){\n try { parent.postMessage({ type: 'kg:ready' }, '*'); } catch (_) {}\n }\n\n function applyPayload(payload){\n if (!payload || !Array.isArray(payload.graphs)) return;\n DATA.graphs = payload.graphs;\n if (!DATA.graphs.length){\n showEmpty(true);\n postReady();\n return;\n }\n showEmpty(false);\n const wanted = payload.activeGraphId\n ? DATA.graphs.findIndex(function(g){ return g.id === payload.activeGraphId; })\n : -1;\n const idx = wanted >= 0 ? wanted : 0;\n loadGraph(idx);\n if (payload.selectedTopicId){\n requestAnimationFrame(function(){ focusTopic(payload.selectedTopicId); });\n }\n postReady();\n }\n\n function focusTopic(id){\n const t = byId.get(id);\n if (!t) return;\n selectTopic(id);\n centerOn(id);\n }\n\n function selectGraphById(id){\n const idx = DATA.graphs.findIndex(function(g){ return g.id === id; });\n if (idx < 0) return;\n showEmpty(false);\n loadGraph(idx);\n }\n\n window.addEventListener('message', function(event){\n const msg = event.data || {};\n if (msg.type === 'kg:set-graphs') applyPayload(msg);\n else if (msg.type === 'kg:select-graph') selectGraphById(msg.graphId);\n else if (msg.type === 'kg:select-topic') focusTopic(msg.topicId);\n else if (msg.type === 'kg:theme') applyTheme(msg);\n });\n\n showEmpty(true);\n postReady();\n window.addEventListener('resize', function(){\n if (!userMoved) centerOnScale(layoutRootId, view.s, false);\n drawEdges();\n });\n\n window.__KG_VIEW__ = {data:DATA, selectTopic:selectTopic, selectLink:selectLink, fit:fit};\n})();\n<\/script>\n</body>\n</html>\n";
2912
+ const GRAPH_CANVAS_HTML = "<!DOCTYPE html>\n<html lang=\"zh-CN\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>知识图谱 · 画布</title>\n<style>\n:root{\n --bg:#fbfbfc;\n --bg-soft:#f6f7f9;\n --surface:#ffffff;\n --ink:#0f1115;\n --ink-2:#3c3f47;\n --secondary:#61666b;\n --muted:#81858c;\n --line:rgba(0,0,0,.10);\n --line-2:rgba(0,0,0,.06);\n --blue:#4176e6;\n --blue-deep:#2555c4;\n --blue-soft:#eef4ff;\n --green:#22c55e;\n --amber:#f59e0b;\n --red:#dc2626;\n --red-deep:#b91c1c;\n --red-soft:rgba(220,38,38,.10);\n --radius:12px;\n --shadow:0 1px 2px rgba(15,17,21,.04), 0 8px 24px rgba(15,17,21,.06);\n --sans:-apple-system,BlinkMacSystemFont,\"Segoe UI\",\"PingFang SC\",\"Hiragino Sans GB\",\"Microsoft YaHei\",sans-serif;\n --mono:\"SF Mono\",\"JetBrains Mono\",Menlo,Consolas,monospace;\n}\n*{box-sizing:border-box}\nhtml,body{height:100%}\nbody{margin:0;background:var(--bg);color:var(--ink);font-family:var(--sans);\n font-size:14px;line-height:1.6;overflow:hidden;-webkit-font-smoothing:antialiased}\nbutton{font-family:inherit;color:inherit}\n\n#stage{position:fixed;left:248px;right:0;top:0;bottom:0;overflow:hidden;cursor:grab;\n background:\n radial-gradient(900px 620px at 50% 38%, #ffffff 0%, rgba(255,255,255,0) 70%),\n var(--bg)}\n#stage::before{content:\"\";position:absolute;inset:0;pointer-events:none;\n background-image:radial-gradient(rgba(15,17,21,.055) 1px, transparent 1px);\n background-size:22px 22px;\n -webkit-mask-image:radial-gradient(ellipse 70% 70% at 50% 45%, #000 0%, transparent 78%);\n mask-image:radial-gradient(ellipse 70% 70% at 50% 45%, #000 0%, transparent 78%)}\n#stage.grabbing{cursor:grabbing}\n#world{position:absolute;left:0;top:0;transform-origin:0 0;will-change:transform}\n#edges{position:absolute;left:0;top:0;overflow:visible;pointer-events:none}\n\n#topbar{position:fixed;left:248px;right:0;top:0;display:flex;align-items:flex-start;justify-content:space-between;\n padding:18px 22px;pointer-events:none;z-index:10}\n#brand h1{margin:0;font-size:16px;font-weight:600;letter-spacing:-.01em}\n#brand p{margin:4px 0 0;font-size:12px;color:var(--muted)}\n#brand b{color:var(--secondary);font-weight:500}\n#hint{font-size:11.5px;color:var(--muted);text-align:right;line-height:1.9;transition:opacity .2s}\n#hint kbd{font-family:var(--mono);font-size:10.5px;border:1px solid var(--line);border-radius:4px;\n padding:1px 5px;color:var(--secondary);background:var(--surface)}\nbody.panel-open #hint{opacity:0}\n\n.card{position:absolute;width:300px;padding:15px 16px 13px;border-radius:var(--radius);cursor:grab;\n user-select:none;background:var(--surface);border:1px solid var(--line);box-shadow:var(--shadow);\n transition:border-color .16s,box-shadow .16s,opacity .16s}\n.card:hover{border-color:rgba(0,0,0,.18)}\n.card.dragging{cursor:grabbing;transition:none}\n.card.selected{border-color:var(--blue);\n box-shadow:0 0 0 2px rgba(65,118,230,.14),0 10px 28px rgba(15,17,21,.10)}\n.card.dim{opacity:.38}\n.card:focus-visible{outline:2px solid var(--blue);outline-offset:3px}\n.chip{font-size:11px;letter-spacing:.02em;color:var(--secondary);background:var(--bg-soft);\n border:1px solid var(--line-2);border-radius:6px;padding:1px 7px}\n.status{display:inline-flex;align-items:center;gap:6px;font-size:11px;color:var(--muted)}\n.dot{width:6px;height:6px;border-radius:50%;background:var(--green)}\n.dot.paused{background:var(--amber)}\n.dot.done{background:#c4c7cc}\n.card h3{margin:0 0 9px;font-size:17px;font-weight:600;line-height:1.35;letter-spacing:-.01em}\n.cover{position:relative;height:124px;margin:0 0 10px}\nbody[data-doc-layout=\"landscape\"] .cover{height:86px;margin-bottom:9px}\nbody[data-doc-layout=\"landscape\"] .doc{width:132px;height:76px;border-radius:5px}\nbody[data-doc-layout=\"landscape\"] .doc-empty{width:140px;height:80px}\n.stack{position:absolute;inset:0}\n.doc{position:absolute;left:50%;top:50%;width:86px;height:116px;border-radius:6px;\n border:1px solid rgba(0,0,0,.08);box-shadow:0 8px 18px rgba(15,17,21,.14);background:#fff;\n object-fit:cover;\n transform:translate(-50%,-50%) translate(var(--dx),var(--dy)) rotate(var(--rot)) scale(var(--sc));\n transition:transform .22s cubic-bezier(.22,1,.36,1)}\n.cover:hover .doc{transform:translate(-50%,-50%) translate(calc(var(--dx) * 1.4),var(--dy)) rotate(calc(var(--rot) * 1.35)) scale(var(--sc))}\n.doc-empty{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:96px;height:120px;\n border:1px dashed var(--line);border-radius:6px;display:flex;align-items:center;justify-content:center;\n color:#b3b7bd;font-size:10.5px;background:var(--bg-soft)}\n.more{position:absolute;right:2px;bottom:0;font-size:10px;color:var(--muted);background:var(--surface);\n border:1px solid var(--line-2);border-radius:999px;padding:0 6px}\n.tags{display:flex;flex-wrap:wrap;gap:5px;margin-top:9px;margin-bottom:2px}\n.tags span{font-size:10px;color:var(--secondary);background:var(--bg-soft);border:1px solid var(--line-2);\n border-radius:999px;padding:1px 7px}\n.one{margin:0;font-size:12.5px;line-height:1.65;color:var(--ink-2);\n display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden}\n\n.dots{display:inline-flex;gap:3px}\n.dots i{width:5px;height:5px;border-radius:50%;background:#dcdfe3}\n.dots i.on{background:var(--ink)}\n\n.edge{fill:none;stroke:rgba(15,17,21,.32);stroke-width:1.2}\n.edge.cross{stroke:rgba(15,17,21,.18);stroke-dasharray:4 6}\n.edge.hot{stroke:var(--blue);stroke-width:1.6}\n.edge.cold{opacity:.22}\n\n.pill{cursor:pointer;pointer-events:auto}\n.pill rect{fill:var(--surface);stroke:var(--line);stroke-width:1;transition:stroke .16s,fill .16s}\n.pill text{font:10.5px var(--sans);fill:var(--secondary);letter-spacing:.01em}\n.pill:hover rect{stroke:rgba(0,0,0,.28)}\n.pill.hot rect{stroke:var(--blue);fill:var(--blue-soft)}\n.pill.hot text{fill:var(--blue-deep)}\n.pill.cold{opacity:.25}\n.pill:focus-visible{outline:none}\n.pill:focus-visible rect{stroke:var(--blue);stroke-width:1.6}\n\n#kg-crumb{position:fixed;left:16px;top:14px;z-index:14;display:flex;align-items:center;gap:6px;\n max-width:calc(100% - 32px);padding:6px 11px;border-radius:999px;overflow:hidden;\n background:color-mix(in srgb,var(--surface) 78%,transparent);backdrop-filter:blur(10px);\n border:1px solid var(--line);pointer-events:auto}\n#kg-crumb .seg{border:0;background:none;padding:0;font-size:12px;color:var(--secondary);\n white-space:nowrap;cursor:pointer}\n#kg-crumb .seg:hover{color:var(--ink)}\n#kg-crumb .sep{color:var(--muted);font-size:11px}\n#kg-crumb b{color:var(--ink);font-weight:600;font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n#controls{position:fixed;left:266px;bottom:18px;display:flex;flex-direction:column;gap:6px;z-index:12}\n#controls button{width:34px;height:34px;border-radius:8px;border:1px solid var(--line);\n background:var(--surface);color:var(--ink-2);font-size:15px;line-height:1;cursor:pointer;\n box-shadow:0 1px 2px rgba(15,17,21,.04);transition:background .15s,color .15s}\n#controls button:hover{background:var(--bg-soft);color:var(--ink)}\n#controls button.on{background:var(--ink);color:#fff;border-color:var(--ink)}\n#controls button:focus-visible{outline:2px solid var(--blue);outline-offset:2px}\n#zoomLabel{position:fixed;left:308px;bottom:23px;font-family:var(--mono);font-size:10.5px;\n color:var(--muted);z-index:12}\n\n#panel{position:fixed;top:0;right:0;width:392px;height:100%;z-index:30;\n background:var(--surface);border-left:1px solid var(--line);\n box-shadow:-8px 0 28px rgba(15,17,21,.06);\n transform:translateX(102%);transition:transform .28s cubic-bezier(.22,1,.36,1);\n display:flex;flex-direction:column}\n#panel.open{transform:none}\n.p-head{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;\n padding:22px 22px 15px;border-bottom:1px solid var(--line-2)}\n.p-kicker{font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:var(--muted)}\n.p-head h2{margin:7px 0 0;font-size:22px;font-weight:600;line-height:1.35;letter-spacing:-.01em}\n#close{width:30px;height:30px;flex:0 0 auto;border-radius:8px;border:1px solid var(--line);\n background:var(--surface);color:var(--muted);font-size:16px;cursor:pointer;line-height:1}\n#close:hover{color:var(--ink);background:var(--bg-soft)}\n.p-body{padding:16px 22px 40px;overflow:auto}\n.p-field{margin:0 0 14px}\n.p-field b{display:block;font-size:11px;letter-spacing:.08em;text-transform:uppercase;\n color:var(--muted);font-weight:500;margin-bottom:3px}\n.p-field span{display:block;font-size:13px;line-height:1.7;color:var(--ink-2)}\n.p-rel-title{margin:24px 0 9px;font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:var(--muted)}\n.rel{display:block;width:100%;text-align:left;background:var(--bg-soft);\n border:1px solid var(--line-2);border-radius:8px;padding:10px 11px;margin:0 0 7px;cursor:pointer;\n transition:background .15s,border-color .15s}\n.rel:hover{background:#f1f3f5;border-color:var(--line)}\n.rel b{display:block;font-size:12.5px;color:var(--ink);margin-bottom:2px;font-weight:600}\n.rel span{display:block;font-size:11.5px;line-height:1.6;color:var(--muted);\n display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden}\n.p-docs{font-size:11.5px;color:var(--muted);margin-top:12px}\n.p-doc-item{display:flex;gap:10px;align-items:center;padding:7px 0;border-bottom:1px solid var(--line-2)}\n.p-doc-item img{width:34px;height:46px;border-radius:3px;border:1px solid var(--line-2);object-fit:cover;flex:0 0 auto}\n.p-doc-item .m b{display:block;font-size:12.5px;font-weight:600;color:var(--ink)}\n.p-doc-item .m span{display:block;font-size:10.5px;color:var(--muted)}\n.p-badges{display:inline-flex;align-items:center;gap:3px;margin-left:5px;vertical-align:middle;flex:0 0 auto}\n.p-badge{display:inline-flex;align-items:center;height:15px;padding:0 4px;border:.5px solid var(--line);border-radius:3px;background:var(--bg-soft);color:var(--ink-2);font:600 9.5px/1 var(--sans);letter-spacing:0;white-space:nowrap;cursor:default}\n.p-badge.ai{border-color:var(--blue);background:var(--blue-soft);color:var(--blue-deep)}\n.p-badge.reviewed{border-color:var(--green);background:rgba(34,197,94,.10)}\n.p-badge.redline{border-color:var(--red);background:var(--red-soft);color:var(--red-deep)}\n.p-doc{font-size:13px;line-height:1.8;color:var(--ink-2)}\n.p-doc h2{font-size:14px;font-weight:600;color:var(--ink);margin:22px 0 6px}\n.p-doc h3{font-size:13px;font-weight:600;color:var(--ink);margin:18px 0 5px}\n.p-doc p{margin:0 0 10px}\n.p-doc ul,.p-doc ol{margin:0 0 10px;padding-left:18px}\n.p-doc li{margin:2px 0}\n.p-doc blockquote{margin:0 0 10px;padding:2px 0 2px 12px;border-left:2px solid var(--line);color:var(--muted)}\n.p-doc code{font-family:var(--mono);font-size:.86em;background:var(--bg-soft);border:1px solid var(--line-2);padding:0 4px;border-radius:4px}\n.p-doc pre{margin:0 0 10px;padding:10px 12px;background:var(--bg-soft);border:1px solid var(--line-2);border-radius:8px;overflow:auto}\n.p-doc pre code{background:none;border:0;padding:0}\n.p-doc strong{color:var(--ink);font-weight:600}\n.p-doc a{color:var(--blue);text-decoration:none}\n\n\n/* ---------- tree ---------- */\n#tree{position:fixed;left:0;top:0;bottom:0;width:248px;z-index:20;display:flex;flex-direction:column;\n background:var(--surface);border-right:1px solid var(--line)}\n.tree-head{padding:18px 16px 13px;border-bottom:1px solid var(--line-2)}\n.tree-title{font-size:14px;font-weight:600}\n.tree-sub{font-size:11px;color:var(--muted);margin-top:2px}\n#treeBody{flex:1;overflow:auto;padding:8px 8px 20px}\n.tree-scope{font-size:10.5px;letter-spacing:.1em;color:var(--muted);padding:12px 10px 5px}\n.tree-group{font-size:11.5px;color:var(--secondary);padding:6px 10px 3px}\n.tree-graph{display:flex;align-items:center;justify-content:space-between;gap:8px;\n padding:5px 10px;border-radius:6px;font-size:12.5px;color:var(--ink-2);cursor:pointer}\n.tree-graph:hover{background:var(--bg-soft)}\n.tree-graph.active{background:var(--blue-soft);color:var(--blue-deep)}\n.tree-graph .n{font-size:10.5px;color:var(--muted);font-variant-numeric:tabular-nums}\n.tree-graph.active .n{color:var(--blue)}\n.tree-topic{padding:4px 10px 4px 24px;font-size:12px;color:var(--muted);border-radius:6px;cursor:pointer;\n white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.tree-topic:hover{background:var(--bg-soft);color:var(--ink)}\n.tree-empty{padding:2px 10px 4px 24px;font-size:11.5px;color:#b3b7bd}\n\n@media (max-width:760px){\n #tree{display:none}\n #stage{left:0}\n #topbar{left:0}\n #controls{left:18px}\n #zoomLabel{left:60px}\n #hint{display:none}\n .only-wide{display:none}\n #brand h1{font-size:15px}\n .card{width:270px}\n #panel{width:100%;height:72%;top:auto;bottom:0;border-left:0;border-top:1px solid var(--line);\n transform:translateY(102%);border-radius:16px 16px 0 0}\n #panel.open{transform:none}\n}\n</style>\n<style>\n:root{\n --bg:#151517; --bg-soft:#232324; --surface:#232324; --ink:#f5f5f7; --ink-2:#cfd3d6;\n --secondary:#adb2b8; --muted:#8a8d95; --line:rgba(255,255,255,.12); --line-2:rgba(255,255,255,.06);\n --blue:#4d93f8; --blue-deep:#9db9ff; --blue-soft:rgba(77,147,248,.14);\n --green:#22c55e; --amber:#f59e0b;\n --red:#f87171; --red-deep:#fca5a5; --red-soft:rgba(248,113,113,.14);\n --shadow:0 1px 2px rgba(0,0,0,.3), 0 10px 30px rgba(0,0,0,.28);\n}\nhtml,body{height:100%}\nbody{display:flex;overflow:hidden;background:var(--bg);color:var(--ink)}\n#rail{width:280px;flex:0 0 280px;background:#141416;border-right:.5px solid rgba(255,255,255,.10);\n display:flex;flex-direction:column;min-height:0}\n.rail-top{height:36px;flex:0 0 36px;display:flex;align-items:center;gap:8px;padding:0 6px 0 12px}\n.rail-brand{display:flex;align-items:center;gap:8px;font-size:14px;font-weight:600;color:var(--ink)}\n.rail-brand svg{width:16px;height:16px;color:var(--secondary)}\n.rail-fold{margin-left:auto;width:28px;height:28px;border:0;background:none;border-radius:6px;\n color:var(--muted);cursor:pointer;display:flex;align-items:center;justify-content:center}\n.rail-fold:hover{background:rgba(255,255,255,.06);color:var(--ink)}\n.rail-search{margin:6px 12px 4px;height:32px;display:flex;align-items:center;gap:8px;padding:0 10px;\n background:#1f1f22;border:.5px solid rgba(255,255,255,.10);border-radius:8px}\n.rail-search svg{width:14px;height:14px;color:var(--muted)}\n.rail-search input{flex:1;min-width:0;background:none;border:0;outline:none;color:var(--ink);font-size:12.5px}\n.rail-search input::placeholder{color:#6f737a}\n.rail-nav{padding:4px 8px;display:flex;flex-direction:column;gap:1px}\n.nav-item{height:34px;display:flex;align-items:center;gap:10px;padding:0 10px;border:0;border-radius:6px;\n background:none;color:var(--secondary);font-size:13.5px;text-align:left;cursor:pointer}\n.nav-item svg{width:15px;height:15px;color:var(--muted)}\n.nav-item:hover{background:rgba(255,255,255,.06)}\n.nav-item.active{background:rgba(255,255,255,.08);color:var(--ink)}\n.nav-item.active svg{color:var(--secondary)}\n.tree-head{height:36px;flex:0 0 36px;display:flex;align-items:center;gap:4px;padding:0 8px 0 12px}\n.rail-tabs{display:flex;align-items:center;gap:18px;height:36px}\n.rail-tab{height:36px;padding:0;border:0;background:none;color:var(--muted);font-size:14px;\n cursor:pointer;position:relative}\n.rail-tab:hover{color:var(--secondary)}\n.rail-tab.active{color:var(--ink)}\n.rail-tab.active::after{content:\"\";position:absolute;left:0;right:0;bottom:0;height:2px;\n border-radius:1px;background:var(--blue)}\n.tree-tools{margin-left:auto;display:flex;align-items:center;gap:2px}\n.tree-tools button{width:28px;height:28px;border:0;background:none;border-radius:6px;\n color:var(--secondary);display:flex;align-items:center;justify-content:center;cursor:pointer}\n.tree-tools button:hover{background:rgba(255,255,255,.06);color:var(--ink)}\n#treeBody{flex:1;min-height:0;overflow:auto;padding:4px 8px 16px}\n.tree-scope{font-size:10.5px;letter-spacing:.1em;color:var(--muted);padding:10px 10px 4px}\n.tree-group{font-size:11.5px;color:var(--secondary);padding:4px 10px 2px}\n.tree-graph{display:flex;justify-content:space-between;align-items:center;height:28px;padding:0 10px;\n border-radius:6px;font-size:12.5px;color:var(--secondary);cursor:pointer}\n.tree-graph:hover{background:rgba(255,255,255,.06)}\n.tree-graph.active{background:var(--blue-soft);color:var(--blue-deep)}\n.tree-graph .n{font-size:10.5px;color:#6f737a;font-variant-numeric:tabular-nums}\n.tree-topic{height:26px;display:flex;align-items:center;padding:0 10px 0 24px;border-radius:6px;\n font-size:12px;color:var(--muted);cursor:pointer;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.tree-topic:hover{background:rgba(255,255,255,.06);color:var(--ink)}\n.tree-empty{padding:2px 10px 4px 24px;font-size:11.5px;color:#5f636a}\n.tree-kb{display:flex;align-items:center;gap:8px;height:28px;padding:0 10px;border-radius:6px;\n font-size:12.5px;color:var(--secondary);cursor:pointer}\n.tree-kb:hover{background:rgba(255,255,255,.06)}\n.tree-kb svg{width:14px;height:14px;color:#d9a441;flex:0 0 auto}\n.tree-kb.file svg{color:#8a8d95}\n.tree-kb .date{margin-left:auto;font-size:10.5px;color:#6f737a}\n#main{flex:1;min-width:0;display:flex;flex-direction:column;position:relative;background:#1a1a1c}\n#mainhead{height:48px;flex:0 0 48px;display:flex;align-items:center;gap:12px;padding:0 18px;\n border-bottom:.5px solid rgba(255,255,255,.10)}\n.crumb{display:flex;align-items:center;gap:8px;font-size:13px;color:var(--muted);min-width:0}\n.crumb b{color:var(--ink);font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.crumb i{font-style:normal;color:#5f636a}\n#headMeta{font-size:11.5px;color:#7f838a;white-space:nowrap}\n.head-actions{margin-left:auto;display:flex;gap:8px}\n.head-actions button{height:28px;padding:0 10px;border:.5px solid rgba(255,255,255,.12);border-radius:6px;\n background:#232324;color:var(--secondary);font-size:12px;cursor:pointer}\n.head-actions button:hover{background:#2c2c2e;color:var(--ink)}\n#stage{position:relative;left:auto;right:auto;top:auto;bottom:auto;flex:1;min-height:0;overflow:hidden;cursor:grab;\n background:radial-gradient(900px 620px at 50% 38%,rgba(255,255,255,.03),transparent 70%),#1a1a1c}\n#stage::before{background-image:radial-gradient(rgba(255,255,255,.055) 1px,transparent 1px)}\n#controls{position:absolute;left:16px;bottom:16px;z-index:12}\n#controls button{background:#232324;border-color:rgba(255,255,255,.12);color:var(--secondary)}\n#controls button:hover{background:#2c2c2e;color:var(--ink)}\n#controls button.on{background:var(--blue);border-color:var(--blue);color:#0b1220}\n#zoomLabel{position:absolute;left:60px;bottom:21px;color:var(--muted)}\n.card{background:#232324;border-color:rgba(255,255,255,.10);\n box-shadow:0 1px 2px rgba(0,0,0,.3),0 10px 30px rgba(0,0,0,.28)}\n.card:hover{border-color:rgba(255,255,255,.20)}\n.card.selected{border-color:var(--blue);box-shadow:0 0 0 2px rgba(77,147,248,.20),0 10px 30px rgba(0,0,0,.35)}\n.card.dim{opacity:.32}\n.card h3{color:var(--ink)}\n.one{color:var(--secondary)}\n.tags span{background:#2c2c2e;border-color:rgba(255,255,255,.08);color:var(--secondary)}\n.doc{border-color:rgba(255,255,255,.12);box-shadow:0 8px 18px rgba(0,0,0,.40)}\n.edge{stroke:rgba(255,255,255,.22)}\n.edge.cross{stroke:rgba(255,255,255,.12)}\n.edge.hot{stroke:var(--blue)}\n.pill rect{fill:#232324;stroke:rgba(255,255,255,.14)}\n.pill text{fill:var(--secondary)}\n.pill.hot rect{fill:rgba(77,147,248,.16);stroke:var(--blue)}\n.pill.hot text{fill:var(--blue-deep)}\n#panel{background:#1e1e21;border-left-color:rgba(255,255,255,.10);box-shadow:-8px 0 28px rgba(0,0,0,.40)}\n.p-head{border-bottom-color:rgba(255,255,255,.06)}\n.p-kicker{color:var(--muted)}\n.p-head h2{color:var(--ink)}\n#close{background:#232324;border-color:rgba(255,255,255,.12);color:var(--muted)}\n#close:hover{background:#2c2c2e;color:var(--ink)}\n.p-field b{color:var(--muted)}\n.p-field span{color:var(--secondary)}\n.p-doc{color:var(--secondary)}\n.p-doc h2,.p-doc h3{color:var(--ink)}\n.p-doc code{background:#2c2c2e;border-color:rgba(255,255,255,.08)}\n.p-doc pre{background:#1a1a1c;border-color:rgba(255,255,255,.08)}\n.rel{background:#262629;border-color:rgba(255,255,255,.07)}\n.rel:hover{background:#2c2c2e;border-color:rgba(255,255,255,.12)}\n.rel b{color:var(--ink)}\n.rel span{color:var(--muted)}\n.p-doc-item{border-bottom-color:rgba(255,255,255,.06)}\n.p-doc-item .m b{color:var(--ink)}\n.p-doc-item .m span{color:var(--muted)}\n#kbView{flex:1;min-height:0;overflow:auto;padding:18px}\n.kb-cards{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:13px}\n.kb-card{display:flex;gap:13px;align-items:center;height:63px;padding:0 13px;border:.5px solid rgba(255,255,255,.10);\n border-radius:10px;background:#232324;text-align:left;cursor:pointer;color:var(--ink)}\n.kb-card:hover{background:#262629}\n.kb-card .plate{width:22px;height:22px;border-radius:6px;display:flex;align-items:center;justify-content:center;font-size:13px;flex:0 0 auto}\n.kb-card b{display:block;font-size:13.5px;color:var(--ink);font-weight:600}\n.kb-card small{display:block;font-size:11.5px;color:var(--muted);margin-top:2px}\n.kb-tabs{display:flex;gap:8px;margin:16px 0 6px;border-bottom:.5px solid rgba(255,255,255,.08)}\n.kb-tab{padding:8px 10px;font-size:12.5px;color:var(--muted);background:none;border:0;cursor:pointer;border-bottom:2px solid transparent}\n.kb-tab.active{color:var(--ink);border-bottom-color:var(--blue)}\n.kb-table{width:100%;border-collapse:collapse;font-size:12.5px}\n.kb-table th{text-align:left;font-weight:500;color:#7f838a;font-size:11px;padding:8px 10px;border-bottom:.5px solid rgba(255,255,255,.08)}\n.kb-table td{padding:9px 10px;border-bottom:.5px solid rgba(255,255,255,.06);color:var(--secondary)}\n.kb-table td.muted{color:var(--muted)}\n.kb-table tr:hover td{background:rgba(255,255,255,.03)}\n[hidden]{display:none !important}\n@media (max-width:900px){#rail{display:none}}\n</style>\n<style>\n/* ---- embedding page: no rail, no page header; the plugin owns both ---- */\n#tree { display: none !important; }\n#stage { left: 0 !important; }\n#controls { left: 18px !important; }\n#zoomLabel { left: 62px !important; }\n#main { width: 100%; }\n#kg-empty { position: absolute; inset: 0; z-index: 8; display: flex; flex-direction: column;\n align-items: center; justify-content: center; gap: 6px; background: #1a1a1c; color: #8a8d95;\n font-family: var(--sans); text-align: center; padding: 24px; }\n#kg-empty strong { font-size: 14px; font-weight: 600; color: #cfd3d6; }\n#kg-empty span { font-size: 12px; }\n</style>\n<style>\n/* ---- host theme bridge ----\n The canvas is a separate document, so it cannot inherit the host's custom\n properties. The parent posts every --dsw-alias-* value below into this page and\n writes it on :root. These fallbacks are only the first-paint values before that\n message lands; the live values always come from the host. */\n:root {\n --bg: var(--dsw-alias-bg-base, #fff);\n --bg-soft: var(--dsw-alias-bg-layer-1, #f6f7f9);\n --surface: var(--dsw-alias-bg-layer-2, #fff);\n --ink: var(--dsw-alias-label-primary, #0f1115);\n --ink-2: var(--dsw-alias-label-secondary, #3c3f47);\n --secondary: var(--dsw-alias-label-secondary, #61666b);\n /* 80% tertiary + 20% primary keeps the third level distinguishable while\n reaching 4.5:1 on the light surface (the raw light tertiary does not). */\n --muted: color-mix(in srgb, var(--dsw-alias-label-tertiary, #81858c) 80%, var(--dsw-alias-label-primary, #0f1115));\n --line: var(--dsw-alias-border-l2, rgba(0, 0, 0, .10));\n --line-2: var(--dsw-alias-border-l1, rgba(0, 0, 0, .06));\n --blue: var(--dsw-alias-state-business-primary, #4176e6);\n /* Accent text needs 4.5:1, and the raw link token is 4.2:1 on white. A 78/22 mix\n with the primary ink keeps the brand hue while clearing the body-text floor. */\n --blue-deep: color-mix(in srgb, var(--dsw-alias-state-business-primary, #4176e6) 78%, var(--dsw-alias-label-primary, #0f1115));\n --blue-soft: color-mix(in srgb, var(--dsw-alias-state-business-primary, #4176e6) 16%, transparent);\n --green: var(--dsw-alias-state-success-primary, #22c55e);\n --amber: var(--dsw-alias-state-warn-primary, #f59e0b);\n --red: var(--dsw-alias-state-error-primary, #dc2626);\n --red-deep: color-mix(in srgb, var(--dsw-alias-state-error-primary, #dc2626) 80%, var(--dsw-alias-label-primary, #0f1115));\n --red-soft: color-mix(in srgb, var(--dsw-alias-state-error-primary, #dc2626) 12%, transparent);\n --shadow: var(--dsw-elevation-panel, 0 1px 2px rgba(0, 0, 0, .10));\n --stage-bg: color-mix(in srgb, var(--dsw-alias-bg-base, #fff) 96%, var(--dsw-alias-label-primary, #0f1115));\n --soft: color-mix(in srgb, var(--dsw-alias-label-primary, #0f1115) 6%, transparent);\n --dot: color-mix(in srgb, var(--dsw-alias-label-primary, #0f1115) 9%, transparent);\n --edge: color-mix(in srgb, var(--dsw-alias-label-primary, #0f1115) 24%, transparent);\n --edge-soft: color-mix(in srgb, var(--dsw-alias-label-primary, #0f1115) 14%, transparent);\n}\n\n#stage {\n background:\n radial-gradient(900px 620px at 50% 38%, color-mix(in srgb, var(--surface) 60%, transparent), transparent 70%),\n var(--stage-bg) !important;\n}\n#stage::before { background-image: radial-gradient(var(--dot) 1px, transparent 1px) !important; }\n#kg-empty { background: var(--stage-bg) !important; color: var(--muted) !important; }\n#kg-empty strong { color: var(--ink) !important; }\n.card:focus-visible, #controls button:focus-visible { outline-color: var(--blue) !important; }\n.p-doc-item img { border-color: var(--line) !important; }\n.card { background: var(--surface) !important; border-color: var(--line) !important; box-shadow: var(--shadow) !important; }\n.card:hover { border-color: color-mix(in srgb, var(--ink) 22%, transparent) !important; }\n.card.selected { border-color: var(--blue) !important; box-shadow: 0 0 0 2px var(--blue-soft), var(--shadow) !important; }\n/* Dimming is focus, not disappearance: 32% made secondary text unreadable. */\n.card.dim { opacity: .55 !important; }\n.card h3 { color: var(--ink) !important; }\n.one { color: var(--secondary) !important; font-size: 13px; line-height: 1.6; }\n.tags span {\n background: var(--soft) !important; border-color: var(--line-2) !important;\n color: var(--secondary) !important; font-size: 11px; padding: 2px 7px;\n}\n.dots i { background: var(--line) !important; }\n.dots i.on { background: var(--ink) !important; }\n.doc { border-color: var(--line) !important; box-shadow: var(--shadow) !important; }\n.doc-empty { border-color: var(--line) !important; color: var(--muted) !important; background: var(--bg-soft) !important; }\n.docGenerated {\n display: flex; flex-direction: column; gap: 3px; padding: 7px 8px;\n background: var(--surface) !important; color: var(--ink);\n border: 1px solid var(--line) !important; border-radius: 6px;\n overflow: hidden;\n}\n.docGenerated .docMark {\n color: var(--blue-deep); font: 600 7.5px/1 var(--mono); letter-spacing: .08em;\n}\n.docGenerated b {\n color: var(--ink); font-size: 8.5px; line-height: 1.25; font-weight: 600;\n overflow-wrap: anywhere; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden;\n}\n.docGenerated i { margin-top: auto; color: var(--muted); font: normal 7px/1 var(--sans); }\n.docGenerated.wide { gap: 4px; padding: 9px 11px; }\n.docGenerated.wide .docMark { font-size: 9px; }\n.docGenerated.wide b { font-size: 12px; -webkit-line-clamp: 2; }\n.docGenerated.wide i { font-size: 8px; }\n.edge { stroke: var(--edge) !important; }\n.edge.cross { stroke: var(--edge-soft) !important; }\n.edge.hot { stroke: var(--blue) !important; }\n.pill rect { fill: var(--surface) !important; stroke: var(--line) !important; }\n.pill text { fill: var(--secondary) !important; }\n.pill.hot rect { fill: var(--blue-soft) !important; stroke: var(--blue) !important; }\n.pill.hot text { fill: var(--blue-deep) !important; }\n#controls button {\n background: var(--surface) !important; border-color: var(--line) !important;\n color: var(--ink-2) !important; box-shadow: var(--shadow) !important;\n}\n#controls button:hover { background: var(--bg-soft) !important; color: var(--ink) !important; }\n#controls button.on { background: var(--blue) !important; border-color: var(--blue) !important; color: var(--bg) !important; }\n#zoomLabel { color: var(--muted) !important; background: none !important; border: 0 !important;\n padding: 2px 4px !important; cursor: pointer; font-family: var(--mono); }\n#zoomLabel:hover { color: var(--ink) !important; }\n#panel { background: var(--surface) !important; border-left-color: var(--line) !important;\n box-shadow: -8px 0 28px color-mix(in srgb, var(--ink) 12%, transparent) !important; }\n#close { background: var(--surface) !important; border-color: var(--line) !important; color: var(--muted) !important; }\n#close:hover { background: var(--bg-soft) !important; color: var(--ink) !important; }\n.p-head { border-bottom-color: var(--line-2) !important; }\n.p-kicker { color: var(--muted) !important; }\n.p-head h2 { color: var(--ink) !important; }\n.p-field b { color: var(--muted) !important; }\n.p-field span, .p-doc { color: var(--secondary) !important; }\n.p-rel-title { color: var(--muted) !important; }\n.rel { background: var(--soft) !important; border-color: var(--line-2) !important; }\n.rel:hover { background: var(--bg-soft) !important; border-color: var(--line) !important; }\n.rel b { color: var(--ink) !important; }\n.rel span { color: var(--secondary) !important; }\n.p-docs { color: var(--muted) !important; }\n.p-doc-item { border-bottom-color: var(--line-2) !important; }\n.p-doc-item .m b { color: var(--ink) !important; }\n.p-doc-item .m span { color: var(--muted) !important; }\n.p-doc-thumb {\n display: flex; align-items: center; justify-content: center; flex: 0 0 auto;\n width: 34px; height: 46px; border-radius: 4px;\n border: 1px solid var(--line); background: var(--soft); color: var(--blue-deep);\n font: 600 8px/1 var(--mono); letter-spacing: .06em;\n}\n.p-doc h2, .p-doc h3 { color: var(--ink) !important; }\n.p-doc code { background: var(--soft) !important; border-color: var(--line-2) !important; }\n.p-doc pre { background: var(--bg) !important; border-color: var(--line-2) !important; }\n</style>\n</head>\n<body data-doc-layout=\"landscape\" data-view=\"graph\">\n<main id=\"main\">\n <div id=\"kg-crumb\" hidden></div>\n <div id=\"stage\">\n <div id=\"world\">\n <svg id=\"edges\" width=\"4200\" height=\"3200\" viewBox=\"0 0 4200 3200\" aria-hidden=\"true\"></svg>\n </div>\n </div>\n <div id=\"controls\" role=\"group\" aria-label=\"画布控制\">\n <button id=\"zin\" aria-label=\"放大\">+</button>\n <button id=\"zout\" aria-label=\"缩小\">−</button>\n <button id=\"fit\" aria-label=\"适应画布\">⤢</button>\n <button id=\"cross\" aria-label=\"显示交叉关系\" title=\"显示交叉关系\">⇄</button>\n <button id=\"relayout\" aria-label=\"重排\" title=\"重排\">↺</button>\n </div>\n <button id=\"zoomLabel\" type=\"button\" aria-label=\"重置缩放为 100%\" title=\"重置缩放为 100%\">100%</button>\n <div id=\"kg-empty\" hidden><strong>还没有可用的图谱</strong><span>在「知识图谱」文件夹里建好主题后,画布会出现在这里。</span></div>\n</main>\n\n<aside id=\"panel\" aria-label=\"主题详情\" aria-hidden=\"true\">\n <div class=\"p-head\">\n <div>\n <div class=\"p-kicker\" id=\"p-kicker\"></div>\n <h2 id=\"p-title\"></h2>\n </div>\n <button id=\"close\" aria-label=\"关闭\">×</button>\n </div>\n <div class=\"p-body\" id=\"p-body\"></div>\n</aside>\n<script>\nconst DATA = { graphs: [] };\n\n(function(){\n \"use strict\";\n const stage = document.getElementById('stage');\n const world = document.getElementById('world');\n const svg = document.getElementById('edges');\n const panel = document.getElementById('panel');\n const zoomLabel = document.getElementById('zoomLabel');\n\n const NS = 'http://www.w3.org/2000/svg';\n let topics = [];\n let links = [];\n let byId = new Map();\n let activeGraph = 0;\n let viewMode = 'graph';\n const cardEl = new Map();\n const view = {x:0, y:0, s:1};\n const CARD_W = 300, H_GAP = 110, V_GAP = 34, PAD = 40;\n const LAND = document.body.dataset.docLayout === 'landscape';\n\n let mode = null;\n let activeTopic = null;\n let activeLink = null;\n let userMoved = false;\n let children = new Map();\n let parentOf = new Map();\n let treeKeys = new Set();\n let pos = new Map();\n let heights = new Map(), subH = new Map();\n let showCross = false;\n let layoutRootId = null;\n\n function esc(s){\n return String(s == null ? '' : s).replace(/[&<>\"]/g, function(c){\n return {'&':'&amp;','<':'&lt;','>':'&gt;','\"':'&quot;'}[c];\n });\n }\n function statusText(s){ return s === 'active' ? '进行中' : s === 'paused' ? '暂停' : '已完成'; }\n // Provenance chips are pure presentation. The host has already permission-filtered\n // the payload, so a badge never gates or hides a document.\n function badgeItems(item){\n const items = [];\n if (item && (item.origin === 'ai' || item.origin === 'mixed')) {\n items.push({kind:'ai', label:'AI 生成', title:item.origin === 'mixed' ? '人工与 AI 混合生成的内容' : 'AI 生成内容;发布时必须保留来源标签'});\n }\n if (item && (item.reviewStatus === 'reviewed' || item.reviewStatus === 'approved')) {\n items.push({kind:'reviewed', label:'已审核', title:item.reviewStatus === 'approved' ? '已审核并批准' : '已审核'});\n }\n if (item && item.authority === 'redline') {\n items.push({kind:'redline', label:'红线', title:'红线:只能订阅,不可内化或覆盖'});\n }\n return items;\n }\n function badgesHtml(item){\n const items = badgeItems(item);\n if (!items.length) return '';\n return '<span class=\"p-badges\" role=\"group\" aria-label=\"内容标签\">' + items.map(function(b){\n return '<span class=\"p-badge ' + b.kind + '\" title=\"' + b.title + '\" aria-label=\"' + b.label + '\">[' + b.label + ']</span>';\n }).join('') + '</span>';\n }\n function linkKey(l){ return l.a + '--' + l.b; }\n function pairKey(a, b){ return a < b ? a + '--' + b : b + '--' + a; }\n\n // ---------- cards ----------\n\n // Documents in the knowledge tree have no stored thumbnail. A generated cover\n // uses the host's own theme variables (set from the parent document), so a light\n // host gets ink-on-white covers and a dark host gets the inverse. No bitmap and\n // no fixed palette: the cover is markup, not an image.\n function coverFor(d, idx, wide, w, h, dx, dy, rot, sc, z){\n const style = 'width:' + w + 'px;height:' + h + 'px;--dx:' + dx + 'px;--dy:' + dy +\n 'px;--rot:' + rot + 'deg;--sc:' + sc + ';z-index:' + z;\n if (d.thumb) {\n const src = (wide && d.thumbWide) ? d.thumbWide : d.thumb;\n return '<img class=\"doc\" src=\"' + src + '\" alt=\"' + esc(d.title) + '\" style=\"' + style + '\">';\n }\n const ext = String(d.file || 'doc').split('.').pop().slice(0, 4).toUpperCase();\n return '<div class=\"doc docGenerated' + (wide ? ' wide' : '') + '\" style=\"' + style + '\" title=\"' + esc(d.title) + '\">' +\n '<span class=\"docMark\">' + esc(ext) + '</span>' +\n '<b>' + esc(d.title || d.file || '') + '</b>' +\n '<i>' + esc(d.date || '') + '</i></div>';\n }\n\n // The detail panel renders the same cover inline, at a fixed 34x46 slot.\n function inlineCover(d){\n if (d.thumb) return '<img src=\"' + d.thumb + '\" alt=\"\">';\n const ext = String(d.file || 'doc').split('.').pop().slice(0, 4).toUpperCase();\n return '<span class=\"p-doc-thumb\"><i>' + esc(ext) + '</i></span>';\n }\n\n function buildCard(t){\n const el = document.createElement('article');\n el.className = 'card';\n el.dataset.id = t.id;\n el.tabIndex = 0;\n el.style.left = '0px';\n el.style.top = '0px';\n el.style.visibility = 'hidden';\n el.setAttribute('role', 'button');\n el.setAttribute('aria-label', t.title + ',' + statusText(t.status) + ',深度 ' + t.depth);\n\n const dots = [1,2,3,4,5].map(i =>\n '<i class=\"' + (i <= t.depth ? 'on' : '') + '\"></i>').join('');\n const docs = t.documents || [];\n const shown = docs.slice(0, 4);\n const mid = (shown.length - 1) / 2;\n let docW = 86, docH = 116, step = 31, rotStep = 6.5, dyStep = 2, scStep = 0.03, coverH = 124;\n if (LAND){\n if (shown.length <= 1){ docW = 240; docH = 84; step = 0; rotStep = 0; dyStep = 0; scStep = 0; coverH = 92; }\n else if (shown.length === 2){ docW = 142; docH = 78; step = 58; rotStep = 5; dyStep = 3; scStep = 0.02; coverH = 88; }\n else if (shown.length === 3){ docW = 132; docH = 76; step = 46; rotStep = 4.2; dyStep = 3; scStep = 0.02; coverH = 86; }\n else { docW = 118; docH = 70; step = 42; rotStep = 4; dyStep = 3; scStep = 0.02; coverH = 80; }\n }\n let stack = '';\n shown.forEach(function(d, i){\n const dist = Math.abs(i - mid);\n const dx = (i - mid) * step;\n const dy = dist * dyStep;\n const rot = (i - mid) * rotStep;\n const sc = 1 - dist * scStep;\n const z = 10 - dist;\n stack += coverFor(d, i, shown.length === 1, docW, docH, dx, dy, rot, sc, z);\n });\n if (docs.length > 4) stack += '<span class=\"more\">+' + (docs.length - 4) + '</span>';\n if (!docs.length) stack = '<div class=\"doc-empty\">docs/ 还是空的</div>';\n const tagList = [t.domain].concat(t.tags || []).filter(function(x, i, arr){\n return x && arr.indexOf(x) === i;\n }).slice(0, 4);\n const tags = tagList.map(function(x){ return '<span>' + esc(x) + '</span>'; }).join('');\n\n el.innerHTML =\n '<h3>' + esc(t.title) + badgesHtml(t) + '</h3>' +\n '<div class=\"cover\" style=\"height:' + coverH + 'px\"><div class=\"stack\">' + stack + '</div></div>' +\n '<p class=\"one\">' + esc(t.summary) + '</p>' +\n '<div class=\"tags\">' + tags + '</div>';\n\n el.addEventListener('pointerdown', onCardDown);\n el.addEventListener('keydown', function(e){\n if (e.key === 'Enter' || e.key === ' '){ e.preventDefault(); selectTopic(t.id); }\n });\n world.appendChild(el);\n cardEl.set(t.id, el);\n }\n\n // ---------- spanning tree ----------\n function degree(id){\n // Cross-graph links must not decide the layout root or the BFS tree: the\n // overview is clustered by source graph, so only internal relations shape a\n // cluster. A cross link stays a dashed edge between the clusters.\n return links.filter(function(l){ return l.crossGraph !== true && (l.a === id || l.b === id); }).length;\n }\n function buildTree(rootId){\n children = new Map(); parentOf = new Map(); treeKeys = new Set();\n const visited = new Set([rootId]);\n const queue = [rootId];\n topics.forEach(function(t){ children.set(t.id, []); });\n while (queue.length){\n const id = queue.shift();\n const neighbors = [];\n links.forEach(function(l){\n if (l.crossGraph === true) return;\n if (l.a === id && !visited.has(l.b)) neighbors.push(l.b);\n else if (l.b === id && !visited.has(l.a)) neighbors.push(l.a);\n });\n neighbors.sort(function(a, b){ return degree(b) - degree(a); });\n neighbors.forEach(function(n){\n visited.add(n);\n parentOf.set(n, id);\n children.get(id).push(n);\n treeKeys.add(pairKey(id, n));\n queue.push(n);\n });\n }\n topics.forEach(function(t){\n if (!visited.has(t.id)){\n parentOf.set(t.id, rootId);\n children.get(rootId).push(t.id);\n treeKeys.add(pairKey(rootId, t.id));\n visited.add(t.id);\n }\n });\n }\n\n // ---------- mind-map layout ----------\n function calcSub(id){\n const h = heights.get(id) || 200;\n const kids = children.get(id) || [];\n if (!kids.length){ subH.set(id, h); return h; }\n let total = 0;\n kids.forEach(function(k, i){\n total += calcSub(k);\n if (i) total += V_GAP;\n });\n subH.set(id, Math.max(h, total));\n return subH.get(id);\n }\n\n function placeNode(id, x, yTop, dir){\n const h = heights.get(id) || 200;\n const sub = subH.get(id) || h;\n const cy = yTop + sub / 2;\n pos.set(id, {x:x, y:cy - h / 2, dir:dir});\n const kids = children.get(id) || [];\n let cursor = yTop;\n kids.forEach(function(k){\n const kh = subH.get(k) || 200;\n const kx = dir > 0 ? x + CARD_W + H_GAP : x - CARD_W - H_GAP;\n placeNode(k, kx, cursor, dir);\n cursor += kh + V_GAP;\n });\n }\n\n function layout(){\n heights = new Map();\n // An empty computed overview (a scope with no readable graph) has no root;\n // skip the BFS instead of dereferencing `topics[0]`. The caller shows the\n // empty state for it.\n if (!topics.length){ layoutRootId = null; return; }\n topics.forEach(function(t){ heights.set(t.id, cardEl.get(t.id).offsetHeight || 200); });\n\n let rootId = topics[0].id, best = -1;\n topics.forEach(function(t){\n const d = degree(t.id);\n if (d > best){ best = d; rootId = t.id; }\n });\n if (byId.has('dsh-enterprise-app')) rootId = 'dsh-enterprise-app';\n layoutRootId = rootId;\n buildTree(rootId);\n calcSub(rootId);\n\n const first = (children.get(rootId) || []).slice();\n first.sort(function(a, b){ return (subH.get(b) || 0) - (subH.get(a) || 0); });\n\n const left = [], right = [];\n let lh = 0, rh = 0;\n first.forEach(function(id){\n if (rh <= lh){ right.push(id); rh += subH.get(id); }\n else { left.push(id); lh += subH.get(id); }\n });\n\n const rootH = heights.get(rootId);\n pos.set(rootId, {x:0, y:-rootH / 2, dir:0});\n\n function placeSide(list, dir){\n let total = 0;\n list.forEach(function(id, i){ total += subH.get(id); if (i) total += V_GAP; });\n let cursor = -total / 2;\n list.forEach(function(id){\n const kh = subH.get(id);\n const x = dir > 0 ? CARD_W + H_GAP : -CARD_W - H_GAP;\n placeNode(id, x, cursor, dir);\n cursor += kh + V_GAP;\n });\n }\n placeSide(left, -1);\n placeSide(right, 1);\n\n let minX = Infinity, minY = Infinity;\n pos.forEach(function(p){ minX = Math.min(minX, p.x); minY = Math.min(minY, p.y); });\n pos.forEach(function(p, id){\n p.x = p.x - minX + PAD;\n p.y = p.y - minY + PAD;\n const t = byId.get(id);\n t.x = p.x; t.y = p.y;\n const el = cardEl.get(id);\n el.style.left = p.x + 'px';\n el.style.top = p.y + 'px';\n el.style.visibility = '';\n });\n }\n\n // ---------- edges & pills ----------\n function center(id){\n const p = pos.get(id), h = heights.get(id) || 200;\n return {x:p.x + CARD_W / 2, y:p.y + h / 2};\n }\n function anchor(id, tx, ty){\n const c = center(id), h = heights.get(id) || 200;\n const dx = tx - c.x, dy = ty - c.y;\n if (!dx && !dy) return c;\n if (Math.abs(dx) * h > Math.abs(dy) * CARD_W){\n const k = (CARD_W / 2) / Math.abs(dx);\n return {x:c.x + dx * k, y:c.y + dy * k};\n }\n const k = (h / 2) / Math.abs(dy);\n return {x:c.x + dx * k, y:c.y + dy * k};\n }\n function qpoint(p0, c, p1, t){\n const u = 1 - t;\n return {x:u*u*p0.x + 2*u*t*c.x + t*t*p1.x, y:u*u*p0.y + 2*u*t*c.y + t*t*p1.y};\n }\n function cpoint(p0, c1, c2, p1, t){\n const u = 1 - t, a = u*u*u, b = 3*u*u*t, c = 3*u*t*t, d = t*t*t;\n return {x:a*p0.x + b*c1.x + c*c2.x + d*p1.x,\n y:a*p0.y + b*c1.y + c*c2.y + d*p1.y};\n }\n function hitsCard(x, y, w, h){\n for (let i = 0; i < topics.length; i++){\n const t = topics[i], th = heights.get(t.id) || 200;\n if (x < t.x + CARD_W + 6 && x + w > t.x - 6 &&\n y < t.y + th + 6 && y + h > t.y - 6) return true;\n }\n return false;\n }\n function freePointOnQuad(p0, c, p1){\n const ts = [0.5, 0.4, 0.6, 0.3, 0.7, 0.22, 0.78];\n for (let i = 0; i < ts.length; i++){\n const p = qpoint(p0, c, p1, ts[i]);\n if (!hitsCard(p.x, p.y)) return p;\n }\n return qpoint(p0, c, p1, 0.5);\n }\n function freePointOnCubic(p0, c1, c2, p1){\n const ts = [0.5, 0.42, 0.58, 0.34, 0.66, 0.26, 0.74];\n for (let i = 0; i < ts.length; i++){\n const p = cpoint(p0, c1, c2, p1, ts[i]);\n if (!hitsCard(p.x, p.y)) return p;\n }\n return cpoint(p0, c1, c2, p1, 0.5);\n }\n\n function overlaps(p, w, placed){\n for (let i = 0; i < placed.length; i++){\n const q = placed[i];\n if (Math.abs(p.x - q.x) < (w + q.w) / 2 + 8 && Math.abs(p.y - q.y) < 24) return true;\n }\n return false;\n }\n function placePill(sample, w, placed){\n const ts = [0.5, 0.56, 0.44, 0.62, 0.38, 0.68, 0.32, 0.74, 0.26, 0.8];\n for (let i = 0; i < ts.length; i++){\n const p = sample(ts[i]);\n if (!hitsCard(p.x - w / 2, p.y - 10, w, 20) && !overlaps(p, w, placed)){\n placed.push({x:p.x, y:p.y, w:w});\n return p;\n }\n }\n const p = sample(0.5);\n placed.push({x:p.x, y:p.y, w:w});\n return p;\n }\n\n function drawEdges(){\n while (svg.firstChild) svg.removeChild(svg.firstChild);\n const placed = [];\n\n links.forEach(function(l){\n const a = byId.get(l.a), b = byId.get(l.b);\n if (!a || !b) return;\n const key = linkKey(l);\n const isTree = treeKeys.has(pairKey(l.a, l.b));\n const isCrossGraph = l.crossGraph === true;\n const isLink = mode === 'link' && activeLink === key;\n const isTopic = mode === 'topic' && (l.a === activeTopic || l.b === activeTopic);\n const hot = isLink || isTopic;\n const cold = !!mode && !hot;\n if (!isTree && !showCross && !hot && !isCrossGraph) return;\n\n let d, sample;\n if (isTree){\n const pid = parentOf.get(l.b) === l.a ? l.a : l.b;\n const cid = pid === l.a ? l.b : l.a;\n const pp = pos.get(pid), pc = center(pid), cc = center(cid);\n const dir = pp.dir || (cc.x >= pc.x ? 1 : -1);\n const x1 = dir > 0 ? pp.x + CARD_W : pp.x;\n const x2 = dir > 0 ? pos.get(cid).x : pos.get(cid).x + CARD_W;\n const y1 = pc.y, y2 = cc.y;\n const bend = Math.max(34, Math.abs(x2 - x1) * 0.42);\n const p0 = {x:x1, y:y1};\n const c1 = {x:x1 + dir * bend, y:y1};\n const c2 = {x:x2 - dir * bend, y:y2};\n const p1 = {x:x2, y:y2};\n d = 'M' + x1 + ',' + y1 + ' C' + c1.x + ',' + c1.y + ' ' + c2.x + ',' + c2.y + ' ' + x2 + ',' + y2;\n sample = function(t){ return cpoint(p0, c1, c2, p1, t); };\n } else {\n const pa = pos.get(l.a), pb = pos.get(l.b);\n let p1, p2, c;\n if (pa.dir === pb.dir && pa.dir !== 0){\n const dir = pa.dir;\n p1 = {x: dir < 0 ? pa.x + CARD_W : pa.x, y: center(l.a).y};\n p2 = {x: dir < 0 ? pb.x + CARD_W : pb.x, y: center(l.b).y};\n const outX = dir < 0 ? Math.max(p1.x, p2.x) + 64 : Math.min(p1.x, p2.x) - 64;\n c = {x: outX, y: (p1.y + p2.y) / 2};\n } else {\n const ca = center(l.a), cb = center(l.b);\n p1 = {x: ca.x, y: pa.y};\n p2 = {x: cb.x, y: pb.y};\n c = {x: (p1.x + p2.x) / 2, y: Math.min(p1.y, p2.y) - 112};\n }\n d = 'M' + p1.x + ',' + p1.y + ' Q' + c.x + ',' + c.y + ' ' + p2.x + ',' + p2.y;\n sample = function(t){ return qpoint(p1, c, p2, t); };\n }\n\n const path = document.createElementNS(NS, 'path');\n path.setAttribute('d', d);\n path.setAttribute('class', 'edge' + (!isTree || isCrossGraph ? ' cross' : '') + (hot ? ' hot' : cold ? ' cold' : ''));\n svg.appendChild(path);\n\n const label = l.label || (a.title + ' ↔ ' + b.title);\n const w = Math.max(42, label.length * 10.8 + 16);\n const pillAt = placePill(sample, w, placed);\n\n const g = document.createElementNS(NS, 'g');\n g.setAttribute('class', 'pill' + (hot ? ' hot' : cold ? ' cold' : ''));\n g.setAttribute('data-key', key);\n g.setAttribute('tabindex', '0');\n g.setAttribute('role', 'button');\n g.setAttribute('aria-label', '关系:' + label);\n\n const rect = document.createElementNS(NS, 'rect');\n rect.setAttribute('x', pillAt.x - w / 2); rect.setAttribute('y', pillAt.y - 10);\n rect.setAttribute('width', w); rect.setAttribute('height', 20);\n rect.setAttribute('rx', 10);\n const text = document.createElementNS(NS, 'text');\n text.setAttribute('x', pillAt.x); text.setAttribute('y', pillAt.y + 3.6);\n text.setAttribute('text-anchor', 'middle');\n text.textContent = label;\n\n g.appendChild(rect); g.appendChild(text);\n g.addEventListener('click', function(e){ e.stopPropagation(); selectLink(key); });\n g.addEventListener('keydown', function(e){\n if (e.key === 'Enter' || e.key === ' '){ e.preventDefault(); selectLink(key); }\n });\n svg.appendChild(g);\n });\n }\n\n // ---------- camera ----------\n function apply(){\n world.style.transform = 'translate(' + view.x + 'px,' + view.y + 'px) scale(' + view.s + ')';\n zoomLabel.textContent = Math.round(view.s * 100) + '%';\n }\n function clampScale(s){ return Math.max(0.22, Math.min(2.0, s)); }\n function zoomAt(px, py, k){\n const s2 = clampScale(view.s * k);\n if (s2 === view.s) return;\n view.x = px - (px - view.x) * (s2 / view.s);\n view.y = py - (py - view.y) * (s2 / view.s);\n view.s = s2;\n apply(); userMoved = true;\n }\n function bbox(){\n let x1 = Infinity, y1 = Infinity, x2 = -Infinity, y2 = -Infinity;\n topics.forEach(function(t){\n const h = heights.get(t.id) || 200;\n x1 = Math.min(x1, t.x); y1 = Math.min(y1, t.y);\n x2 = Math.max(x2, t.x + CARD_W); y2 = Math.max(y2, t.y + h);\n });\n return {x1:x1, y1:y1, x2:x2, y2:y2};\n }\n function fit(animate){\n const b = bbox();\n const pad = 70;\n const vw = stage.clientWidth, vh = stage.clientHeight;\n const s = clampScale(Math.min((vw - pad * 2) / (b.x2 - b.x1), (vh - pad * 2) / (b.y2 - b.y1), 1));\n const nx = (vw - (b.x2 - b.x1) * s) / 2 - b.x1 * s;\n const ny = (vh - (b.y2 - b.y1) * s) / 2 - b.y1 * s;\n if (animate) tweenTo(nx, ny, s); else { view.x = nx; view.y = ny; view.s = s; apply(); }\n userMoved = false;\n }\n let raf = null;\n function tweenTo(x2, y2, s2){\n cancelAnimationFrame(raf);\n const x1 = view.x, y1 = view.y, s1 = view.s, t0 = performance.now(), dur = 320;\n function step(now){\n const p = Math.min(1, (now - t0) / dur);\n const e = 1 - Math.pow(1 - p, 3);\n view.x = x1 + (x2 - x1) * e;\n view.y = y1 + (y2 - y1) * e;\n view.s = s1 + (s2 - s1) * e;\n apply();\n if (p < 1) raf = requestAnimationFrame(step);\n }\n raf = requestAnimationFrame(step);\n }\n function centerOnScale(id, s, animate){\n const t = byId.get(id); if (!t) return;\n const h = heights.get(id) || 200;\n const x = stage.clientWidth / 2 - (t.x + CARD_W / 2) * s;\n const y = stage.clientHeight / 2 - (t.y + h / 2) * s;\n if (animate) tweenTo(x, y, s);\n else { view.x = x; view.y = y; view.s = s; apply(); }\n userMoved = true;\n }\n\n // A topic jump keeps whatever zoom the reader chose; only the explicit reset\n // control and a graph switch change the scale.\n function centerOn(id){\n centerOnScale(id, view.s, true);\n }\n\n function resetZoom(){\n const target = (mode === 'topic' && activeTopic) ? activeTopic : layoutRootId;\n centerOnScale(target, 1, true);\n }\n\n // ---------- pan & zoom ----------\n let panning = false, panMoved = false, px = 0, py = 0;\n stage.addEventListener('pointerdown', function(e){\n if (e.target.closest('.card') || e.target.closest('.pill') || e.target.closest('#panel')) return;\n panning = true; panMoved = false; px = e.clientX; py = e.clientY;\n stage.classList.add('grabbing');\n stage.setPointerCapture(e.pointerId);\n });\n stage.addEventListener('pointermove', function(e){\n if (!panning) return;\n if (Math.abs(e.clientX - px) + Math.abs(e.clientY - py) > 3) panMoved = true;\n view.x += e.clientX - px; view.y += e.clientY - py;\n px = e.clientX; py = e.clientY;\n apply(); userMoved = true;\n });\n function endPan(e){\n if (!panning) return;\n panning = false; stage.classList.remove('grabbing');\n try { stage.releasePointerCapture(e.pointerId); } catch(_){}\n if (!panMoved && mode) closePanel();\n }\n stage.addEventListener('pointerup', endPan);\n stage.addEventListener('pointercancel', endPan);\n stage.addEventListener('wheel', function(e){\n e.preventDefault();\n zoomAt(e.clientX, e.clientY, Math.exp(-e.deltaY * 0.0011));\n }, {passive:false});\n document.getElementById('zin').addEventListener('click', function(){\n zoomAt(stage.clientWidth / 2, stage.clientHeight / 2, 1.22);\n });\n document.getElementById('zout').addEventListener('click', function(){\n zoomAt(stage.clientWidth / 2, stage.clientHeight / 2, 1 / 1.22);\n });\n document.getElementById('fit').addEventListener('click', function(){ fit(true); });\n document.getElementById('zoomLabel').addEventListener('click', resetZoom);\n document.getElementById('relayout').addEventListener('click', function(){\n layout(); fit(true); drawEdges();\n });\n document.getElementById('cross').addEventListener('click', function(){\n showCross = !showCross;\n this.classList.toggle('on', showCross);\n this.setAttribute('aria-pressed', showCross ? 'true' : 'false');\n drawEdges();\n });\n stage.addEventListener('dblclick', function(e){ if (!e.target.closest('.card')) fit(true); });\n\n // ---------- card drag ----------\n let drag = null;\n function onCardDown(e){\n if (e.button !== 0) return;\n e.stopPropagation();\n const id = e.currentTarget.dataset.id;\n const t = byId.get(id);\n const el = cardEl.get(id);\n drag = {id:id, sx:e.clientX, sy:e.clientY, ox:t.x, oy:t.y, moved:false, el:el};\n el.classList.add('dragging');\n window.addEventListener('pointermove', onDragMove);\n window.addEventListener('pointerup', onDragUp);\n }\n function onDragMove(e){\n if (!drag) return;\n const dx = (e.clientX - drag.sx) / view.s;\n const dy = (e.clientY - drag.sy) / view.s;\n if (Math.abs(dx) + Math.abs(dy) > 3) drag.moved = true;\n const t = byId.get(drag.id);\n t.x = drag.ox + dx; t.y = drag.oy + dy;\n const p = pos.get(drag.id); p.x = t.x; p.y = t.y;\n drag.el.style.left = t.x + 'px';\n drag.el.style.top = t.y + 'px';\n drawEdges();\n }\n function onDragUp(){\n window.removeEventListener('pointermove', onDragMove);\n window.removeEventListener('pointerup', onDragUp);\n if (!drag) return;\n drag.el.classList.remove('dragging');\n const id = drag.id, moved = drag.moved;\n drag = null;\n if (!moved) selectTopic(id);\n userMoved = true;\n }\n\n // ---------- selection ----------\n function paint(){\n cardEl.forEach(function(el, cid){\n let sel = false, dim = false;\n if (mode === 'topic'){ sel = cid === activeTopic; dim = !sel; }\n else if (mode === 'link'){\n const l = links.find(function(x){ return linkKey(x) === activeLink; });\n sel = !!l && (cid === l.a || cid === l.b);\n dim = !sel;\n }\n el.classList.toggle('selected', sel);\n el.classList.toggle('dim', dim);\n });\n }\n function notifySelection(topicId){\n try {\n parent.postMessage({\n type: 'kg:selection',\n graphId: (DATA.graphs[activeGraph] || {}).id || null,\n topicId: topicId || null\n }, '*');\n } catch (_) {}\n }\n function selectTopic(id){\n const clicked = byId.get(id);\n if (clicked && clicked.sourceGraphId){\n // A card in 总图 is a namespaced copy. Selecting it must land on the real\n // graph and node, not open a detail panel for a computed duplicate.\n try {\n parent.postMessage({\n type: 'kg:open-source',\n graphId: clicked.sourceGraphId,\n topicId: clicked.sourceNodeId || id\n }, '*');\n } catch (_) {}\n return;\n }\n if (mode === 'topic' && activeTopic === id){ closePanel(); return; }\n mode = 'topic'; activeTopic = id; activeLink = null;\n paint(); drawEdges(); openTopicPanel(id); setHash(id);\n notifySelection(id);\n }\n function selectLink(key){\n if (mode === 'link' && activeLink === key){ closePanel(); return; }\n mode = 'link'; activeLink = key; activeTopic = null;\n paint(); drawEdges(); openLinkPanel(key); setHash(key);\n }\n function closePanel(){\n mode = null; activeTopic = null; activeLink = null;\n paint(); drawEdges();\n panel.classList.remove('open');\n panel.setAttribute('aria-hidden', 'true');\n document.body.classList.remove('panel-open');\n setHash(null);\n notifySelection(null);\n }\n document.getElementById('close').addEventListener('click', closePanel);\n document.addEventListener('keydown', function(e){ if (e.key === 'Escape') closePanel(); });\n\n function showPanel(kicker, title, html){\n document.getElementById('p-kicker').textContent = kicker;\n document.getElementById('p-title').textContent = title;\n const body = document.getElementById('p-body');\n body.innerHTML = html;\n body.scrollTop = 0;\n body.querySelectorAll('.rel').forEach(function(btn){\n btn.addEventListener('click', function(){\n const to = btn.dataset.to;\n selectTopic(to); centerOn(to);\n });\n });\n body.querySelectorAll('.p-doc-item[data-doc-path]').forEach(function(item){\n item.addEventListener('click', function(){\n try { parent.postMessage({ type: 'kg:open-document', path: item.dataset.docPath }, '*'); } catch (_) {}\n });\n });\n panel.classList.add('open');\n panel.setAttribute('aria-hidden', 'false');\n document.body.classList.add('panel-open');\n }\n function inline(s){\n s = esc(s);\n s = s.replace(/`([^`]+)`/g, '<code>$1</code>');\n s = s.replace(/\\*\\*([^*]+)\\*\\*/g, '<strong>$1</strong>');\n s = s.replace(/\\[([^\\]]+)\\]\\(([^)]+)\\)/g, '<a href=\"$2\" target=\"_blank\" rel=\"noopener\">$1</a>');\n return s;\n }\n function renderMarkdown(md){\n const lines = String(md || '').split('\\n');\n let html = '', inCode = false, code = [], list = null;\n function closeList(){ if (list){ html += '</' + list + '>'; list = null; } }\n lines.forEach(function(line){\n if (/^```/.test(line)){\n if (inCode){ html += '<pre><code>' + esc(code.join('\\n')) + '</code></pre>'; code = []; inCode = false; }\n else { closeList(); inCode = true; }\n return;\n }\n if (inCode){ code.push(line); return; }\n if (!line.trim()){ closeList(); return; }\n let m;\n if ((m = line.match(/^(#{1,3})\\s+(.*)$/))){\n closeList();\n const lv = Math.min(3, m[1].length);\n html += '<h' + lv + '>' + inline(m[2]) + '</h' + lv + '>';\n } else if ((m = line.match(/^\\s*[-*]\\s+(.*)$/))){\n if (list !== 'ul'){ closeList(); html += '<ul>'; list = 'ul'; }\n html += '<li>' + inline(m[1]) + '</li>';\n } else if ((m = line.match(/^\\s*\\d+\\.\\s+(.*)$/))){\n if (list !== 'ol'){ closeList(); html += '<ol>'; list = 'ol'; }\n html += '<li>' + inline(m[1]) + '</li>';\n } else if ((m = line.match(/^>\\s?(.*)$/))){\n closeList();\n html += '<blockquote>' + inline(m[1]) + '</blockquote>';\n } else {\n closeList();\n html += '<p>' + inline(line) + '</p>';\n }\n });\n if (inCode) html += '<pre><code>' + esc(code.join('\\n')) + '</code></pre>';\n closeList();\n return html;\n }\n function field(k, v){\n return '<div class=\"p-field\"><b>' + k + '</b><span>' + esc(v || '未登记') + '</span></div>';\n }\n function openTopicPanel(id){\n const t = byId.get(id);\n const rels = links.filter(function(l){ return l.a === id || l.b === id; });\n let html = '<div class=\"p-doc\">' + renderMarkdown(t.body || t.summary || '') + '</div>';\n if (t.documents && t.documents.length){\n html += '<div class=\"p-rel-title\">文档 · ' + t.documents.length + ' 篇</div>';\n t.documents.forEach(function(d){\n html += '<div class=\"p-doc-item\" data-doc-path=\"' + esc(d.path) + '\" role=\"button\" tabindex=\"0\" style=\"cursor:pointer\">' + inlineCover(d) + '<div class=\"m\">' +\n '<b>' + esc(d.title) + badgesHtml(d) + '</b><span>' + esc(d.file) + ' · ' + esc(d.date) + '</span></div></div>';\n });\n }\n html += '<div class=\"p-rel-title\">关系 · ' + rels.length + ' 篇</div>';\n rels.forEach(function(l){\n const other = l.a === id ? l.b : l.a;\n const o = byId.get(other);\n html += '<button class=\"rel\" data-to=\"' + esc(other) + '\"><b>' + esc(o ? o.title : other) +\n '</b><span>' + esc(l.body || '') + '</span></button>';\n });\n if (!rels.length) html += '<div class=\"p-docs\">还没有关系文档。孤立的线价值很低。</div>';\n html += '<div class=\"p-docs\">文档:' + ((t.documents || []).length) + ' 个文件</div>';\n showPanel((t.domain ? t.domain + ' · ' : '') + statusText(t.status) + ' · depth ' + t.depth + '/5', t.title, html);\n }\n function openLinkPanel(key){\n const l = links.find(function(x){ return linkKey(x) === key; });\n if (!l) return;\n const a = byId.get(l.a), b = byId.get(l.b);\n let html = field('关系', l.body);\n html += '<div class=\"p-rel-title\">两端</div>';\n html += '<button class=\"rel\" data-to=\"' + esc(l.a) + '\"><b>' + esc(a ? a.title : l.a) +\n '</b><span>' + esc(a ? a.summary : '') + '</span></button>';\n html += '<button class=\"rel\" data-to=\"' + esc(l.b) + '\"><b>' + esc(b ? b.title : l.b) +\n '</b><span>' + esc(b ? b.summary : '') + '</span></button>';\n showPanel('关系文档' + (l.updated ? ' · ' + l.updated : ''),\n (a ? a.title : l.a) + ' ↔ ' + (b ? b.title : l.b), html);\n }\n function setHash(v){\n try { history.replaceState(null, '', v ? '#' + v : location.pathname + location.search); } catch(_){}\n }\n\n // ---------- graph switching ----------\n /** Floating breadcrumb: graph scope / group / graph name. Parent segments close\n the detail panel and return to the graph root; there is no separate list view. */\n function renderCrumb(){\n const el = document.getElementById('kg-crumb');\n if (!el) return;\n const g = DATA.graphs[activeGraph];\n if (!g) { el.hidden = true; return; }\n const parts = ['<button class=\"seg\" data-level=\"0\">知识图谱</button>'];\n if (g.group) parts.push('<span class=\"sep\">/</span><button class=\"seg\" data-level=\"1\">' + esc(g.group) + '</button>');\n parts.push('<span class=\"sep\">/</span><b>' + esc(g.name) + '</b>');\n el.innerHTML = parts.join('');\n el.hidden = false;\n el.querySelectorAll('button[data-level]').forEach(function(btn){\n btn.addEventListener('click', function(){\n closePanel();\n centerOnScale(layoutRootId, view.s, true);\n });\n });\n }\n\n function loadGraph(idx){\n const g = DATA.graphs[idx];\n if (!g) return;\n closePanel();\n activeGraph = idx;\n // The overview is the only graph that draws its cross-graph links by default:\n // crossing source graphs is its purpose, so the dashed edges are not hidden\n // behind the ordinary cross-link toggle.\n showCross = g.format === 'overview';\n const crossBtn = document.getElementById('cross');\n if (crossBtn) {\n crossBtn.classList.toggle('on', showCross);\n crossBtn.setAttribute('aria-pressed', showCross ? 'true' : 'false');\n }\n topics = g.topics;\n links = g.links;\n byId = new Map(topics.map(function(t){ return [t.id, t]; }));\n cardEl.forEach(function(el){ el.remove(); });\n cardEl.clear();\n while (svg.firstChild) svg.removeChild(svg.firstChild);\n heights = new Map(); subH = new Map(); pos = new Map();\n\n topics.forEach(buildCard);\n if (!topics.length){\n renderCrumb();\n drawEdges();\n showEmpty(true);\n return;\n }\n layout();\n apply();\n renderCrumb();\n\n requestAnimationFrame(function(){\n // First entry and every graph switch start at 1:1. The reader asked for a\n // true-scale canvas; fitting the whole graph on open made every card's\n // 12-13px copy render at 64%. Panning still reaches the rest.\n centerOnScale(layoutRootId, 1, false);\n drawEdges();\n });\n }\n\n // ---------- the embedding host ----------\n const emptyEl = document.getElementById('kg-empty');\n\n // The host's alias tokens, read from the parent document (same origin) and kept\n // live by the panel's postMessage. Reading the parent on boot avoids a flash of\n // the wrong scheme before the first message; the message is still required for\n // a later theme switch.\n const THEME_TOKENS = [\n '--dsw-alias-bg-base', '--dsw-alias-bg-layer-1', '--dsw-alias-bg-layer-2',\n '--dsw-alias-label-primary', '--dsw-alias-label-secondary', '--dsw-alias-label-tertiary',\n '--dsw-alias-border-l1', '--dsw-alias-border-l2',\n '--dsw-alias-state-business-primary', '--dsw-alias-link',\n '--dsw-alias-state-success-primary', '--dsw-alias-state-warn-primary',\n '--dsw-elevation-panel'\n ];\n\n function readHostTheme(){\n try {\n const doc = parent.document;\n const bodyStyle = parent.getComputedStyle(doc.body);\n const rootStyle = parent.getComputedStyle(doc.documentElement);\n const tokens = {};\n THEME_TOKENS.forEach(function(name){\n const value = (bodyStyle.getPropertyValue(name) || rootStyle.getPropertyValue(name) || '').trim();\n if (value !== '') tokens[name] = value;\n });\n return { tokens: tokens, dark: doc.body.hasAttribute('data-ds-dark-theme') };\n } catch (_) {\n return null;\n }\n }\n\n function applyTheme(theme){\n if (!theme || !theme.tokens) return;\n const root = document.documentElement;\n Object.keys(theme.tokens).forEach(function(name){\n root.style.setProperty(name, theme.tokens[name]);\n });\n root.style.colorScheme = theme.dark ? 'dark' : 'light';\n document.body.toggleAttribute('data-ds-dark-theme', !!theme.dark);\n }\n\n applyTheme(readHostTheme());\n\n function showEmpty(show){\n if (emptyEl) emptyEl.hidden = !show;\n const stageEl = document.getElementById('stage');\n if (stageEl) stageEl.style.visibility = show ? 'hidden' : 'visible';\n const controlsEl = document.getElementById('controls');\n if (controlsEl) controlsEl.hidden = show;\n const zoomEl = document.getElementById('zoomLabel');\n if (zoomEl) zoomEl.hidden = show;\n }\n\n function postReady(){\n try { parent.postMessage({ type: 'kg:ready' }, '*'); } catch (_) {}\n }\n\n function applyPayload(payload){\n if (!payload || !Array.isArray(payload.graphs)) return;\n DATA.graphs = payload.graphs;\n if (!DATA.graphs.length){\n showEmpty(true);\n postReady();\n return;\n }\n showEmpty(false);\n const wanted = payload.activeGraphId\n ? DATA.graphs.findIndex(function(g){ return g.id === payload.activeGraphId; })\n : -1;\n const idx = wanted >= 0 ? wanted : 0;\n loadGraph(idx);\n if (payload.selectedTopicId){\n requestAnimationFrame(function(){ focusTopic(payload.selectedTopicId); });\n }\n postReady();\n }\n\n function focusTopic(id){\n const t = byId.get(id);\n if (!t) return;\n selectTopic(id);\n centerOn(id);\n }\n\n function selectGraphById(id){\n const idx = DATA.graphs.findIndex(function(g){ return g.id === id; });\n if (idx < 0) return;\n showEmpty(false);\n loadGraph(idx);\n }\n\n window.addEventListener('message', function(event){\n const msg = event.data || {};\n if (msg.type === 'kg:set-graphs') applyPayload(msg);\n else if (msg.type === 'kg:select-graph') selectGraphById(msg.graphId);\n else if (msg.type === 'kg:select-topic') focusTopic(msg.topicId);\n else if (msg.type === 'kg:theme') applyTheme(msg);\n });\n\n showEmpty(true);\n postReady();\n window.addEventListener('resize', function(){\n if (!userMoved) centerOnScale(layoutRootId, view.s, false);\n drawEdges();\n });\n\n window.__KG_VIEW__ = {data:DATA, selectTopic:selectTopic, selectLink:selectLink, fit:fit};\n})();\n<\/script>\n</body>\n</html>\n";
2913
2913
  //#endregion
2914
2914
  //#region src/outlineText.ts
2915
2915
  /**
@@ -9269,9 +9269,28 @@ const run$3 = async (operation) => {
9269
9269
  function graphCreateHint(id = "<graph-id>", name = "<图谱名称>") {
9270
9270
  return "kg_add {\"kind\":\"graph\",\"scope\":\"personal\",\"id\":" + JSON.stringify(id) + ",\"name\":" + JSON.stringify(name) + "}";
9271
9271
  }
9272
+ /**
9273
+ * Resolve a short overview spelling.
9274
+ *
9275
+ * `null` means the bare `总图` / `__overview__`, which prefers the caller's
9276
+ * personal overview. A level means `global/__overview__` or
9277
+ * `department/总图`-style spelling. `undefined` means "not an overview alias".
9278
+ */
9279
+ function overviewAliasLevel(value) {
9280
+ const needle = value.trim();
9281
+ if (needle === "__overview__" || needle === "总图") return null;
9282
+ for (const level of OVERVIEW_LEVELS) if (needle === level + "/__overview__" || needle === level + "/总图") return level;
9283
+ }
9272
9284
  /** Resolve one graph by id, path or unique name. */
9273
9285
  function requireGraph(graphs, value) {
9274
9286
  const needle = value.trim();
9287
+ const alias = overviewAliasLevel(needle);
9288
+ if (alias !== void 0) {
9289
+ const overviews = graphs.filter(isOverviewGraph);
9290
+ const match = alias === null ? overviews.find((graph) => graph.scope === "personal") ?? (overviews.length === 1 ? overviews[0] : void 0) : overviews.find((graph) => graph.scope === alias);
9291
+ if (match !== void 0) return match;
9292
+ if (alias === null && overviews.length > 1) throw new KnowledgeToolError("invalid", "there are several overview graphs; pass global/__overview__, department/__overview__ or personal/__overview__");
9293
+ }
9275
9294
  const found = graphs.filter((graph) => graph.id === needle || graph.path === needle || graph.name === needle);
9276
9295
  if (found.length === 1) return found[0];
9277
9296
  if (found.length === 0) {
@@ -10295,6 +10314,1047 @@ function edgeSummary(store, edge) {
10295
10314
  missing: edge.missing
10296
10315
  };
10297
10316
  }
10317
+ /** Display name shared by the three scope-level overviews. */
10318
+ const OVERVIEW_GRAPH_NAME = "总图";
10319
+ /** The three knowledge scopes, each with its own overview. */
10320
+ const OVERVIEW_LEVELS = [
10321
+ "global",
10322
+ "department",
10323
+ "personal"
10324
+ ];
10325
+ /** Build a `links.json` store for one Host and scope. */
10326
+ var JsonOverviewStore = class {
10327
+ host;
10328
+ now;
10329
+ storeDir;
10330
+ scope;
10331
+ links;
10332
+ storeIssues = [];
10333
+ used;
10334
+ rev = 0;
10335
+ /** The file this store last read, so a standalone flat layout writes back to it. */
10336
+ pathUsed;
10337
+ constructor(host, scope, now = Date.now, storeDir) {
10338
+ this.host = host;
10339
+ this.now = now;
10340
+ this.storeDir = storeDir;
10341
+ this.scope = scope;
10342
+ this.used = now();
10343
+ this.pathUsed = scope.actualPath + "/links.json";
10344
+ }
10345
+ async open() {
10346
+ if (this.links !== void 0) return;
10347
+ const state = await loadOverviewLinks(this.host, this.scope);
10348
+ this.links = state.links;
10349
+ this.storeIssues = state.issues;
10350
+ this.pathUsed = state.actualPath;
10351
+ this.used = this.now();
10352
+ this.rev += 1;
10353
+ }
10354
+ async query() {
10355
+ await this.open();
10356
+ this.used = this.now();
10357
+ return [...this.links ?? []];
10358
+ }
10359
+ async replace(links) {
10360
+ await writeOverviewLinks(this.host, this.pathUsed, renderOverviewLinks(links));
10361
+ this.links = [...links];
10362
+ this.storeIssues = [];
10363
+ this.used = this.now();
10364
+ this.rev += 1;
10365
+ }
10366
+ close() {
10367
+ this.links = void 0;
10368
+ }
10369
+ lastUsed() {
10370
+ return this.used;
10371
+ }
10372
+ revision() {
10373
+ return String(this.rev) + ":" + (this.links === void 0 ? "closed" : JSON.stringify(this.links));
10374
+ }
10375
+ estimatedBytes() {
10376
+ return this.links === void 0 ? 0 : JSON.stringify(this.links).length * 2;
10377
+ }
10378
+ issues() {
10379
+ return this.storeIssues;
10380
+ }
10381
+ /**
10382
+ * Persist the derived read model under the probed store root.
10383
+ *
10384
+ * This snapshot is not the source of truth — `links.json` is — so a failed
10385
+ * write never blocks a read and a missing store root simply skips it. It gives
10386
+ * the future Relate adapter a concrete, probe-tested location to replace.
10387
+ */
10388
+ async materialize(aggregate) {
10389
+ const root = typeof this.storeDir === "function" ? this.storeDir() : this.storeDir;
10390
+ if (root === void 0 || root === "") return;
10391
+ const directory = join(root, this.scope.level);
10392
+ await mkdir(directory, { recursive: true });
10393
+ const name = this.scope.actualPath.replace(/[^A-Za-z0-9._-]+/gu, "_") + ".json";
10394
+ const handle = await open(join(directory, name), "w");
10395
+ try {
10396
+ await handle.writeFile(JSON.stringify({
10397
+ schemaVersion: 1,
10398
+ revision: this.revision(),
10399
+ scope: this.scope,
10400
+ aggregate
10401
+ }, null, 2));
10402
+ await handle.sync();
10403
+ } finally {
10404
+ await handle.close();
10405
+ }
10406
+ }
10407
+ };
10408
+ /** The default MVP provider: one `links.json` per scope plus a JSON read-model snapshot. */
10409
+ var JsonOverviewStoreProvider = class {
10410
+ host;
10411
+ storeDir;
10412
+ constructor(host, storeDir) {
10413
+ this.host = host;
10414
+ this.storeDir = storeDir;
10415
+ }
10416
+ async open(scope) {
10417
+ const store = new JsonOverviewStore(this.host, scope, Date.now, this.storeDir?.());
10418
+ await store.open();
10419
+ return store;
10420
+ }
10421
+ };
10422
+ /** Where the store goes when the KB root cannot satisfy the probe. */
10423
+ const OVERVIEW_STORE_FALLBACK_DIR = "/var/lib/dataops/kb-overview";
10424
+ /** Probe one directory: open/write/fsync/read/lock, cleaning up after itself. */
10425
+ async function probeOverviewStoreOnce(dir) {
10426
+ const checks = {
10427
+ open: false,
10428
+ write: false,
10429
+ fsync: false,
10430
+ read: false,
10431
+ lock: false
10432
+ };
10433
+ const probeFile = join(dir, ".probe-" + String(process.pid) + "-" + String(Date.now()));
10434
+ const lockFile = join(dir, ".probe-lock-" + String(process.pid) + "-" + String(Date.now()));
10435
+ try {
10436
+ await mkdir(dir, { recursive: true });
10437
+ checks.open = true;
10438
+ const handle = await open(probeFile, "w");
10439
+ try {
10440
+ await handle.writeFile("kb-overview-probe\n");
10441
+ checks.write = true;
10442
+ await handle.sync();
10443
+ checks.fsync = true;
10444
+ } finally {
10445
+ await handle.close();
10446
+ }
10447
+ checks.read = await readFile(probeFile, "utf8") === "kb-overview-probe\n";
10448
+ const lock = await open(lockFile, "wx");
10449
+ checks.lock = true;
10450
+ await lock.close();
10451
+ return {
10452
+ ok: Object.values(checks).every(Boolean),
10453
+ checks
10454
+ };
10455
+ } catch (error) {
10456
+ return {
10457
+ ok: false,
10458
+ checks,
10459
+ error: messageOf$2(error)
10460
+ };
10461
+ } finally {
10462
+ await unlink(probeFile).catch(() => void 0);
10463
+ await unlink(lockFile).catch(() => void 0);
10464
+ }
10465
+ }
10466
+ /**
10467
+ * Probe the configured overview store root and fall back when it is unusable.
10468
+ *
10469
+ * A KB root may be a read-only NAS, an unmounted share, or a filesystem without
10470
+ * the lock/fsync semantics a store needs. The probe never assumes availability:
10471
+ * it creates a file, fsyncs it, reads it back and takes an exclusive lock, then
10472
+ * removes both artifacts. A failed requested root moves the store to
10473
+ * {@link OVERVIEW_STORE_FALLBACK_DIR}; reads keep working either way.
10474
+ */
10475
+ async function probeOverviewStoreDir(requested, fallbackDir = OVERVIEW_STORE_FALLBACK_DIR) {
10476
+ const primary = await probeOverviewStoreOnce(requested);
10477
+ const result = primary.ok ? {
10478
+ dir: requested,
10479
+ requested,
10480
+ fallback: false,
10481
+ ok: true,
10482
+ checks: primary.checks
10483
+ } : await (async () => {
10484
+ const fallback = await probeOverviewStoreOnce(fallbackDir);
10485
+ return {
10486
+ dir: fallbackDir,
10487
+ requested,
10488
+ fallback: true,
10489
+ ok: fallback.ok,
10490
+ checks: fallback.checks,
10491
+ ...primary.error === void 0 && fallback.error === void 0 ? {} : { error: [primary.error, fallback.error].filter((item) => item !== void 0).join("; ") }
10492
+ };
10493
+ })();
10494
+ await writeFile(join(result.dir, "manifest.json"), JSON.stringify({
10495
+ backend: "json",
10496
+ schemaVersion: 1,
10497
+ metric: "kb.overview.store.probe",
10498
+ at: (/* @__PURE__ */ new Date()).toISOString(),
10499
+ ...result
10500
+ }, null, 2) + "\n").catch(() => void 0);
10501
+ return result;
10502
+ }
10503
+ /** TTL floors/ceilings in minutes, per the approved memory lifecycle. */
10504
+ const OVERVIEW_TTL_MINUTES = {
10505
+ personal: {
10506
+ min: 5,
10507
+ max: 10,
10508
+ fallback: 10
10509
+ },
10510
+ department: {
10511
+ min: 15,
10512
+ max: 30,
10513
+ fallback: 20
10514
+ },
10515
+ global: {
10516
+ min: 30,
10517
+ max: 60,
10518
+ fallback: 45
10519
+ }
10520
+ };
10521
+ /**
10522
+ * Lifecycle owner for every overview store.
10523
+ *
10524
+ * The approved model is per scope: global and department stores are shared by
10525
+ * everyone allowed to read that scope, while a personal store belongs to exactly
10526
+ * one user. Stores load on first use, stay open while an operation holds a
10527
+ * reference, and are evicted by idle TTL, LRU count and the memory budget.
10528
+ *
10529
+ * `rebuild()` opens the replacement completely before swapping it into the map
10530
+ * and closing the old one, so a reader never observes a half-built store. A future
10531
+ * auth/logout hook calls {@link closePersonal}; plugin disposal calls
10532
+ * {@link closeAll}.
10533
+ */
10534
+ var OverviewStoreManager = class {
10535
+ provider;
10536
+ entries = /* @__PURE__ */ new Map();
10537
+ ttlMs;
10538
+ maxStores;
10539
+ memoryBudgetBytes;
10540
+ now;
10541
+ constructor(provider, options = {}) {
10542
+ this.provider = provider;
10543
+ this.now = options.now ?? Date.now;
10544
+ this.ttlMs = {
10545
+ personal: clampTtl("personal", options.ttlMs?.personal),
10546
+ department: clampTtl("department", options.ttlMs?.department),
10547
+ global: clampTtl("global", options.ttlMs?.global)
10548
+ };
10549
+ this.maxStores = Math.max(1, options.maxStores ?? 64);
10550
+ this.memoryBudgetBytes = Math.max(0, options.memoryBudgetBytes ?? 33554432);
10551
+ }
10552
+ /** Key a store by level + authoritative base; personal therefore includes the uid. */
10553
+ keyOf(scope) {
10554
+ return scope.level + ":" + scope.actualPath;
10555
+ }
10556
+ /** Open (or reuse) one store and take a reference. */
10557
+ async acquire(scope) {
10558
+ const key = this.keyOf(scope);
10559
+ let entry = this.entries.get(key);
10560
+ if (entry === void 0) {
10561
+ const store = await this.provider.open(scope);
10562
+ entry = {
10563
+ store,
10564
+ refs: 0,
10565
+ lastUsed: store.lastUsed()
10566
+ };
10567
+ this.entries.set(key, entry);
10568
+ }
10569
+ entry.refs += 1;
10570
+ entry.lastUsed = this.now();
10571
+ this.sweep();
10572
+ return entry.store;
10573
+ }
10574
+ /** Drop one reference; eviction happens on the next sweep. */
10575
+ release(store) {
10576
+ const entry = this.entries.get(this.keyOf(store.scope));
10577
+ if (entry === void 0 || entry.store !== store) return;
10578
+ entry.refs = Math.max(0, entry.refs - 1);
10579
+ entry.lastUsed = this.now();
10580
+ }
10581
+ /**
10582
+ * Close every personal store that belongs to one user.
10583
+ *
10584
+ * The future managed-auth logout/revocation hook calls this; the JSON MVP also
10585
+ * relies on it when a caller disappears, so a shared process never keeps another
10586
+ * user's personal snapshot alive.
10587
+ */
10588
+ closePersonal(userId) {
10589
+ const marker = "personal/" + userId + "/.graphs/__overview__";
10590
+ for (const [key, entry] of this.entries) {
10591
+ if (entry.store.scope.level !== "personal") continue;
10592
+ if (entry.store.scope.actualPath !== marker && !entry.store.scope.actualPath.endsWith("/" + marker)) continue;
10593
+ entry.store.close();
10594
+ this.entries.delete(key);
10595
+ }
10596
+ }
10597
+ /** Plugin disposal / process exit: close every store once. */
10598
+ closeAll() {
10599
+ for (const entry of this.entries.values()) entry.store.close();
10600
+ this.entries.clear();
10601
+ }
10602
+ /**
10603
+ * Replace one scope's store atomically.
10604
+ *
10605
+ * The new store is opened in full first; only then does the map switch to it and
10606
+ * the old store close. A failed open leaves readers on the old snapshot.
10607
+ */
10608
+ async rebuild(scope) {
10609
+ const key = this.keyOf(scope);
10610
+ const fresh = await this.provider.open(scope);
10611
+ await fresh.open();
10612
+ const previous = this.entries.get(key);
10613
+ this.entries.set(key, {
10614
+ store: fresh,
10615
+ refs: previous?.refs ?? 0,
10616
+ lastUsed: this.now()
10617
+ });
10618
+ previous?.store.close();
10619
+ return fresh;
10620
+ }
10621
+ /** Evict idle stores by TTL, then by LRU count, then by memory budget. */
10622
+ sweep(at = this.now()) {
10623
+ for (const [key, entry] of [...this.entries]) {
10624
+ if (entry.refs > 0) continue;
10625
+ if (at - entry.lastUsed <= this.ttlMs[entry.store.scope.level]) continue;
10626
+ entry.store.close();
10627
+ this.entries.delete(key);
10628
+ }
10629
+ this.evictToCount(this.maxStores);
10630
+ while (this.cachedBytes() > this.memoryBudgetBytes) if (!this.evictOneIdleLru()) break;
10631
+ }
10632
+ /** Cached store count, for diagnostics and tests. */
10633
+ size() {
10634
+ return this.entries.size;
10635
+ }
10636
+ /** Cached footprint, for diagnostics and tests. */
10637
+ cachedBytes() {
10638
+ let total = 0;
10639
+ for (const entry of this.entries.values()) total += entry.store.estimatedBytes();
10640
+ return total;
10641
+ }
10642
+ evictToCount(limit) {
10643
+ while (this.entries.size > limit && this.evictOneIdleLru());
10644
+ }
10645
+ evictOneIdleLru() {
10646
+ let victimKey;
10647
+ let victimAt = Number.POSITIVE_INFINITY;
10648
+ for (const [key, entry] of this.entries) {
10649
+ if (entry.refs > 0) continue;
10650
+ if (entry.lastUsed < victimAt) {
10651
+ victimAt = entry.lastUsed;
10652
+ victimKey = key;
10653
+ }
10654
+ }
10655
+ if (victimKey === void 0) return false;
10656
+ this.entries.get(victimKey)?.store.close();
10657
+ this.entries.delete(victimKey);
10658
+ return true;
10659
+ }
10660
+ };
10661
+ /** Clamp a configured TTL to its level's approved range. */
10662
+ function clampTtl(level, value) {
10663
+ const range = OVERVIEW_TTL_MINUTES[level];
10664
+ const fallback = range.fallback * 6e4;
10665
+ if (value === void 0 || !Number.isFinite(value)) return fallback;
10666
+ const min = range.min * 6e4;
10667
+ const max = range.max * 6e4;
10668
+ return Math.min(max, Math.max(min, value));
10669
+ }
10670
+ /** Cache slot: one aggregate per host and overview scope. */
10671
+ const overviewCache = /* @__PURE__ */ new WeakMap();
10672
+ /** Whether a graph row is one of the computed overviews. */
10673
+ function isOverviewGraph(graph) {
10674
+ if (graph.computed === true) return true;
10675
+ return isOverviewStorePath(graph.id) || isOverviewStorePath(graph.path);
10676
+ }
10677
+ /** Whether a path is `<anything>/.graphs/__overview__`. */
10678
+ function isOverviewStorePath(value) {
10679
+ const parts = value.split("/");
10680
+ return parts.length >= 3 && parts[parts.length - 2] === ".graphs" && parts[parts.length - 1] === "__overview__";
10681
+ }
10682
+ /** The scope base of a graph root (`<base>/知识图谱` → `<base>`). */
10683
+ function scopeBaseOfRoot(value) {
10684
+ const parts = value.split("/").filter((segment) => segment !== "");
10685
+ if (parts.length > 0 && parts[parts.length - 1] === "知识图谱") parts.pop();
10686
+ return parts.join("/");
10687
+ }
10688
+ /** Turn Host-resolved graph roots into overview scopes. */
10689
+ function overviewScopesFromRoots(roots) {
10690
+ const scopes = [];
10691
+ const seen = /* @__PURE__ */ new Set();
10692
+ for (const root of roots) {
10693
+ const viewBase = scopeBaseOfRoot(root.viewPath);
10694
+ const actualBase = scopeBaseOfRoot(root.actualPath);
10695
+ const key = root.key + ":" + actualBase;
10696
+ if (seen.has(key)) continue;
10697
+ seen.add(key);
10698
+ scopes.push({
10699
+ level: root.key,
10700
+ viewBase,
10701
+ actualBase,
10702
+ ...root.groupLabel === void 0 || root.groupLabel === "" ? {} : { groupLabel: root.groupLabel }
10703
+ });
10704
+ }
10705
+ return scopes;
10706
+ }
10707
+ /** Derive the store scope of one overview row. */
10708
+ function overviewStoreScopeOf(graph) {
10709
+ const suffix = "/.graphs/__overview__";
10710
+ const viewBase = graph.path.endsWith(suffix) ? graph.path.slice(0, -21) : scopeBaseOfRoot(graph.path);
10711
+ const actualPath = graph.actualPath ?? graph.path;
10712
+ const actualBase = actualPath.endsWith(suffix) ? actualPath.slice(0, -21) : scopeBaseOfRoot(actualPath);
10713
+ return overviewStoreScope({
10714
+ level: graph.scope,
10715
+ viewBase,
10716
+ actualBase,
10717
+ groupLabel: graph.group
10718
+ });
10719
+ }
10720
+ /** Complete one scope input into its store coordinates. */
10721
+ function overviewStoreScope(input) {
10722
+ return {
10723
+ level: input.level,
10724
+ viewBase: input.viewBase,
10725
+ actualBase: input.actualBase,
10726
+ groupLabel: input.groupLabel ?? "",
10727
+ viewPath: joinRel(input.viewBase, ".graphs/__overview__"),
10728
+ actualPath: joinRel(input.actualBase, ".graphs/__overview__")
10729
+ };
10730
+ }
10731
+ /** The synthetic graph row one scope's overview publishes. */
10732
+ function overviewGraphNode(scope, aggregate) {
10733
+ const counts = aggregate === void 0 ? {
10734
+ topics: 0,
10735
+ links: 0,
10736
+ documents: 0
10737
+ } : {
10738
+ topics: aggregate.nodes.length,
10739
+ links: aggregate.edges.length,
10740
+ documents: aggregate.nodes.length
10741
+ };
10742
+ return {
10743
+ id: scope.viewPath,
10744
+ name: OVERVIEW_GRAPH_NAME,
10745
+ scope: scope.level,
10746
+ path: scope.viewPath,
10747
+ group: scope.groupLabel,
10748
+ topics: aggregate?.topics ?? [],
10749
+ links: aggregate?.links ?? [],
10750
+ counts,
10751
+ actualPath: scope.actualPath,
10752
+ computed: true,
10753
+ readOnly: true
10754
+ };
10755
+ }
10756
+ /** The default scope: the caller's personal overview. */
10757
+ async function personalOverviewScope(host) {
10758
+ const caller = await host.resolveCaller();
10759
+ if (!isSafeSegment(caller.userId)) throw new KnowledgeToolError("forbidden", "unsafe caller id; cannot resolve the personal overview");
10760
+ return overviewStoreScope({
10761
+ level: "personal",
10762
+ viewBase: "personal",
10763
+ actualBase: "personal/" + caller.userId
10764
+ });
10765
+ }
10766
+ /** Read one hidden path, treating any refusal as "not there". */
10767
+ async function readHiddenText(host, relPath) {
10768
+ if (host.readActual === void 0) return void 0;
10769
+ try {
10770
+ if (host.statActual !== void 0 && await host.statActual(relPath) === void 0) return void 0;
10771
+ return await host.readActual(relPath);
10772
+ } catch {
10773
+ return;
10774
+ }
10775
+ }
10776
+ /** Whether a hidden path exists, through the Host's own stat seam. */
10777
+ async function hiddenExists(host, relPath) {
10778
+ if (host.statActual !== void 0) return await host.statActual(relPath) !== void 0;
10779
+ return await readHiddenText(host, relPath) !== void 0;
10780
+ }
10781
+ /** Parse and validate one link record; returns undefined for an unusable row. */
10782
+ function parseOverviewLink(value) {
10783
+ if (!isRecord$5(value)) return void 0;
10784
+ const id = typeof value.id === "string" ? value.id.trim() : "";
10785
+ const fromGraph = typeof value.fromGraph === "string" ? value.fromGraph.trim() : "";
10786
+ const from = typeof value.from === "string" ? value.from.trim() : "";
10787
+ const toGraph = typeof value.toGraph === "string" ? value.toGraph.trim() : "";
10788
+ const to = typeof value.to === "string" ? value.to.trim() : "";
10789
+ const type = typeof value.type === "string" ? value.type.trim() : "";
10790
+ if (!GRAPH_ITEM_ID.test(id) || fromGraph === "" || from === "" || toGraph === "" || to === "" || type === "") return;
10791
+ const authority = value.authority;
10792
+ const origin = value.origin;
10793
+ const reviewStatus = value.reviewStatus;
10794
+ if (!AUTHORITIES$1.includes(authority)) return void 0;
10795
+ if (!ORIGINS$1.includes(origin)) return void 0;
10796
+ if (!REVIEW_STATUSES$1.includes(reviewStatus)) return void 0;
10797
+ const tags = Array.isArray(value.tags) && value.tags.every((item) => typeof item === "string") ? value.tags.map((item) => item.trim()).filter((item) => item !== "") : [];
10798
+ const sourceRefs = Array.isArray(value.sourceRefs) && value.sourceRefs.every((item) => typeof item === "string") ? value.sourceRefs.map((item) => item.trim()).filter((item) => item !== "") : [];
10799
+ const title = typeof value.title === "string" && value.title.trim() !== "" ? value.title.trim() : void 0;
10800
+ const body = typeof value.body === "string" && value.body.trim() !== "" ? value.body : void 0;
10801
+ const createdAt = typeof value.createdAt === "string" ? value.createdAt : "";
10802
+ const updatedAt = typeof value.updatedAt === "string" ? value.updatedAt : "";
10803
+ return {
10804
+ id,
10805
+ fromGraph,
10806
+ from,
10807
+ toGraph,
10808
+ to,
10809
+ type,
10810
+ ...title === void 0 ? {} : { title },
10811
+ authority,
10812
+ internalizable: value.internalizable !== false,
10813
+ origin,
10814
+ reviewStatus,
10815
+ tags,
10816
+ sourceRefs,
10817
+ ...body === void 0 ? {} : { body },
10818
+ createdAt,
10819
+ updatedAt
10820
+ };
10821
+ }
10822
+ /** Read the cross-link store of one scope, or an empty one when it does not exist. */
10823
+ async function loadOverviewLinks(host, scope) {
10824
+ const primary = scope.actualPath + "/links.json";
10825
+ const candidates = [primary];
10826
+ if (scope.level === "personal" && scope.actualBase !== "personal") candidates.push("personal/.graphs/__overview__/links.json");
10827
+ let source;
10828
+ let actualPath = primary;
10829
+ for (const candidate of candidates) {
10830
+ source = await readHiddenText(host, candidate);
10831
+ if (source !== void 0) {
10832
+ actualPath = candidate;
10833
+ break;
10834
+ }
10835
+ }
10836
+ if (source === void 0) return {
10837
+ links: [],
10838
+ issues: [],
10839
+ actualPath
10840
+ };
10841
+ let parsed;
10842
+ try {
10843
+ parsed = JSON.parse(source);
10844
+ } catch (error) {
10845
+ return {
10846
+ links: [],
10847
+ issues: ["links.json is not valid JSON: " + messageOf$2(error)],
10848
+ actualPath
10849
+ };
10850
+ }
10851
+ if (!isRecord$5(parsed) || parsed.schemaVersion !== 1 || !Array.isArray(parsed.links)) return {
10852
+ links: [],
10853
+ issues: ["links.json must be {\"schemaVersion\":1,\"links\":[...]}"],
10854
+ actualPath
10855
+ };
10856
+ const links = [];
10857
+ const issues = [];
10858
+ const seen = /* @__PURE__ */ new Set();
10859
+ for (const [index, row] of parsed.links.entries()) {
10860
+ const link = parseOverviewLink(row);
10861
+ if (link === void 0) {
10862
+ issues.push("links[" + String(index) + "] is not a valid cross-graph link");
10863
+ continue;
10864
+ }
10865
+ if (seen.has(link.id)) {
10866
+ issues.push("duplicate cross-graph link id \"" + link.id + "\" was ignored");
10867
+ continue;
10868
+ }
10869
+ seen.add(link.id);
10870
+ links.push(link);
10871
+ }
10872
+ return {
10873
+ links,
10874
+ issues,
10875
+ actualPath
10876
+ };
10877
+ }
10878
+ /** Serialize the store, preserving nothing else: `links.json` is fully owned here. */
10879
+ function renderOverviewLinks(links) {
10880
+ return JSON.stringify({
10881
+ schemaVersion: 1,
10882
+ links: [...links]
10883
+ }, null, 2) + "\n";
10884
+ }
10885
+ /** Write `links.json` through the Host seam. */
10886
+ async function writeOverviewLinks(host, actualPath, content) {
10887
+ const directory = actualPath.split("/").slice(0, -1).join("/");
10888
+ if (!await host.canWrite(directory)) throw new KnowledgeToolError("forbidden", "write access is required for this overview scope", directory);
10889
+ await host.createEntry(directory, { directory: true }).catch(() => void 0);
10890
+ if (await hiddenExists(host, actualPath)) {
10891
+ await host.overwriteFile(actualPath, content);
10892
+ return;
10893
+ }
10894
+ try {
10895
+ await host.createEntry(actualPath, {
10896
+ directory: false,
10897
+ content
10898
+ });
10899
+ } catch (error) {
10900
+ if (error.code === "exists") {
10901
+ await host.overwriteFile(actualPath, content);
10902
+ return;
10903
+ }
10904
+ throw error;
10905
+ }
10906
+ }
10907
+ /** Find one readable graph by id, path or unique name. */
10908
+ function findGraphReference(graphs, value) {
10909
+ const needle = value.trim();
10910
+ const found = graphs.filter((graph) => graph.id === needle || graph.path === needle || graph.name === needle);
10911
+ return found.length === 1 ? found[0] : void 0;
10912
+ }
10913
+ /** The readable graphs belonging to one overview level, self excluded. */
10914
+ function graphsOfLevel(graphs, level) {
10915
+ return graphs.filter((graph) => !isOverviewGraph(graph) && graph.scope === level);
10916
+ }
10917
+ /** Stable key for the aggregate cache: scope, catalogue content and link snapshot. */
10918
+ function overviewSignature(scope, graphs, links) {
10919
+ const catalogue = graphs.map((graph) => [
10920
+ graph.id,
10921
+ graph.name,
10922
+ graph.scope,
10923
+ String(graph.counts.topics),
10924
+ String(graph.counts.links),
10925
+ graph.topics.map((topic) => [
10926
+ topic.id,
10927
+ topic.title,
10928
+ topic.domain ?? "",
10929
+ topic.authority ?? "",
10930
+ topic.reviewStatus ?? "",
10931
+ topic.origin ?? "",
10932
+ topic.tags.join(""),
10933
+ topic.documents[0]?.path ?? topic.path
10934
+ ].join("")).join("")
10935
+ ].join("")).join("");
10936
+ return scope.level + "\x07" + scope.actualBase + "" + catalogue + "" + JSON.stringify(links);
10937
+ }
10938
+ /** Acquire one store through the manager, or a transient one when none is wired. */
10939
+ async function acquireOverviewStore(host, scope) {
10940
+ if (host.overviewStores !== void 0) return {
10941
+ store: await host.overviewStores.acquire(scope),
10942
+ transient: false
10943
+ };
10944
+ const store = new JsonOverviewStore(host, scope);
10945
+ await store.open();
10946
+ return {
10947
+ store,
10948
+ transient: true
10949
+ };
10950
+ }
10951
+ /** Release one store and close it when it was transient. */
10952
+ function releaseOverviewStore(host, acquired) {
10953
+ if (!acquired.transient) {
10954
+ host.overviewStores?.release(acquired.store);
10955
+ return;
10956
+ }
10957
+ acquired.store.close();
10958
+ }
10959
+ /**
10960
+ * Build the overview from already readable graphs and the cross-link store.
10961
+ *
10962
+ * Pure and permission-agnostic: every graph in `graphs` has already passed
10963
+ * `canReadPath` and belongs to `scope.level`; a cross link is included only when
10964
+ * BOTH endpoint graphs are present in that list. A hidden graph is therefore
10965
+ * neither named nor counted.
10966
+ */
10967
+ function buildOverviewAggregate(scope, graphs, crossLinks = [], storeIssues = []) {
10968
+ const readable = graphsOfLevel(graphs, scope.level);
10969
+ const issues = [...storeIssues];
10970
+ const summaries = [];
10971
+ const nodeIndex = /* @__PURE__ */ new Map();
10972
+ const nodes = [];
10973
+ const topics = [];
10974
+ const edges = [];
10975
+ const links = [];
10976
+ for (const graph of readable) {
10977
+ const format = graph.format ?? "legacy";
10978
+ summaries.push({
10979
+ id: graph.id,
10980
+ name: graph.name,
10981
+ scope: scope.level,
10982
+ group: graph.group,
10983
+ path: graph.path,
10984
+ format,
10985
+ counts: { ...graph.counts }
10986
+ });
10987
+ for (const topic of graph.topics) {
10988
+ const namespaced = graph.id + ":" + topic.id;
10989
+ if (nodeIndex.has(namespaced)) continue;
10990
+ const type = format === "graph-json" ? topic.domain ?? "topic" : "topic";
10991
+ const docPath = topic.documents[0]?.path ?? topic.path;
10992
+ nodeIndex.set(namespaced, topic);
10993
+ nodes.push({
10994
+ id: namespaced,
10995
+ graphId: graph.id,
10996
+ graphName: graph.name,
10997
+ scope: scope.level,
10998
+ nodeId: topic.id,
10999
+ type,
11000
+ title: topic.title,
11001
+ ...topic.authority === void 0 ? {} : { authority: topic.authority },
11002
+ ...topic.reviewStatus === void 0 ? {} : { reviewStatus: topic.reviewStatus },
11003
+ tags: [...topic.tags],
11004
+ docPath
11005
+ });
11006
+ topics.push({
11007
+ ...topic,
11008
+ id: namespaced,
11009
+ domain: type,
11010
+ tags: [graph.name, ...topic.tags],
11011
+ path: docPath,
11012
+ sourceGraphId: graph.id,
11013
+ sourceNodeId: topic.id,
11014
+ scope: scope.level
11015
+ });
11016
+ }
11017
+ }
11018
+ for (const graph of readable) for (const link of graph.links) {
11019
+ const from = graph.id + ":" + link.a;
11020
+ const to = graph.id + ":" + link.b;
11021
+ if (!nodeIndex.has(from) || !nodeIndex.has(to)) continue;
11022
+ const stem = link.file === void 0 ? link.a + "--" + link.b : link.file.replace(/\.md$/iu, "");
11023
+ edges.push({
11024
+ id: graph.id + ":" + stem,
11025
+ graphId: graph.id,
11026
+ edgeId: stem,
11027
+ from,
11028
+ to,
11029
+ type: link.label ?? "related",
11030
+ ...link.label === void 0 ? {} : { title: link.label },
11031
+ tags: [],
11032
+ sourceRefs: [],
11033
+ crossGraph: false
11034
+ });
11035
+ links.push({
11036
+ a: from,
11037
+ b: to,
11038
+ ...link.label === void 0 ? {} : { label: link.label },
11039
+ body: link.body,
11040
+ ...link.file === void 0 ? {} : { file: link.file }
11041
+ });
11042
+ }
11043
+ let crossEdges = 0;
11044
+ for (const record of crossLinks) {
11045
+ const fromGraph = findGraphReference(readable, record.fromGraph);
11046
+ const toGraph = findGraphReference(readable, record.toGraph);
11047
+ const from = fromGraph === void 0 ? void 0 : fromGraph.id + ":" + record.from;
11048
+ const to = toGraph === void 0 ? void 0 : toGraph.id + ":" + record.to;
11049
+ if (from === void 0 || to === void 0 || !nodeIndex.has(from) || !nodeIndex.has(to)) {
11050
+ issues.push("cross-graph link \"" + record.id + "\" was skipped: an endpoint is not readable");
11051
+ continue;
11052
+ }
11053
+ crossEdges += 1;
11054
+ const label = record.title ?? record.type;
11055
+ edges.push({
11056
+ id: record.id,
11057
+ graphId: scope.viewPath,
11058
+ edgeId: record.id,
11059
+ from,
11060
+ to,
11061
+ type: record.type,
11062
+ ...record.title === void 0 ? {} : { title: record.title },
11063
+ authority: record.authority,
11064
+ origin: record.origin,
11065
+ reviewStatus: record.reviewStatus,
11066
+ tags: [...record.tags],
11067
+ sourceRefs: [...record.sourceRefs],
11068
+ crossGraph: true
11069
+ });
11070
+ links.push({
11071
+ a: from,
11072
+ b: to,
11073
+ label,
11074
+ body: record.body ?? "",
11075
+ crossGraph: true
11076
+ });
11077
+ }
11078
+ const counts = {
11079
+ topics: nodes.length,
11080
+ links: edges.length,
11081
+ documents: nodes.length
11082
+ };
11083
+ return {
11084
+ graph: {
11085
+ id: scope.viewPath,
11086
+ name: OVERVIEW_GRAPH_NAME,
11087
+ scope: scope.level,
11088
+ group: scope.groupLabel,
11089
+ path: scope.viewPath,
11090
+ format: "overview",
11091
+ computed: true,
11092
+ readOnly: true,
11093
+ counts
11094
+ },
11095
+ graphs: summaries,
11096
+ nodes,
11097
+ edges,
11098
+ topics,
11099
+ links,
11100
+ totals: {
11101
+ graphs: summaries.length,
11102
+ nodes: nodes.length,
11103
+ edges: edges.length,
11104
+ crossEdges
11105
+ },
11106
+ issues
11107
+ };
11108
+ }
11109
+ /**
11110
+ * Load (or reuse) one scope's overview aggregate.
11111
+ *
11112
+ * The cache key covers the scope, every readable graph's identity/counts/attributes
11113
+ * and the cross-link snapshot, so a refresh or write changes the answer without a
11114
+ * TTL; {@link invalidateOverviewCache} still drops it eagerly on the write seams.
11115
+ * The store manager supplies the per-scope snapshot, so the same function serves
11116
+ * the global, department and personal overviews without mixing users' stores.
11117
+ */
11118
+ async function loadOverviewAggregate(host, graphs, scopeInput) {
11119
+ const scope = scopeInput === void 0 ? await personalOverviewScope(host) : "viewPath" in scopeInput ? scopeInput : overviewStoreScope(scopeInput);
11120
+ const acquired = await acquireOverviewStore(host, scope);
11121
+ try {
11122
+ const links = await acquired.store.query();
11123
+ const levelGraphs = graphsOfLevel(graphs, scope.level);
11124
+ const key = overviewSignature(scope, levelGraphs, links);
11125
+ let cache = overviewCache.get(host);
11126
+ if (cache === void 0) {
11127
+ cache = /* @__PURE__ */ new Map();
11128
+ overviewCache.set(host, cache);
11129
+ }
11130
+ const cached = cache.get(scope.viewPath);
11131
+ if (cached !== void 0 && cached.key === key) return cached.value;
11132
+ const value = buildOverviewAggregate(scope, levelGraphs, links, acquired.store.issues());
11133
+ cache.set(scope.viewPath, {
11134
+ key,
11135
+ value
11136
+ });
11137
+ if (acquired.store instanceof JsonOverviewStore) await acquired.store.materialize(value).catch(() => void 0);
11138
+ return value;
11139
+ } finally {
11140
+ releaseOverviewStore(host, acquired);
11141
+ }
11142
+ }
11143
+ /** The `host.listGraphs()` answer plus one synthesized row per resolved scope. */
11144
+ async function appendOverviewGraphs(host, graphs, scopes) {
11145
+ const real = graphs.filter((graph) => !isOverviewGraph(graph));
11146
+ const entries = [];
11147
+ const seen = /* @__PURE__ */ new Set();
11148
+ for (const input of scopes) {
11149
+ const scope = overviewStoreScope(input);
11150
+ if (seen.has(scope.viewPath)) continue;
11151
+ seen.add(scope.viewPath);
11152
+ const aggregate = await loadOverviewAggregate(host, real, scope);
11153
+ entries.push(overviewGraphNode(scope, aggregate));
11154
+ }
11155
+ return [...real, ...entries];
11156
+ }
11157
+ /** `kg_get` for one overview: graphs, namespaced nodes and remapped edges. */
11158
+ async function getOverview(host, graphs, overview) {
11159
+ const aggregate = await loadOverviewAggregate(host, graphs, overviewStoreScopeOf(overview));
11160
+ return {
11161
+ ok: true,
11162
+ overview: true,
11163
+ computed: true,
11164
+ readOnly: true,
11165
+ graph: aggregate.graph,
11166
+ totals: aggregate.totals,
11167
+ graphs: aggregate.graphs,
11168
+ nodes: aggregate.nodes,
11169
+ edges: aggregate.edges,
11170
+ ...aggregate.issues.length === 0 ? {} : { issues: aggregate.issues }
11171
+ };
11172
+ }
11173
+ /** `kg_add kind=edge` on an overview: one cross-graph link in that scope. */
11174
+ async function addOverviewEdge(host, graphs, overview, args) {
11175
+ const scope = overviewStoreScopeOf(overview);
11176
+ const id = (args.id ?? "").trim();
11177
+ if (!GRAPH_ITEM_ID.test(id)) throw new KnowledgeToolError("invalid", "id must be 1-64 lowercase letters, digits or hyphens", id === "" ? void 0 : id);
11178
+ const fromGraphValue = (args.fromGraph ?? "").trim();
11179
+ const toGraphValue = (args.toGraph ?? "").trim();
11180
+ if (fromGraphValue === "" || toGraphValue === "") throw new KnowledgeToolError("invalid", "a cross-graph edge needs fromGraph and toGraph (each names a readable graph in this 总图 scope); from/to remain node ids", id);
11181
+ if (isOverviewGraph({
11182
+ id: fromGraphValue,
11183
+ path: fromGraphValue
11184
+ }) || isOverviewGraph({
11185
+ id: toGraphValue,
11186
+ path: toGraphValue
11187
+ })) throw new KnowledgeToolError("invalid", "an overview cannot link to itself; name two source graphs", id);
11188
+ const levelGraphs = graphsOfLevel(graphs, scope.level);
11189
+ const fromGraph = findGraphReference(levelGraphs, fromGraphValue);
11190
+ if (fromGraph === void 0) throw new KnowledgeToolError("not-found", "fromGraph must name exactly one readable graph in the " + scope.level + " scope", fromGraphValue);
11191
+ const toGraph = findGraphReference(levelGraphs, toGraphValue);
11192
+ if (toGraph === void 0) throw new KnowledgeToolError("not-found", "toGraph must name exactly one readable graph in the " + scope.level + " scope", toGraphValue);
11193
+ const from = (args.from ?? "").trim();
11194
+ const to = (args.to ?? "").trim();
11195
+ if (from === "" || to === "") throw new KnowledgeToolError("invalid", "from and to are required node ids", id);
11196
+ if (fromGraph.id === toGraph.id && from === to) throw new KnowledgeToolError("invalid", "from and to must be different nodes", id);
11197
+ if (!fromGraph.topics.some((topic) => topic.id === from)) throw new KnowledgeToolError("not-found", "from node is not in " + fromGraph.name + ": " + from, from);
11198
+ if (!toGraph.topics.some((topic) => topic.id === to)) throw new KnowledgeToolError("not-found", "to node is not in " + toGraph.name + ": " + to, to);
11199
+ const type = (args.type ?? "").trim();
11200
+ if (type === "") throw new KnowledgeToolError("invalid", "type (the relation label) is required for an edge", id);
11201
+ const caller = await host.resolveCaller();
11202
+ const acquired = await acquireOverviewStore(host, scope);
11203
+ try {
11204
+ const store = acquired.store;
11205
+ const existing = await store.query();
11206
+ assertOverviewLinksWritable(store, overview);
11207
+ if (existing.some((link) => link.id === id)) throw new KnowledgeToolError("exists", "a cross-graph link with this id already exists", id);
11208
+ const now = (/* @__PURE__ */ new Date()).toISOString();
11209
+ const record = {
11210
+ id,
11211
+ fromGraph: fromGraph.id,
11212
+ from,
11213
+ toGraph: toGraph.id,
11214
+ to,
11215
+ type,
11216
+ ...args.title === void 0 || args.title.trim() === "" ? {} : { title: args.title.trim() },
11217
+ authority: enumArg(args.authority, AUTHORITIES$1, "authority") ?? "advisory",
11218
+ internalizable: booleanArg(args.internalizable, "internalizable") ?? true,
11219
+ origin: enumArg(args.origin, ORIGINS$1, "origin") ?? "human",
11220
+ reviewStatus: enumArg(args.reviewStatus, REVIEW_STATUSES$1, "reviewStatus") ?? "draft",
11221
+ tags: stringListArg(args.tags, "tags") ?? [],
11222
+ sourceRefs: stringListArg(args.sourceRefs, "sourceRefs") ?? [],
11223
+ ...args.body === void 0 || args.body.trim() === "" ? {} : { body: args.body },
11224
+ createdAt: now,
11225
+ updatedAt: now
11226
+ };
11227
+ const next = [...existing, record];
11228
+ const linksPath = overview.path + "/links.json";
11229
+ if (args.confirm !== true) return {
11230
+ ok: true,
11231
+ draft: true,
11232
+ action: "add",
11233
+ kind: "edge",
11234
+ format: "overview",
11235
+ graph: overview.path,
11236
+ scope: scope.level,
11237
+ id,
11238
+ fromGraph: fromGraph.id,
11239
+ toGraph: toGraph.id,
11240
+ from,
11241
+ to,
11242
+ type,
11243
+ path: linksPath,
11244
+ content: renderOverviewLinks(next),
11245
+ next: "show this draft to the user; call again with confirm:true to write the cross-graph edge"
11246
+ };
11247
+ await store.replace(next);
11248
+ invalidateOverviewCache(host);
11249
+ await host.refreshView().catch(() => void 0);
11250
+ const audit = await recordAudit(host, caller, {
11251
+ action: "create",
11252
+ relPath: linksPath,
11253
+ tool: "kg_add",
11254
+ graphId: overview.path,
11255
+ topicId: id,
11256
+ intent: "new cross-graph edge",
11257
+ diffSummary: "linked " + fromGraph.id + ":" + from + " -> " + toGraph.id + ":" + to,
11258
+ outcome: "applied"
11259
+ });
11260
+ return {
11261
+ ok: true,
11262
+ action: "add",
11263
+ kind: "edge",
11264
+ format: "overview",
11265
+ graph: overview.path,
11266
+ scope: scope.level,
11267
+ id,
11268
+ fromGraph: fromGraph.id,
11269
+ toGraph: toGraph.id,
11270
+ from,
11271
+ to,
11272
+ type,
11273
+ path: linksPath,
11274
+ audit
11275
+ };
11276
+ } finally {
11277
+ releaseOverviewStore(host, acquired);
11278
+ }
11279
+ }
11280
+ /** `kg_del` on an overview: move one cross-graph link to `_trash/links/`. */
11281
+ async function deleteOverviewEdge(host, overview, args) {
11282
+ if (args.kind !== void 0 && args.kind !== "" && args.kind !== "edge") throw new KnowledgeToolError("invalid", "an overview only contains cross-graph edges; pass kind:\"edge\"", args.id);
11283
+ const scope = overviewStoreScopeOf(overview);
11284
+ const id = args.id.trim();
11285
+ const caller = await host.resolveCaller();
11286
+ const acquired = await acquireOverviewStore(host, scope);
11287
+ try {
11288
+ const store = acquired.store;
11289
+ const existing = await store.query();
11290
+ assertOverviewLinksWritable(store, overview);
11291
+ const record = existing.find((link) => link.id === id);
11292
+ if (record === void 0) throw new KnowledgeToolError("not-found", "no cross-graph link has this id", id);
11293
+ const trashName = stamp() + "-" + id + ".json";
11294
+ const trashPath = scope.actualPath + "/_trash/links/" + trashName;
11295
+ const linksPath = overview.path + "/links.json";
11296
+ const summary = {
11297
+ action: "del",
11298
+ kind: "edge",
11299
+ format: "overview",
11300
+ graph: overview.path,
11301
+ scope: scope.level,
11302
+ id,
11303
+ fromGraph: record.fromGraph,
11304
+ toGraph: record.toGraph,
11305
+ from: record.from,
11306
+ to: record.to,
11307
+ path: linksPath,
11308
+ toPath: overview.path + "/_trash/links/" + trashName
11309
+ };
11310
+ if (args.confirm !== true) return {
11311
+ ok: true,
11312
+ draft: true,
11313
+ ...summary,
11314
+ next: "show these paths to the user; call again with confirm:true to move the cross-graph link to _trash"
11315
+ };
11316
+ if (!await host.canWrite(scope.actualPath)) throw new KnowledgeToolError("forbidden", "write access is required for this overview scope", overview.path);
11317
+ await host.createEntry(scope.actualPath + "/_trash/links", { directory: true }).catch(() => void 0);
11318
+ await host.createEntry(trashPath, {
11319
+ directory: false,
11320
+ content: JSON.stringify(record, null, 2) + "\n"
11321
+ });
11322
+ await store.replace(existing.filter((link) => link.id !== id));
11323
+ invalidateOverviewCache(host);
11324
+ await host.refreshView().catch(() => void 0);
11325
+ const audit = await recordAudit(host, caller, {
11326
+ action: "delete",
11327
+ relPath: linksPath,
11328
+ toRelPath: overview.path + "/_trash/links/" + trashName,
11329
+ tool: "kg_del",
11330
+ graphId: overview.path,
11331
+ topicId: id,
11332
+ intent: "move-to-trash",
11333
+ diffSummary: "removed cross-graph edge " + id,
11334
+ outcome: "applied"
11335
+ });
11336
+ return {
11337
+ ok: true,
11338
+ ...summary,
11339
+ movedToTrash: true,
11340
+ audit
11341
+ };
11342
+ } finally {
11343
+ releaseOverviewStore(host, acquired);
11344
+ }
11345
+ }
11346
+ /** Refuse a write over a `links.json` this store could not parse. */
11347
+ function assertOverviewLinksWritable(store, overview) {
11348
+ if (store.issues().some((issue) => issue.startsWith("links.json is not valid JSON") || issue.startsWith("links.json must be"))) throw new KnowledgeToolError("invalid", "links.json is unreadable; repair or remove it before writing cross-graph edges", overview.path);
11349
+ }
11350
+ /** `kg_set`/`kg_add kind=node` on an overview: an actionable refusal. */
11351
+ function overviewReadOnly(field) {
11352
+ return new KnowledgeToolError("invalid", "the 总图 overview is computed and read-only: " + (field === "node" ? "add the node to its source graph with kg_add {\"kind\":\"node\",\"graph\":\"<source-graph>\",...}; it then appears in that scope's 总图 automatically" : "edit the source graph or node with kg_set graph=<source-graph> id=<node-or-edge-id>"));
11353
+ }
11354
+ /** Drop every cached aggregate for one host; called on the write seams and refresh. */
11355
+ function invalidateOverviewCache(host) {
11356
+ overviewCache.delete(host);
11357
+ }
10298
11358
  /** The scope base that owns one graph path, legacy or graph-json. */
10299
11359
  function scopeBaseOfPath(value) {
10300
11360
  if (value === void 0 || value === "") return void 0;
@@ -10334,7 +11394,7 @@ function resolveGraphCreateTarget(graphs, value, caller) {
10334
11394
  visibility: "global"
10335
11395
  };
10336
11396
  if (scope === "department") {
10337
- const existing = graphs.find((graph) => graph.scope === "department" && scopeBaseOfPath(graph.actualPath) !== void 0 && scopeBaseOfPath(graph.path) !== void 0);
11397
+ const existing = graphs.find((graph) => graph.scope === "department" && !isOverviewGraph(graph) && scopeBaseOfPath(graph.actualPath) !== void 0 && scopeBaseOfPath(graph.path) !== void 0);
10338
11398
  const viewBase = existing === void 0 ? void 0 : scopeBaseOfPath(existing.path);
10339
11399
  const actualBase = existing === void 0 ? void 0 : scopeBaseOfPath(existing.actualPath);
10340
11400
  if (viewBase === void 0 || actualBase === void 0) throw new KnowledgeToolError("invalid", "this caller has no readable department graph to copy the department path from; pass scope:\"department/<chain>\" (the department path in the graph tree) to create one");
@@ -10393,9 +11453,11 @@ async function createGraphJson(host, args) {
10393
11453
  const graphArgIsScope = graphArg !== "" && isGraphCreateScope(graphArg);
10394
11454
  const id = (args.id ?? (GRAPH_ITEM_ID.test(graphArg) && !graphArgIsScope ? graphArg : "")).trim();
10395
11455
  if (!GRAPH_ITEM_ID.test(id)) throw new KnowledgeToolError("invalid", "graph id must be 1-64 lowercase letters, digits or hyphens", id === "" ? void 0 : id);
11456
+ if (id === "__overview__") throw new KnowledgeToolError("invalid", "graph id \"__overview__\" is reserved for the computed 总图", id);
10396
11457
  const scopeValue = args.scope ?? (graphArgIsScope ? graphArg : void 0);
10397
11458
  const name = (args.name ?? args.title ?? "").trim();
10398
11459
  if (name === "") throw new KnowledgeToolError("invalid", "name is required to create a graph");
11460
+ if (name === "总图") throw new KnowledgeToolError("exists", "\"总图\" is the reserved name of the computed overview graph");
10399
11461
  if (name.length > 120) throw new KnowledgeToolError("invalid", "name must be at most 120 characters");
10400
11462
  const description = (args.description ?? "").trim();
10401
11463
  if (description.length > 2e3) throw new KnowledgeToolError("invalid", "description must be at most 2000 characters");
@@ -11140,16 +12202,16 @@ async function deleteFromGraphJson(host, graph, store, args) {
11140
12202
  const createKnowledgeGraphTools = (host) => [
11141
12203
  defineTool({
11142
12204
  name: "kg_add",
11143
- description: "Add one graph item and WRITE the knowledge tree. Call without confirm:true first to receive the exact draft; show that draft to the user; call again with confirm:true only after they approve. kind=graph creates a new graph-json graph: it writes .graphs/<id>/graph.json under the caller's writable scope (scope=personal by default, or department/global when the caller may write there). Use it when kg_add/kg_get say no readable graph matches; the draft is the exact manifest, and confirm:true creates the graph so later kg_add calls resolve it. Legacy folder graphs: kind=topic creates a visible folder + index.md card; kind=link creates a hidden .kg/links document. Graph-json graphs (format=graph-json, stored under .graphs/<id>/graph.json): kind=node creates the node document at \"path\" with an id/type/title/authority/internalizable/origin/reviewStatus/tags/sourceRefs front matter block and appends {id,path} to graph.json; kind=edge appends {id,from,to,type} and, when a body or edge attributes are given, writes .graphs/<id>/links/<id>.md. Duplicate ids and unknown edge endpoints are refused. \"graph\" is the graph path or name; \"kind\" is topic/link for a legacy graph, node/edge for a graph-json graph, or graph to create one.",
12205
+ description: "Add one graph item and WRITE the knowledge tree. Call without confirm:true first to receive the exact draft; show that draft to the user; call again with confirm:true only after they approve. kind=graph creates a new graph-json graph: it writes .graphs/<id>/graph.json under the caller's writable scope (scope=personal by default, or department/global when the caller may write there). Use it when kg_add/kg_get say no readable graph matches; the draft is the exact manifest, and confirm:true creates the graph so later kg_add calls resolve it. Legacy folder graphs: kind=topic creates a visible folder + index.md card; kind=link creates a hidden .kg/links document. Graph-json graphs (format=graph-json, stored under .graphs/<id>/graph.json): kind=node creates the node document at \"path\" with an id/type/title/authority/internalizable/origin/reviewStatus/tags/sourceRefs front matter block and appends {id,path} to graph.json; kind=edge appends {id,from,to,type} and, when a body or edge attributes are given, writes .graphs/<id>/links/<id>.md. Duplicate ids and unknown edge endpoints are refused. \"graph\" is the graph path or name; \"kind\" is topic/link for a legacy graph, node/edge for a graph-json graph, or graph to create one. The computed overview graph 总图 is read-only: kind=edge on graph=\"总图\" (or \"__overview__\") writes a cross-graph link to personal/.graphs/__overview__/links.json using fromGraph/toGraph (graph ids) plus from/to (node ids); kind=node there is refused.",
11144
12206
  parameters: {
11145
12207
  graph: {
11146
12208
  type: "string",
11147
- description: "Graph path or name, e.g. personal/知识图谱/工作轨迹 or personal/.graphs/procurement. Not required for kind=graph."
12209
+ description: "Graph path or name, e.g. personal/知识图谱/工作轨迹 or personal/.graphs/procurement; 总图 for a cross-graph edge. Not required for kind=graph."
11148
12210
  },
11149
12211
  kind: {
11150
12212
  type: "string",
11151
12213
  required: true,
11152
- description: "topic | link (legacy graph), node | edge (graph-json graph), or graph (create a graph-json graph)."
12214
+ description: "topic | link (legacy graph), node | edge (graph-json graph, or edge on 总图), or graph (create a graph-json graph)."
11153
12215
  },
11154
12216
  id: {
11155
12217
  type: "string",
@@ -11177,41 +12239,49 @@ const createKnowledgeGraphTools = (host) => [
11177
12239
  },
11178
12240
  type: {
11179
12241
  type: "string",
11180
- description: "Node type (policy|fact|procedure|case|skill|decision|topic; default fact) or edge relation type (graph-json only)."
12242
+ description: "Node type (policy|fact|procedure|case|skill|decision|topic; default fact) or edge relation type (graph-json and overview cross-graph edges)."
11181
12243
  },
11182
12244
  authority: {
11183
12245
  type: "string",
11184
- description: "canonical | advisory | redline; default advisory (graph-json only)."
12246
+ description: "canonical | advisory | redline; default advisory (graph-json and overview edges)."
11185
12247
  },
11186
12248
  internalizable: {
11187
12249
  type: "boolean",
11188
- description: "Whether personal internalization is allowed; default true (graph-json only)."
12250
+ description: "Whether personal internalization is allowed; default true (graph-json and overview edges)."
11189
12251
  },
11190
12252
  origin: {
11191
12253
  type: "string",
11192
- description: "human | ai | mixed; default human (graph-json only)."
12254
+ description: "human | ai | mixed; default human (graph-json and overview edges)."
11193
12255
  },
11194
12256
  reviewStatus: {
11195
12257
  type: "string",
11196
- description: "draft | reviewed | approved; default draft (graph-json only)."
12258
+ description: "draft | reviewed | approved; default draft (graph-json and overview edges)."
11197
12259
  },
11198
12260
  tags: {
11199
12261
  type: "array",
11200
12262
  items: { type: "string" },
11201
- description: "Node, edge or graph tags (graph-json only)."
12263
+ description: "Node, edge or graph tags (graph-json and overview edges)."
11202
12264
  },
11203
12265
  sourceRefs: {
11204
12266
  type: "array",
11205
12267
  items: { type: "string" },
11206
- description: "Node or edge source references (graph-json only)."
12268
+ description: "Node or edge source references (graph-json and overview edges)."
11207
12269
  },
11208
12270
  from: {
11209
12271
  type: "string",
11210
- description: "Source node id of the edge (kind=edge on a graph-json graph)."
12272
+ description: "Source node id of the edge (kind=edge)."
11211
12273
  },
11212
12274
  to: {
11213
12275
  type: "string",
11214
- description: "Target node id of the edge (kind=edge on a graph-json graph)."
12276
+ description: "Target node id of the edge (kind=edge)."
12277
+ },
12278
+ fromGraph: {
12279
+ type: "string",
12280
+ description: "Source graph id for a 总图 cross-graph edge (kind=edge, graph=总图)."
12281
+ },
12282
+ toGraph: {
12283
+ type: "string",
12284
+ description: "Target graph id for a 总图 cross-graph edge (kind=edge, graph=总图)."
11215
12285
  },
11216
12286
  domain: {
11217
12287
  type: "string",
@@ -11255,7 +12325,13 @@ const createKnowledgeGraphTools = (host) => [
11255
12325
  if ((args.kind ?? "").trim() === "graph") return createGraphJson(host, args);
11256
12326
  const graphValue = (args.graph ?? "").trim();
11257
12327
  if (graphValue === "") throw new KnowledgeToolError("invalid", "graph is required unless kind is \"graph\"; create one first with " + graphCreateHint());
11258
- const graph = requireGraph(await host.listGraphs(), graphValue);
12328
+ const graphs = await host.listGraphs();
12329
+ const graph = requireGraph(graphs, graphValue);
12330
+ if (isOverviewGraph(graph)) {
12331
+ if (args.kind === "edge") return addOverviewEdge(host, graphs, graph, args);
12332
+ if (args.kind === "node") throw overviewReadOnly("node");
12333
+ throw new KnowledgeToolError("invalid", "the overview graph 总图 is computed and read-only; only kind:\"edge\" (a cross-graph link) can be added there");
12334
+ }
11259
12335
  const store = graphJsonStore(graph);
11260
12336
  if (store !== void 0) return addToGraphJson(host, graph, store, args);
11261
12337
  const actualGraph = actualGraphPath(graph);
@@ -11366,11 +12442,11 @@ const createKnowledgeGraphTools = (host) => [
11366
12442
  }),
11367
12443
  defineTool({
11368
12444
  name: "kg_get",
11369
- description: "Read the knowledge graph. Without graph/id it returns the overview of every readable graph; when none exists the answer names the kg_add kind=graph call that creates one. With graph and no id it lists that graph's topics, nodes and relations. With graph+id it returns one item: a legacy topic card, or a graph-json node/edge with its id/title/type/authority/origin/reviewStatus/tags/sourceRefs, path and missing flag. Graph-json graphs are read from .graphs/<id>/graph.json plus the referenced node documents' front matter. Read-only; never writes.",
12445
+ description: "Read the knowledge graph. Without graph/id it returns the overview of every readable graph; when none exists the answer names the kg_add kind=graph call that creates one. With graph and no id it lists that graph's topics, nodes and relations. With graph+id it returns one item: a legacy topic card, or a graph-json node/edge with its id/title/type/authority/origin/reviewStatus/tags/sourceRefs, path and missing flag. Graph-json graphs are read from .graphs/<id>/graph.json plus the referenced node documents' front matter. graph=\"总图\" (or \"__overview__\") returns the computed aggregate: readable graph summaries, nodes namespaced \"<graphId>:<nodeId>\" and edges with remapped endpoints, including cross-graph links. Read-only; never writes.",
11370
12446
  parameters: {
11371
12447
  graph: {
11372
12448
  type: "string",
11373
- description: "Graph path or name. Omit for the overview."
12449
+ description: "Graph path or name; 总图 defaults to personal, or pass global/__overview__ / department/__overview__ / personal/__overview__. Omit for the catalogue."
11374
12450
  },
11375
12451
  id: {
11376
12452
  type: "string",
@@ -11380,27 +12456,52 @@ const createKnowledgeGraphTools = (host) => [
11380
12456
  output: jsonOutput$1,
11381
12457
  execute: async (args) => run$3(async () => {
11382
12458
  const graphs = await host.listGraphs();
11383
- if (args.graph === void 0 || args.graph.trim() === "") return {
11384
- ok: true,
11385
- overview: true,
11386
- totals: {
11387
- graphs: graphs.length,
11388
- topics: graphs.reduce((sum, graph) => sum + graph.topics.length, 0),
11389
- relations: graphs.reduce((sum, graph) => sum + graph.links.length, 0)
11390
- },
11391
- graphs: graphs.map((graph) => ({
11392
- id: graph.id,
11393
- name: graph.name,
11394
- scope: graph.scope,
11395
- group: graph.group,
11396
- path: graph.path,
11397
- format: graph.format ?? "legacy",
11398
- counts: graph.counts,
11399
- topics: graph.topics.map((topic) => topicSummary(graph, topic))
11400
- })),
11401
- ...graphs.length === 0 ? { next: "no graph exists yet; create one with " + graphCreateHint() + " (draft, then confirm:true)" } : {}
11402
- };
12459
+ if (args.graph === void 0 || args.graph.trim() === "") {
12460
+ const readable = graphs.filter((graph) => !isOverviewGraph(graph));
12461
+ const overviews = graphs.filter(isOverviewGraph);
12462
+ const personalOverview = overviews.find((graph) => graph.scope === "personal");
12463
+ return {
12464
+ ok: true,
12465
+ overview: true,
12466
+ totals: {
12467
+ graphs: readable.length,
12468
+ topics: readable.reduce((sum, graph) => sum + graph.topics.length, 0),
12469
+ relations: readable.reduce((sum, graph) => sum + graph.links.length, 0)
12470
+ },
12471
+ graphs: readable.map((graph) => ({
12472
+ id: graph.id,
12473
+ name: graph.name,
12474
+ scope: graph.scope,
12475
+ group: graph.group,
12476
+ path: graph.path,
12477
+ format: graph.format ?? "legacy",
12478
+ counts: graph.counts,
12479
+ topics: graph.topics.map((topic) => topicSummary(graph, topic))
12480
+ })),
12481
+ ...overviews.length === 0 ? {} : {
12482
+ overviewGraphs: overviews.map((overview) => ({
12483
+ id: overview.id,
12484
+ name: overview.name,
12485
+ scope: overview.scope,
12486
+ computed: true,
12487
+ readOnly: true,
12488
+ counts: overview.counts
12489
+ })),
12490
+ ...personalOverview === void 0 ? {} : { overviewGraph: {
12491
+ id: personalOverview.id,
12492
+ name: personalOverview.name,
12493
+ scope: personalOverview.scope,
12494
+ computed: true,
12495
+ readOnly: true,
12496
+ counts: personalOverview.counts,
12497
+ next: "call kg_get {\"graph\":\"总图\"} for personal, or global/__overview__ / department/__overview__"
12498
+ } }
12499
+ },
12500
+ ...readable.length === 0 ? { next: "no graph exists yet; create one with " + graphCreateHint() + " (draft, then confirm:true)" } : {}
12501
+ };
12502
+ }
11403
12503
  const graph = requireGraph(graphs, args.graph);
12504
+ if (isOverviewGraph(graph)) return getOverview(host, graphs, graph);
11404
12505
  const store = graphJsonStore(graph);
11405
12506
  if (store !== void 0) return getFromGraphJson(host, graph, store, args.id);
11406
12507
  if (args.id === void 0 || args.id.trim() === "") return {
@@ -11520,6 +12621,7 @@ const createKnowledgeGraphTools = (host) => [
11520
12621
  output: jsonOutput$1,
11521
12622
  execute: async (args) => run$3(async () => {
11522
12623
  const graph = requireGraph(await host.listGraphs(), args.graph);
12624
+ if (isOverviewGraph(graph)) throw overviewReadOnly("item");
11523
12625
  const store = graphJsonStore(graph);
11524
12626
  if (store !== void 0) return setOnGraphJson(host, graph, store, args);
11525
12627
  const topic = requireTopic(graph, args.id);
@@ -11627,6 +12729,7 @@ const createKnowledgeGraphTools = (host) => [
11627
12729
  output: jsonOutput$1,
11628
12730
  execute: async (args) => run$3(async () => {
11629
12731
  const graph = requireGraph(await host.listGraphs(), args.graph);
12732
+ if (isOverviewGraph(graph)) return deleteOverviewEdge(host, graph, args);
11630
12733
  const store = graphJsonStore(graph);
11631
12734
  if (store !== void 0) return deleteFromGraphJson(host, graph, store, args);
11632
12735
  const topic = requireTopic(graph, args.id);
@@ -19953,6 +21056,20 @@ const Config = z.object({
19953
21056
  mineruMemoryMaxMiB: z.number().default(4096),
19954
21057
  publishDir: z.string().default(""),
19955
21058
  indexDir: z.string().default("/nas/kb/index"),
21059
+ overviewStoreDir: z.string().default(""),
21060
+ overviewEnabled: z.boolean().default(true),
21061
+ overviewStoreFallbackDir: z.string().default(""),
21062
+ overviewTtlMinutes: z.object({
21063
+ personal: z.number().default(10),
21064
+ department: z.number().default(20),
21065
+ global: z.number().default(45)
21066
+ }).default({
21067
+ personal: 10,
21068
+ department: 20,
21069
+ global: 45
21070
+ }),
21071
+ overviewMaxStores: z.number().default(64),
21072
+ overviewMemoryBudgetMB: z.number().default(32),
19956
21073
  retrieval: z.object({ vector: z.object({
19957
21074
  enabled: z.boolean().default(false),
19958
21075
  provider: z.union([z.const("openai-compatible"), z.const("ollama")]).default("openai-compatible"),
@@ -22692,6 +23809,18 @@ function apply(ctx, deploymentConfig) {
22692
23809
  tagged.readOnly = true;
22693
23810
  }
22694
23811
  mergeProjectedGraphs(graphTree, projectedByScope);
23812
+ const overviewRows = config.overviewEnabled === false ? [] : (await appendOverviewGraphs(graphToolHost, knowledgeGraphsOf(graphTree), overviewScopesFromRoots(roots))).filter(isOverviewGraph);
23813
+ for (const row of overviewRows) {
23814
+ const targetScope = graphTree.scopes.find((scope) => scope.key === row.scope);
23815
+ if (targetScope === void 0) continue;
23816
+ const firstGroup = targetScope.groups[0];
23817
+ if (firstGroup === void 0) targetScope.groups.push({
23818
+ key: "",
23819
+ label: "",
23820
+ graphs: [row]
23821
+ });
23822
+ else firstGroup.graphs.push(row);
23823
+ }
22695
23824
  return writeJson(res, 200, {
22696
23825
  ...graphTree,
22697
23826
  scopes: graphTree.scopes.map((scope) => ({
@@ -25604,11 +26733,23 @@ function apply(ctx, deploymentConfig) {
25604
26733
  const graphToolHost = {
25605
26734
  resolveCaller: knowledgeToolHost.resolveCaller,
25606
26735
  canWrite: knowledgeToolHost.canWrite,
25607
- createEntry: knowledgeToolHost.createEntry,
25608
- overwriteFile: knowledgeToolHost.overwriteFile,
25609
- moveEntry: knowledgeToolHost.moveEntry,
26736
+ createEntry: async (relPath, options) => {
26737
+ invalidateOverviewCache(graphToolHost);
26738
+ return knowledgeToolHost.createEntry(relPath, options);
26739
+ },
26740
+ overwriteFile: async (relPath, content) => {
26741
+ invalidateOverviewCache(graphToolHost);
26742
+ return knowledgeToolHost.overwriteFile(relPath, content);
26743
+ },
26744
+ moveEntry: async (from, to, caller) => {
26745
+ invalidateOverviewCache(graphToolHost);
26746
+ return knowledgeToolHost.moveEntry(from, to, caller);
26747
+ },
25610
26748
  statEntry: knowledgeToolHost.statEntry,
25611
- refreshView: knowledgeToolHost.refreshView,
26749
+ refreshView: async (expectVisible) => {
26750
+ invalidateOverviewCache(graphToolHost);
26751
+ return knowledgeToolHost.refreshView(expectVisible);
26752
+ },
25612
26753
  appendAudit: knowledgeToolHost.appendAudit,
25613
26754
  viewDir: knowledgeToolHost.viewDir,
25614
26755
  readText: async (viewPath) => {
@@ -25651,9 +26792,49 @@ function apply(ctx, deploymentConfig) {
25651
26792
  canRead: (relPath) => canReadPath(host, config, relPath)
25652
26793
  });
25653
26794
  mergeProjectedGraphs(tree, await projectGraphJsonScopes(host, config, roots, caller.userId));
25654
- return knowledgeGraphsOf(tree);
25655
- }
25656
- };
26795
+ if (config.overviewEnabled === false) return knowledgeGraphsOf(tree);
26796
+ return appendOverviewGraphs(graphToolHost, knowledgeGraphsOf(tree), overviewScopesFromRoots(roots));
26797
+ }
26798
+ };
26799
+ const overviewStoreSetting = (config.overviewStoreDir ?? "").trim();
26800
+ const requestedOverviewStoreDir = overviewStoreSetting === "" ? join(localConfig(config).actualRoot, ".overview") : resolveStorageRoot(overviewStoreSetting);
26801
+ let overviewStoreRoot = requestedOverviewStoreDir;
26802
+ const overviewFallbackSetting = (config.overviewStoreFallbackDir ?? "").trim();
26803
+ const overviewFallbackDir = overviewFallbackSetting === "" ? OVERVIEW_STORE_FALLBACK_DIR : resolveStorageRoot(overviewFallbackSetting);
26804
+ const overviewTtl = config.overviewTtlMinutes;
26805
+ const overviewStoreManager = new OverviewStoreManager(new JsonOverviewStoreProvider(graphToolHost, () => overviewStoreRoot), {
26806
+ ttlMs: {
26807
+ personal: (overviewTtl?.personal ?? 10) * 6e4,
26808
+ department: (overviewTtl?.department ?? 20) * 6e4,
26809
+ global: (overviewTtl?.global ?? 45) * 6e4
26810
+ },
26811
+ maxStores: config.overviewMaxStores ?? 64,
26812
+ memoryBudgetBytes: (config.overviewMemoryBudgetMB ?? 32) * 1024 * 1024
26813
+ });
26814
+ graphToolHost.overviewStores = overviewStoreManager;
26815
+ probeOverviewStoreDir(requestedOverviewStoreDir, overviewFallbackDir).then((probe) => {
26816
+ overviewStoreRoot = probe.dir;
26817
+ const message = "knowledge-base: overview store probe " + JSON.stringify({
26818
+ requested: probe.requested,
26819
+ dir: probe.dir,
26820
+ fallback: probe.fallback,
26821
+ ok: probe.ok,
26822
+ checks: probe.checks,
26823
+ ...probe.error === void 0 ? {} : { error: probe.error }
26824
+ });
26825
+ if (probe.ok && !probe.fallback) host.logger?.info?.(message);
26826
+ else host.logger?.warn?.(message);
26827
+ }).catch((error) => {
26828
+ host.logger?.warn?.("knowledge-base: overview store probe failed: " + (error instanceof Error ? error.message : String(error)));
26829
+ });
26830
+ const closeOverviewStores = () => {
26831
+ overviewStoreManager.closeAll();
26832
+ };
26833
+ process.once("exit", closeOverviewStores);
26834
+ ctx.effect(() => () => {
26835
+ process.off("exit", closeOverviewStores);
26836
+ overviewStoreManager.closeAll();
26837
+ }, "dsh-knowledge-base: overview store lifecycle");
25657
26838
  const memoryUsersRoot = (() => {
25658
26839
  const configured = (config.memoryUsersRoot ?? "").trim();
25659
26840
  return configured === "" ? join(localConfig(config).actualRoot, ".memory", "users") : resolveStorageRoot(configured);