dsh-layers-hippocampus 1.7.2 → 1.7.4

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/ui/client.js CHANGED
@@ -52,6 +52,8 @@
52
52
  sessionReset: '/api/hippocampus/session/reset',
53
53
  // Settings page: install the GitHub Orchestrator through the Host manager.
54
54
  orchestratorInstall: '/api/hippocampus/orchestrator/install',
55
+ // v1.7.4: recent recall/capture events, used only to light up the graph.
56
+ activity: '/api/hippocampus/activity',
55
57
  };
56
58
  const POLL_MS = 3000;
57
59
  /** Fallback ring budget (MB) when the Host has not sent the config yet. */
@@ -921,6 +923,98 @@
921
923
  return hash >>> 0;
922
924
  }
923
925
 
926
+ // ---- v1.7.4 graph geometry ---------------------------------------------
927
+ // Pure math: no DOM, no React, deterministic. Exported as
928
+ // `module.exports.graphGeometry` so the unit tests exercise real numbers
929
+ // instead of asserting on source text.
930
+ const GRAPH_MIN_RADIUS = 4;
931
+ const GRAPH_MAX_RADIUS = 14;
932
+ const GRAPH_LABEL_ROOM = 26;
933
+ const GRAPH_PADDING = 16;
934
+ // v1.7.5: dragging a node must NOT move the canvas. The old auto-pan made
935
+ // the view follow the pointer, so the node looked like it flew away instead
936
+ // of leaving the frame. Nodes may now be parked in a gutter around the world
937
+ // (still recoverable with 适应视图 / 双击), and the canvas only moves when the
938
+ // user drags empty space.
939
+ const GRAPH_DRAG_GUTTER = 240;
940
+
941
+ function clampNumber(value, low, high) {
942
+ const numeric = Number(value);
943
+ if (!Number.isFinite(numeric)) return low;
944
+ return Math.max(low, Math.min(high, numeric));
945
+ }
946
+
947
+ /** Node radius in CSS pixels — stays constant however far the view zooms. */
948
+ function computeRadius(node, maxWeight) {
949
+ if (node && node.ghost === true) return 4;
950
+ if (node && node.ghostRoot === true) return 6;
951
+ const weight = Math.max(0, Number(node && node.weight) || 0);
952
+ const ceiling = Math.max(1, Number(maxWeight) || 0);
953
+ const scale = Math.min(1, Math.sqrt(weight / ceiling));
954
+ return clampNumber(
955
+ GRAPH_MIN_RADIUS + scale * (GRAPH_MAX_RADIUS - GRAPH_MIN_RADIUS),
956
+ GRAPH_MIN_RADIUS,
957
+ GRAPH_MAX_RADIUS,
958
+ );
959
+ }
960
+
961
+ /**
962
+ * The drawable world is at least the viewport and grows when `count` nodes
963
+ * cannot be laid out readably inside it. Growing the world — then fitting
964
+ * the view — is what replaced the old behaviour of cramming everything into
965
+ * a fixed 640×320 box, which was the "dots piled up in the middle" bug.
966
+ */
967
+ function layoutWorld({ width, height, count } = {}) {
968
+ const viewWidth = Math.max(160, Number(width) || 0);
969
+ const viewHeight = Math.max(160, Number(height) || 0);
970
+ const cell = 96; // diameter + label room + breathing space per node
971
+ const needed = Math.max(1, Number(count) || 0) * cell * cell;
972
+ const factor = clampNumber(Math.sqrt(needed / (viewWidth * viewHeight)), 1, 3);
973
+ return {
974
+ x: 0,
975
+ y: 0,
976
+ width: Math.round(viewWidth * factor),
977
+ height: Math.round(viewHeight * factor),
978
+ factor,
979
+ };
980
+ }
981
+
982
+ function graphBounds(positions) {
983
+ if (!positions || positions.length === 0) return { minX: 0, minY: 0, maxX: 0, maxY: 0 };
984
+ let minX = Infinity;
985
+ let minY = Infinity;
986
+ let maxX = -Infinity;
987
+ let maxY = -Infinity;
988
+ for (const position of positions) {
989
+ const r = Number(position.r) || 6;
990
+ minX = Math.min(minX, position.x - r);
991
+ minY = Math.min(minY, position.y - r);
992
+ maxX = Math.max(maxX, position.x + r);
993
+ maxY = Math.max(maxY, position.y + r);
994
+ }
995
+ return { minX, minY, maxX, maxY };
996
+ }
997
+
998
+ /**
999
+ * Viewport transform that shows the whole graph. `k` may exceed 1 a little
1000
+ * so a 3-node graph is not lost in a corner, but never so far that a node
1001
+ * leaves the frame.
1002
+ */
1003
+ function fitView(positions, viewport, { padding = 40, maxScale = 1.4 } = {}) {
1004
+ const viewWidth = Math.max(80, Number(viewport && viewport.width) || 0);
1005
+ const viewHeight = Math.max(80, Number(viewport && viewport.height) || 0);
1006
+ if (!positions || positions.length === 0) return { x: 0, y: 0, k: 1 };
1007
+ const bounds = graphBounds(positions);
1008
+ const width = Math.max(1, bounds.maxX - bounds.minX + padding * 2);
1009
+ const height = Math.max(1, bounds.maxY - bounds.minY + padding * 2);
1010
+ const k = clampNumber(Math.min(maxScale, viewWidth / width, viewHeight / height), 0.2, 1.4);
1011
+ return {
1012
+ x: (viewWidth - width * k) / 2 - (bounds.minX - padding) * k,
1013
+ y: (viewHeight - height * k) / 2 - (bounds.minY - padding) * k,
1014
+ k,
1015
+ };
1016
+ }
1017
+
924
1018
  /**
925
1019
  * Position the graph ONCE, off the render path.
926
1020
  *
@@ -929,17 +1023,25 @@
929
1023
  * result is frozen in a ref by the caller, so progressive reveal — which
930
1024
  * only changes how many frozen coordinates are painted — can never restart
931
1025
  * the simulation.
1026
+ *
1027
+ * v1.7.4: distances and forces scale with the world size (not with a fixed
1028
+ * 640px constant), the centring force is a gentle spring instead of the old
1029
+ * `(width/2 - x) / width * 2` term that dwarfed repulsion and collapsed the
1030
+ * cloud, and every coordinate is clamped to the world, not to a 640×320 box.
932
1031
  */
933
- function computeLayout(nodes, edges, width, height) {
1032
+ function computeLayout(nodes, edges, width, height, maxWeight) {
1033
+ const worldWidth = Math.max(80, Number(width) || 0);
1034
+ const worldHeight = Math.max(80, Number(height) || 0);
934
1035
  const rand = mulberry32(hashSeed(nodes.map((node) => node.id).join('|')));
935
1036
  const index = new Map(nodes.map((node, i) => [node.id, i]));
936
1037
  const count = nodes.length;
937
1038
  const positions = nodes.map((node, i) => ({
938
1039
  id: node.id,
939
- x: width / 2 + (rand() - 0.5) * width * 0.6 + (i % 7) * 2,
940
- y: height / 2 + (rand() - 0.5) * height * 0.6 + (i % 5) * 2,
1040
+ x: worldWidth / 2 + (rand() - 0.5) * worldWidth * 0.5 + (i % 7) * 2,
1041
+ y: worldHeight / 2 + (rand() - 0.5) * worldHeight * 0.5 + (i % 5) * 2,
941
1042
  vx: 0,
942
1043
  vy: 0,
1044
+ r: computeRadius(node, maxWeight),
943
1045
  // Isolated nodes get extra jitter so they cannot sit in a neat pile.
944
1046
  jitter: (rand() - 0.5) * 24,
945
1047
  }));
@@ -948,8 +1050,10 @@
948
1050
  .map((edge) => ({ a: index.get(edge.source), b: index.get(edge.target), weight: edge.weight || 1 }))
949
1051
  .filter((link) => link.a !== undefined && link.b !== undefined);
950
1052
 
951
- const iterations = Math.min(320, 40 + count * 4);
952
- const repulsion = 900;
1053
+ const area = worldWidth * worldHeight;
1054
+ const spacing = clampNumber(Math.sqrt((area * 0.08) / Math.max(1, count)), 44, 150);
1055
+ const repulsion = 0.9 * spacing * spacing;
1056
+ const iterations = Math.min(600, 80 + count * 8);
953
1057
  for (let step = 0; step < iterations; step += 1) {
954
1058
  const alpha = 0.9 * (1 - step / iterations) + 0.02;
955
1059
  for (let i = 0; i < count; i += 1) {
@@ -959,12 +1063,13 @@
959
1063
  let dx = a.x - b.x;
960
1064
  let dy = a.y - b.y;
961
1065
  let distance = Math.sqrt(dx * dx + dy * dy);
962
- if (distance < 1) {
1066
+ if (distance < 0.001) {
963
1067
  dx = (rand() - 0.5) * 2;
964
1068
  dy = (rand() - 0.5) * 2;
965
1069
  distance = 1;
966
1070
  }
967
- const force = (repulsion / (distance * distance)) * alpha;
1071
+ const d = Math.max(6, distance); // clamp so a near-collision cannot explode
1072
+ const force = (repulsion / (d * d)) * alpha;
968
1073
  const fx = (dx / distance) * force;
969
1074
  const fy = (dy / distance) * force;
970
1075
  a.vx += fx;
@@ -979,40 +1084,47 @@
979
1084
  const dx = b.x - a.x;
980
1085
  const dy = b.y - a.y;
981
1086
  const distance = Math.sqrt(dx * dx + dy * dy) || 1;
982
- const target = 80;
1087
+ const target = 46 + 0.9 * ((a.r || 6) + (b.r || 6));
983
1088
  const force = ((distance - target) / distance) * 0.04 * alpha * Math.min(2, link.weight);
984
1089
  a.vx += dx * force;
985
1090
  a.vy += dy * force;
986
1091
  b.vx -= dx * force;
987
1092
  b.vy -= dy * force;
988
1093
  }
1094
+ let fastest = 0;
989
1095
  for (let i = 0; i < count; i += 1) {
990
1096
  const node = positions[i];
991
- node.vx += ((width / 2 - node.x) / width) * 2 * alpha;
992
- node.vy += ((height / 2 - node.y) / height) * 2 * alpha;
993
- node.vx *= 0.6;
994
- node.vy *= 0.6;
995
- node.x = Math.max(24, Math.min(width - 24, node.x + node.vx + node.jitter * 0.05));
996
- node.y = Math.max(24, Math.min(height - 24, node.y + node.vy + node.jitter * 0.05));
1097
+ // Gentle spring: 1/50 of the remaining distance per unit alpha.
1098
+ node.vx += (worldWidth / 2 - node.x) * 0.02 * alpha;
1099
+ node.vy += (worldHeight / 2 - node.y) * 0.02 * alpha;
1100
+ node.vx *= 0.72;
1101
+ node.vy *= 0.72;
1102
+ node.x = clampNumber(node.x + node.vx + node.jitter * 0.05, GRAPH_PADDING, worldWidth - GRAPH_PADDING);
1103
+ node.y = clampNumber(node.y + node.vy + node.jitter * 0.05, GRAPH_PADDING, worldHeight - GRAPH_PADDING);
1104
+ fastest = Math.max(fastest, Math.abs(node.vx), Math.abs(node.vy));
997
1105
  }
1106
+ if (step > 40 && fastest < 0.05) break;
998
1107
  }
999
1108
  return positions;
1000
1109
  }
1001
1110
 
1002
1111
  /**
1003
- * v1.5.6: initial overlap separation. The force pass can leave a pair (or a
1004
- * tight cluster) closer than a readable node, especially with equal weights.
1005
- * One deterministic post-pass pushes every pair below `minDistance` apart
1006
- * without re-running the simulation, so the first painted frame is already
1007
- * readable instead of a pile of labels.
1112
+ * Post-pass that guarantees readable spacing: every pair is pushed apart
1113
+ * until the gap covers both radii plus label room, and each push stays
1114
+ * inside the world so no node slides out of reach.
1008
1115
  */
1009
- function separateOverlaps(positions, { minDistance = 56, passes = 14 } = {}) {
1116
+ function separateOverlaps(positions, { width = null, height = null, padding = GRAPH_PADDING, passes = 16 } = {}) {
1117
+ const worldWidth = Number.isFinite(Number(width)) ? Number(width) : null;
1118
+ const worldHeight = Number.isFinite(Number(height)) ? Number(height) : null;
1119
+ const clampX = (value) => (worldWidth === null ? value : clampNumber(value, padding, worldWidth - padding));
1120
+ const clampY = (value) => (worldHeight === null ? value : clampNumber(value, padding, worldHeight - padding));
1010
1121
  for (let pass = 0; pass < passes; pass += 1) {
1011
1122
  let moved = false;
1012
1123
  for (let i = 0; i < positions.length; i += 1) {
1013
1124
  for (let j = i + 1; j < positions.length; j += 1) {
1014
1125
  const a = positions[i];
1015
1126
  const b = positions[j];
1127
+ const minDistance = (a.r || 6) + (b.r || 6) + GRAPH_LABEL_ROOM;
1016
1128
  const dx = a.x - b.x;
1017
1129
  const dy = a.y - b.y;
1018
1130
  const distance = Math.sqrt(dx * dx + dy * dy);
@@ -1021,10 +1133,10 @@
1021
1133
  const angle = distance > 0.001 ? Math.atan2(dy, dx) : ((i * 37 + j * 17) % 628) / 100;
1022
1134
  const ux = Math.cos(angle);
1023
1135
  const uy = Math.sin(angle);
1024
- a.x += ux * push;
1025
- a.y += uy * push;
1026
- b.x -= ux * push;
1027
- b.y -= uy * push;
1136
+ a.x = clampX(a.x + ux * push);
1137
+ a.y = clampY(a.y + uy * push);
1138
+ b.x = clampX(b.x - ux * push);
1139
+ b.y = clampY(b.y - uy * push);
1028
1140
  moved = true;
1029
1141
  }
1030
1142
  }
@@ -1142,10 +1254,102 @@
1142
1254
  );
1143
1255
  }
1144
1256
 
1257
+ // ---- v1.7.4 activity glow ---------------------------------------------
1258
+
1259
+ const GLOW_PRESETS = {
1260
+ accent: { strong: '#0a2f6b', weak: '#7fb0ff', capture: '#bfe0ff' },
1261
+ vivid: { strong: '#0b3d1f', weak: '#63e6a4', capture: '#c8ffe0' },
1262
+ warm: { strong: '#5a2b00', weak: '#ffb481', capture: '#ffe3b0' },
1263
+ };
1264
+ const GLOW_STRONG_TAG_LIMIT = 6;
1265
+ const GLOW_WEAK_TAG_LIMIT = 24;
1266
+ const GLOW_DWELL_MS = 2400;
1267
+ const GLOW_FRESH_MS = 6000;
1268
+
1269
+ function normalizeHex(value) {
1270
+ return typeof value === 'string' && /^#[0-9a-fA-F]{6}$/.test(value.trim()) ? value.trim().toLowerCase() : null;
1271
+ }
1272
+
1273
+ function mixHex(a, b, ratio) {
1274
+ const left = normalizeHex(a) || '#4f8cff';
1275
+ const right = normalizeHex(b) || '#ffffff';
1276
+ const blend = (offset) => {
1277
+ const x = parseInt(left.slice(offset, offset + 2), 16);
1278
+ const y = parseInt(right.slice(offset, offset + 2), 16);
1279
+ return Math.round(x + (y - x) * ratio).toString(16).padStart(2, '0');
1280
+ };
1281
+ return '#' + blend(1) + blend(3) + blend(5);
1282
+ }
1283
+
1284
+ /**
1285
+ * Glow colours, derived from the theme accent by default so a white canvas
1286
+ * keeps enough contrast (the shadow is dark blue, not a pale wash).
1287
+ */
1288
+ function glowColors({ preset = 'accent', custom = null } = {}) {
1289
+ if (normalizeHex(custom)) {
1290
+ const base = normalizeHex(custom);
1291
+ return { strong: mixHex(base, '#0a1b3d', 0.35), weak: mixHex(base, '#ffffff', 0.55), capture: mixHex(base, '#ffffff', 0.2) };
1292
+ }
1293
+ return GLOW_PRESETS[preset] || GLOW_PRESETS.accent;
1294
+ }
1295
+
1296
+ const GRAPH_STYLE = [
1297
+ '.hp-graph svg g.hp-glow-strong circle.hp-dot { stroke: var(--hip-glow-strong); stroke-width: 2.4; filter: drop-shadow(0 0 3px var(--hip-glow-strong)) drop-shadow(0 0 11px var(--hip-glow-strong)); }',
1298
+ '.hp-graph svg g.hp-glow-weak circle.hp-dot { stroke: var(--hip-glow-weak); stroke-width: 1.8; filter: drop-shadow(0 0 5px var(--hip-glow-weak)); }',
1299
+ '.hp-graph svg g.hp-glow-capture circle.hp-dot { stroke: var(--hip-glow-capture); stroke-width: 2; animation: hp-glow-pulse 620ms ease-out 1; }',
1300
+ '@keyframes hp-glow-pulse { 0% { filter: drop-shadow(0 0 0 var(--hip-glow-capture)); } 45% { filter: drop-shadow(0 0 12px var(--hip-glow-capture)); } 100% { filter: drop-shadow(0 0 2px var(--hip-glow-capture)); } }',
1301
+ '@media (prefers-reduced-motion: reduce) { .hp-graph svg g.hp-glow-capture circle.hp-dot { animation: none; } }',
1302
+ ].join('\n');
1303
+
1304
+ /** Poll the activity feed; it is decoration, so every failure is silent. */
1305
+ function useActivity({ spaceId, enabled, intervalMs = 1000 }) {
1306
+ const [feed, setFeed] = React.useState({ items: [], cursor: 0, at: 0 });
1307
+ React.useEffect(() => {
1308
+ if (!enabled) return undefined;
1309
+ let alive = true;
1310
+ let timer = 0;
1311
+ const tick = async () => {
1312
+ if (!alive) return;
1313
+ try {
1314
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return;
1315
+ const query = new URLSearchParams();
1316
+ if (spaceId) query.set('space', spaceId);
1317
+ query.set('since', String(feed.cursor || 0));
1318
+ const response = await fetch(API.activity + '?' + query.toString(), { headers: { accept: 'application/json' } });
1319
+ if (!response.ok) return;
1320
+ const payload = await response.json();
1321
+ if (!alive) return;
1322
+ const items = Array.isArray(payload.items) ? payload.items : [];
1323
+ if (items.length > 0) setFeed({ items, cursor: Number(payload.cursor) || feed.cursor, at: Date.now() });
1324
+ } catch {
1325
+ /* activity is a hint, never a dependency */
1326
+ }
1327
+ };
1328
+ tick();
1329
+ timer = setInterval(tick, intervalMs);
1330
+ return () => {
1331
+ alive = false;
1332
+ clearInterval(timer);
1333
+ };
1334
+ }, [spaceId, enabled, intervalMs, feed.cursor]);
1335
+ return feed;
1336
+ }
1337
+
1145
1338
  function KnowledgeGraph(props) {
1146
1339
  const graph = props.graph;
1147
- const width = 640;
1148
- const height = 320;
1340
+ const ui = (props.config && props.config.ui) || {};
1341
+ const glowEnabled = ui.graphGlowEnabled !== false;
1342
+ const glowLook = { preset: ui.graphGlowPreset || 'accent', custom: ui.graphGlowCustom || null };
1343
+ const canvasTint = ui.graphCanvasTint || 'auto';
1344
+ const colors = glowColors(glowLook);
1345
+ const canvasBackground = canvasTint === 'none' ? 'transparent' : canvasTint === 'tint' ? 'rgba(79,140,255,0.055)' : 'rgba(15,23,42,0.035)';
1346
+ const spaceId = props.spaceId || null;
1347
+ const wrapRef = React.useRef(null);
1348
+ const [boxWidth, setBoxWidth] = React.useState(640);
1349
+ // Real pixels, not a fixed 640×320 drawing: a narrow side rail must not
1350
+ // scale dots and labels down to nothing.
1351
+ const width = Math.max(240, Math.round(boxWidth));
1352
+ const height = Math.max(280, Math.min(520, Math.round(width * 0.55)));
1149
1353
  const nodes = (graph && graph.nodes) || [];
1150
1354
  const edges = (graph && graph.edges) || [];
1151
1355
  // Ghost nodes come from the tag tree's grace window (state/tag-tree.json via
@@ -1160,13 +1364,30 @@
1160
1364
  const allNodes = [...nodes, ...ghostRootNodes, ...ghostNodes];
1161
1365
  const allEdges = [...edges, ...ghostEdges];
1162
1366
 
1367
+ const maxWeight = Math.max(1, ...allNodes.map((node) => node.weight || 0));
1163
1368
  const layoutRef = React.useRef(null);
1164
1369
  const layoutKey =
1165
- allNodes.length + ':' + allEdges.length + ':' + (graph ? graph.generatedAt : 0) + ':' + ghostNodes.map((node) => node.id).join(',');
1370
+ allNodes.length +
1371
+ ':' +
1372
+ allEdges.length +
1373
+ ':' +
1374
+ (graph ? graph.generatedAt : 0) +
1375
+ ':' +
1376
+ ghostNodes.map((node) => node.id).join(',') +
1377
+ ':' +
1378
+ Math.round(width / 16) +
1379
+ 'x' +
1380
+ Math.round(height / 16);
1166
1381
  if (!layoutRef.current || layoutRef.current.key !== layoutKey) {
1167
- layoutRef.current = { key: layoutKey, positions: separateOverlaps(computeLayout(allNodes, allEdges, width, height)) };
1382
+ const world = layoutWorld({ width, height, count: allNodes.length });
1383
+ const positions = separateOverlaps(computeLayout(allNodes, allEdges, world.width, world.height, maxWeight), {
1384
+ width: world.width,
1385
+ height: world.height,
1386
+ });
1387
+ layoutRef.current = { key: layoutKey, positions, world };
1168
1388
  }
1169
1389
  const positions = layoutRef.current.positions;
1390
+ const world = layoutRef.current.world;
1170
1391
  const byId = new Map(positions.map((position) => [position.id, position]));
1171
1392
  const indexOfId = new Map(positions.map((position, i) => [position.id, i]));
1172
1393
 
@@ -1188,10 +1409,39 @@
1188
1409
  const v = viewRef.current;
1189
1410
  g.setAttribute('transform', `translate(${v.x}, ${v.y}) scale(${v.k})`);
1190
1411
  };
1191
- const resetView = () => {
1192
- viewRef.current = { x: 0, y: 0, k: 1 };
1412
+ const fitToContent = () => {
1413
+ viewRef.current = fitView(positions, { width, height });
1193
1414
  applyView();
1194
1415
  };
1416
+ const resetView = fitToContent;
1417
+
1418
+ // Measure the card so the drawing matches the space it actually has.
1419
+ React.useEffect(() => {
1420
+ const el = wrapRef.current;
1421
+ if (!el) return undefined;
1422
+ const measure = () => {
1423
+ const rect = typeof el.getBoundingClientRect === 'function' ? el.getBoundingClientRect() : null;
1424
+ const next = Math.max(240, Math.round((rect && rect.width) || 640));
1425
+ setBoxWidth((prev) => (Math.abs(prev - next) > 24 ? next : prev));
1426
+ };
1427
+ measure();
1428
+ if (typeof ResizeObserver === 'function') {
1429
+ const observer = new ResizeObserver(measure);
1430
+ observer.observe(el);
1431
+ return () => observer.disconnect();
1432
+ }
1433
+ if (typeof window !== 'undefined' && window.addEventListener) {
1434
+ window.addEventListener('resize', measure);
1435
+ return () => window.removeEventListener('resize', measure);
1436
+ }
1437
+ return undefined;
1438
+ }, []);
1439
+
1440
+ // A fresh layout (or a resize) is shown in full.
1441
+ React.useEffect(() => {
1442
+ viewRef.current = fitView(positions, { width, height });
1443
+ applyView();
1444
+ }, [layoutKey, width, height]);
1195
1445
 
1196
1446
  React.useEffect(() => {
1197
1447
  aliveRef.current = true;
@@ -1251,7 +1501,49 @@
1251
1501
  }, [layoutKey, allNodes.length]);
1252
1502
 
1253
1503
  const [focus, setFocus] = React.useState(null);
1254
- const maxWeight = Math.max(1, ...allNodes.map((node) => node.weight || 0));
1504
+ const feed = useActivity({ spaceId, enabled: glowEnabled });
1505
+ const glowTimer = React.useRef(0);
1506
+ React.useEffect(() => {
1507
+ if (!glowEnabled) return undefined;
1508
+ const clearGlow = () => {
1509
+ for (const el of nodeEls.current) {
1510
+ if (el && el.classList) el.classList.remove('hp-glow-strong', 'hp-glow-weak', 'hp-glow-capture');
1511
+ }
1512
+ };
1513
+ const now = Date.now();
1514
+ const fresh = (feed.items || []).filter((item) => now - (Number(item.at) || now) <= GLOW_FRESH_MS);
1515
+ clearGlow();
1516
+ if (fresh.length === 0) return undefined;
1517
+ const strong = new Set();
1518
+ const capture = new Set();
1519
+ const weak = new Set();
1520
+ for (const item of fresh) {
1521
+ const tags = Array.isArray(item.tags) ? item.tags : [];
1522
+ for (const tag of tags) {
1523
+ if (typeof tag !== 'string') continue;
1524
+ if (item.kind === 'capture') capture.add(tag);
1525
+ else strong.add(tag);
1526
+ }
1527
+ }
1528
+ for (const edge of allEdges) {
1529
+ if (strong.has(edge.source)) weak.add(edge.target);
1530
+ else if (strong.has(edge.target)) weak.add(edge.source);
1531
+ }
1532
+ for (const tag of strong) weak.delete(tag);
1533
+ for (const tag of capture) weak.delete(tag);
1534
+ for (const position of positions) {
1535
+ const el = nodeEls.current[indexOfId.get(position.id)];
1536
+ if (!el || !el.classList) continue;
1537
+ if (capture.has(position.id)) el.classList.add('hp-glow-capture');
1538
+ else if (strong.has(position.id) && strong.size <= GLOW_STRONG_TAG_LIMIT) el.classList.add('hp-glow-strong');
1539
+ else if (weak.has(position.id) && weak.size <= GLOW_WEAK_TAG_LIMIT) el.classList.add('hp-glow-weak');
1540
+ }
1541
+ glowTimer.current = setTimeout(clearGlow, GLOW_DWELL_MS);
1542
+ return () => {
1543
+ if (glowTimer.current) clearTimeout(glowTimer.current);
1544
+ clearGlow();
1545
+ };
1546
+ }, [feed.at, glowEnabled, layoutKey]);
1255
1547
 
1256
1548
  /** Repaint node transforms + every rendered line from the frozen array. */
1257
1549
  const paint = () => {
@@ -1390,7 +1682,8 @@
1390
1682
  const dx = b.x - a.x;
1391
1683
  const dy = b.y - a.y;
1392
1684
  const distance = Math.max(1, Math.sqrt(dx * dx + dy * dy));
1393
- const force = ((distance - 80) / distance) * 0.06 * alpha * Math.min(2, link.weight);
1685
+ const target = 46 + 0.9 * ((a.r || 6) + (b.r || 6));
1686
+ const force = ((distance - target) / distance) * 0.06 * alpha * Math.min(2, link.weight);
1394
1687
  a.vx += dx * force;
1395
1688
  a.vy += dy * force;
1396
1689
  b.vx -= dx * force;
@@ -1400,8 +1693,8 @@
1400
1693
  const node = positions[i];
1401
1694
  node.vx *= 0.7;
1402
1695
  node.vy *= 0.7;
1403
- node.x = Math.max(24, Math.min(width - 24, node.x + node.vx));
1404
- node.y = Math.max(24, Math.min(height - 24, node.y + node.vy));
1696
+ node.x = clampNumber(node.x + node.vx, GRAPH_PADDING - GRAPH_DRAG_GUTTER, world.width - GRAPH_PADDING + GRAPH_DRAG_GUTTER);
1697
+ node.y = clampNumber(node.y + node.vy, GRAPH_PADDING - GRAPH_DRAG_GUTTER, world.height - GRAPH_PADDING + GRAPH_DRAG_GUTTER);
1405
1698
  // The centre node is pinned only while the pointer is down; after
1406
1699
  // release it settles like the rest of the local neighbourhood.
1407
1700
  }
@@ -1459,8 +1752,10 @@
1459
1752
  }
1460
1753
  const point = toSvg(evt);
1461
1754
  const position = positions[drag.index];
1462
- position.x = Math.max(24, Math.min(width - 24, point.x + drag.offsetX));
1463
- position.y = Math.max(24, Math.min(height - 24, point.y + drag.offsetY));
1755
+ // The node follows the pointer and may leave the visible frame: the only
1756
+ // limit is the world plus a gutter, so nothing is permanently lost.
1757
+ position.x = clampNumber(point.x + drag.offsetX, GRAPH_PADDING - GRAPH_DRAG_GUTTER, world.width - GRAPH_PADDING + GRAPH_DRAG_GUTTER);
1758
+ position.y = clampNumber(point.y + drag.offsetY, GRAPH_PADDING - GRAPH_DRAG_GUTTER, world.height - GRAPH_PADDING + GRAPH_DRAG_GUTTER);
1464
1759
  position.vx = 0;
1465
1760
  position.vy = 0;
1466
1761
  paint();
@@ -1492,7 +1787,17 @@
1492
1787
 
1493
1788
  return h(
1494
1789
  'div',
1495
- { style: cardStyle },
1790
+ {
1791
+ ref: wrapRef,
1792
+ className: 'hp-graph',
1793
+ style: {
1794
+ ...cardStyle,
1795
+ '--hip-glow-strong': colors.strong,
1796
+ '--hip-glow-weak': colors.weak,
1797
+ '--hip-glow-capture': colors.capture,
1798
+ },
1799
+ },
1800
+ h('style', null, GRAPH_STYLE),
1496
1801
  h(
1497
1802
  'div',
1498
1803
  { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginBottom: 6 } },
@@ -1502,10 +1807,22 @@
1502
1807
  { style: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' } },
1503
1808
  h(
1504
1809
  'div',
1505
- { style: { ...labelStyle, marginBottom: 0 }, title: '按住 Ctrl(Mac 为 Cmd)拖拽画布平移;Ctrl + 滚轮缩放;双击空白处重置视图' },
1506
- 'Ctrl 拖拽平移 · Ctrl 滚轮缩放',
1810
+ { style: { ...labelStyle, marginBottom: 0 }, title: '空白处拖拽平移;Ctrl + 滚轮缩放;双击空白或点「适应视图」回到全貌' },
1811
+ '拖拽平移 · Ctrl 滚轮缩放',
1507
1812
  ),
1508
- h('div', { style: { ...labelStyle, marginBottom: 0 } }, `${fmtNumber(graph.nodeCount)} 节点 · ${fmtNumber(graph.edgeCount)} 边${graph.truncated ? '(已截断)' : ''}`),
1813
+ h(
1814
+ 'button',
1815
+ { type: 'button', onClick: fitToContent, style: toggleStyle(false), title: '缩放到刚好看见整张图谱' },
1816
+ '适应视图',
1817
+ ),
1818
+ h(
1819
+ 'div',
1820
+ { style: { ...labelStyle, marginBottom: 0 }, title: Number(graph.droppedNodes) > 0 ? '节点上限可在设置 → 图谱与光效里调整' : '当前显示全部节点' },
1821
+ `${fmtNumber(graph.nodeCount)}/${fmtNumber(graph.totalNodes || graph.nodeCount)} 节点 · ${fmtNumber(graph.edgeCount)} 边${graph.truncated ? '(已截断)' : ''}`,
1822
+ ),
1823
+ Number(graph.droppedNodes) > 0
1824
+ ? h('div', { style: { ...labelStyle, marginBottom: 0, color: palette.warn } }, `+${fmtNumber(graph.droppedNodes)} 节点未显示(按事件数从少到多隐藏)`)
1825
+ : null,
1509
1826
  ghostNodes.length > 0
1510
1827
  ? h(
1511
1828
  'div',
@@ -1532,10 +1849,12 @@
1532
1849
  {
1533
1850
  ref: svgRef,
1534
1851
  width: '100%',
1852
+ height,
1535
1853
  viewBox: `0 0 ${width} ${height}`,
1536
- style: { display: 'block', touchAction: 'none' },
1854
+ style: { display: 'block', touchAction: 'none', background: canvasBackground, borderRadius: 6 },
1537
1855
  onPointerDown: (evt) => {
1538
- if ((evt.ctrlKey || evt.metaKey) && evt.target === evt.currentTarget) startPan(evt);
1856
+ // Empty canvas: plain drag pans, no modifier needed.
1857
+ if (evt.target === evt.currentTarget) startPan(evt);
1539
1858
  },
1540
1859
  onPointerMove,
1541
1860
  onPointerUp: endDrag,
@@ -1545,6 +1864,20 @@
1545
1864
  },
1546
1865
  },
1547
1866
  h('g', { ref: groupRef, transform: 'translate(0, 0) scale(1)' },
1867
+ // The dashed frame is the layout world: everything inside is reachable
1868
+ // by dragging, and it grows with the node count instead of clipping.
1869
+ h('rect', {
1870
+ key: 'world',
1871
+ x: 0,
1872
+ y: 0,
1873
+ width: world.width,
1874
+ height: world.height,
1875
+ fill: 'none',
1876
+ stroke: palette.border,
1877
+ strokeDasharray: '6 6',
1878
+ opacity: 0.5,
1879
+ pointerEvents: 'none',
1880
+ }),
1548
1881
  // Edges first, and only when BOTH endpoints are painted: no dangling lines.
1549
1882
  allEdges.map((edge, i) => {
1550
1883
  const a = byId.get(edge.source);
@@ -1576,7 +1909,7 @@
1576
1909
  if (!position) return null;
1577
1910
  const ghost = node.ghost === true;
1578
1911
  const ghostRoot = node.ghostRoot === true;
1579
- const radius = ghost ? 4 : ghostRoot ? 6 : 3 + (Math.sqrt((node.weight || 0) / maxWeight) || 0) * 7;
1912
+ const radius = computeRadius(node, maxWeight);
1580
1913
  const core = !ghost && !ghostRoot && i < 5;
1581
1914
  const active = focus === node.id;
1582
1915
  return h(
@@ -1587,6 +1920,7 @@
1587
1920
  nodeEls.current[i] = el;
1588
1921
  },
1589
1922
  transform: `translate(${position.x}, ${position.y})`,
1923
+ 'data-node-id': node.id,
1590
1924
  style: {
1591
1925
  cursor: 'grab',
1592
1926
  touchAction: 'none',
@@ -1608,6 +1942,7 @@
1608
1942
  fill: 'transparent', // larger hit target, invisible
1609
1943
  }),
1610
1944
  h('circle', {
1945
+ className: 'hp-dot',
1611
1946
  r: radius,
1612
1947
  fill: ghost ? 'rgba(217,155,43,0.22)' : ghostRoot ? 'transparent' : active ? palette.accent : 'rgba(79,140,255,0.55)',
1613
1948
  stroke: ghost || ghostRoot ? palette.warn : palette.border,
@@ -1624,7 +1959,7 @@
1624
1959
  }),
1625
1960
  ),
1626
1961
  ),
1627
- h('div', { style: { ...labelStyle, marginTop: 6, marginBottom: 0 } }, 'Ctrl+拖拽平移 · Ctrl+滚轮缩放 · 双击空白重置视图;拖拽节点可移动;单击查看标签;核心节点常显。幽灵节点=宽限期内的层级记忆,仅在"历史全貌"可见(半透明、虚线、挂在父 root 下)。'),
1962
+ h('div', { style: { ...labelStyle, marginTop: 6, marginBottom: 0 } }, '空白处拖拽平移 · Ctrl+滚轮缩放 · 双击空白或「适应视图」回到全貌;拖拽节点可移动,节点能被拖出可见范围(画布不会跟着跑,点「适应视图」就能把它找回来);单击查看标签;核心节点常显。虚线框是布局边界,随节点数自动扩大。最近 recall 命中的标签会亮起,相邻标签弱亮。幽灵节点=宽限期内的层级记忆,仅在"历史全貌"可见(半透明、虚线、挂在父 root 下)。'),
1628
1963
  );
1629
1964
  }
1630
1965
 
@@ -2266,7 +2601,12 @@
2266
2601
  ? h('div', { style: { ...labelStyle, marginBottom: 0 } }, `检索:${searchQuery}(命中 ${shownGraph.nodes.length} 个标签)`)
2267
2602
  : null,
2268
2603
  graphState.graph
2269
- ? h(KnowledgeGraph, { graph: shownGraph, ghosts: (graphState.tagTree && graphState.tagTree.ghosts) || [] })
2604
+ ? h(KnowledgeGraph, {
2605
+ graph: shownGraph,
2606
+ config: payload.config || null,
2607
+ spaceId: activeSpace || null,
2608
+ ghosts: (graphState.tagTree && graphState.tagTree.ghosts) || [],
2609
+ })
2270
2610
  : h('div', { style: { ...cardStyle, color: palette.muted, fontSize: 13 } }, graphState.error ? `图谱不可用:${graphState.error.code}` : '正在读取图谱缓存…'),
2271
2611
  // UI_TASK_1/3: business rows are CHECKBOXES for the regulated mover. The
2272
2612
  // old per-row transfer button and the raw event_ids text box are gone.
@@ -2573,6 +2913,15 @@
2573
2913
  enableReflection: Boolean(config.enableReflection),
2574
2914
  dreamIdleMinutes: Number(config.dreamIdleMinutes),
2575
2915
  graphMaxEdges: Number(config.graphMaxEdges),
2916
+ graphMaxNodes: Number(config.graphMaxNodes ?? 80),
2917
+ // v1.7.4 graph appearance: glow + canvas. Defaults mirror config.js.
2918
+ ui: {
2919
+ graphGlowEnabled: config.ui ? config.ui.graphGlowEnabled !== false : true,
2920
+ graphGlowPreset: (config.ui && config.ui.graphGlowPreset) || 'accent',
2921
+ graphGlowCustom: (config.ui && config.ui.graphGlowCustom) || '',
2922
+ graphCanvasTint: (config.ui && config.ui.graphCanvasTint) || 'auto',
2923
+ graphActivityPersist: Boolean(config.ui && config.ui.graphActivityPersist),
2924
+ },
2576
2925
  storageBudgetMb: Number(config.storageBudgetMb),
2577
2926
  // L1.5 tag-tree lifecycle. Defaults mirror config.js; the form sends the
2578
2927
  // four dotted keys back in the same patch as every other setting.
@@ -2676,6 +3025,7 @@
2676
3025
  const NUMBER_RULES = [
2677
3026
  { key: 'dreamIdleMinutes', label: '空闲判定', min: 1, max: 525600 },
2678
3027
  { key: 'graphMaxEdges', label: '图谱最大边数', min: 100, max: 2000 },
3028
+ { key: 'graphMaxNodes', label: '图谱节点上限', min: 10, max: 2000 },
2679
3029
  { key: 'storageBudgetMb', label: '存储预算', min: 10, max: 1000 },
2680
3030
  { key: 'decayHalfLifeDays', label: '记忆半衰期', min: 7, max: 365 },
2681
3031
  { key: 'activeSetCap', label: '活跃标签上限', min: 100, max: 1000 },
@@ -2928,11 +3278,110 @@
2928
3278
  * item each; `visibleInSimple` makes the 简洁模式 promise (身份 / 上下文窗口 / 存储迁移 /
2929
3279
  * 原始回合留存) declarative instead of a `simpleMode &&` scattered across the JSX.
2930
3280
  */
3281
+ /**
3282
+ * v1.7.4: 图谱与光效。节点上限决定「最少事件先出局」的截断点;光效把 recall
3283
+ * 命中的标签点亮(强/弱/脉冲三级),颜色默认由主题强调色派生。
3284
+ */
3285
+ function SettingsGraphGroup(bag) {
3286
+ const { draft, edit, disabled } = bag;
3287
+ const ui = draft.ui || {};
3288
+ return [
3289
+ h(
3290
+ Section,
3291
+ { title: '图谱规模', hint: '节点按「事件数最少优先」隐藏,事件最多的标签永远保留;被隐藏的数量会在图标题里以 +N 提示。' },
3292
+ h(Field, {
3293
+ label: '节点上限(graphMaxNodes)',
3294
+ hint: '默认 80。调大能看见更多标签,但布局更密。',
3295
+ value: draft.graphMaxNodes,
3296
+ min: 10,
3297
+ max: 2000,
3298
+ step: 10,
3299
+ onChange: (value) => edit('graphMaxNodes', value),
3300
+ disabled,
3301
+ }),
3302
+ h(Field, {
3303
+ label: '边上限(graphMaxEdges)',
3304
+ hint: '保存后立即按新上限重新拉取 /api/hippocampus/graph 并重绘。',
3305
+ value: draft.graphMaxEdges,
3306
+ min: 100,
3307
+ max: 2000,
3308
+ step: 100,
3309
+ onChange: (value) => edit('graphMaxEdges', value),
3310
+ disabled,
3311
+ }),
3312
+ ),
3313
+ h(
3314
+ Section,
3315
+ { title: 'recall 光效', hint: '记忆被 recall 命中时对应标签强光亮起、相邻标签弱亮;新写入的标签脉冲一次(620ms),2.4 秒后自动淡出。' },
3316
+ h(Toggle, {
3317
+ label: '启用光效',
3318
+ hint: '关闭后图谱不再随 recall 亮起(静态偏好或低性能设备)。',
3319
+ checked: ui.graphGlowEnabled !== false,
3320
+ onChange: (value) => edit('ui.graphGlowEnabled', value),
3321
+ disabled,
3322
+ }),
3323
+ h(Select, {
3324
+ label: '预设色(ui.graphGlowPreset)',
3325
+ hint: 'accent 跟随主题强调色(默认,白底也够对比);vivid / warm 为高对比预设。',
3326
+ value: ui.graphGlowPreset || 'accent',
3327
+ options: [
3328
+ { value: 'accent', label: 'accent — 跟随主题强调色(默认)' },
3329
+ { value: 'vivid', label: 'vivid — 冷绿高对比' },
3330
+ { value: 'warm', label: 'warm — 暖橙高对比' },
3331
+ ],
3332
+ onChange: (value) => edit('ui.graphGlowPreset', value),
3333
+ disabled,
3334
+ }),
3335
+ h(
3336
+ 'div',
3337
+ { style: { display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', margin: '6px 0 12px' } },
3338
+ h('div', { style: { ...labelStyle, marginBottom: 0, flex: '1 1 220px' } }, '自定义光色(ui.graphGlowCustom)'),
3339
+ h('input', {
3340
+ type: 'color',
3341
+ value: normalizeHex(ui.graphGlowCustom) || '#4f8cff',
3342
+ disabled,
3343
+ onChange: (evt) => edit('ui.graphGlowCustom', evt.target.value),
3344
+ style: { width: 44, height: 28, padding: 2, border: `1px solid ${palette.border}`, borderRadius: 8, background: 'transparent' },
3345
+ }),
3346
+ h(
3347
+ 'button',
3348
+ { type: 'button', style: smallButtonStyle, disabled, onClick: () => edit('ui.graphGlowCustom', '') },
3349
+ '恢复跟随预设',
3350
+ ),
3351
+ ),
3352
+ h(Select, {
3353
+ label: '画布底色(ui.graphCanvasTint)',
3354
+ hint: 'auto 给一层极淡底色提高对比;none 完全透明,跟随主题;tint 稍强。',
3355
+ value: ui.graphCanvasTint || 'auto',
3356
+ options: [
3357
+ { value: 'auto', label: 'auto — 极淡底色(默认)' },
3358
+ { value: 'tint', label: 'tint — 更明显的底色' },
3359
+ { value: 'none', label: 'none — 透明' },
3360
+ ],
3361
+ onChange: (value) => edit('ui.graphCanvasTint', value),
3362
+ disabled,
3363
+ }),
3364
+ ),
3365
+ h(
3366
+ Section,
3367
+ { title: '活动流', hint: '光效读取的是最近的 recall / capture 事件(不含敏感标签)。持久化只影响重启后能否回放,默认关闭。' },
3368
+ h(Toggle, {
3369
+ label: '活动流落盘(ui.graphActivityPersist)',
3370
+ hint: '默认关闭:活动只在内存里,重启即清空。打开后写入 state/activity.json,重启仍能看到最近的闪烁历史。',
3371
+ checked: Boolean(ui.graphActivityPersist),
3372
+ onChange: (value) => edit('ui.graphActivityPersist', value),
3373
+ disabled,
3374
+ }),
3375
+ ),
3376
+ ];
3377
+ }
3378
+
2931
3379
  const SETTINGS_GROUPS = [
2932
3380
  { id: 'identity', label: '身份与行为', hint: '人格锚点 · 空闲行为', visibleInSimple: true },
2933
3381
  { id: 'context', label: '上下文与注入', hint: '窗口记账 · 注入形态 · 运行模式 · 检索 · 调度', visibleInSimple: true },
2934
3382
  { id: 'ingest', label: '摄入与蒸馏', hint: '打标 · 工具裁剪 · 能力开关 · Dream / L2 合并 / L2.5', visibleInSimple: false },
2935
3383
  { id: 'retention', label: '留存与归档', hint: 'raw 冷热分层 · 标签树 · 老化 · 存储图谱 · 删除复习', visibleInSimple: true },
3384
+ { id: 'graph', label: '图谱与光效', hint: '节点上限 · recall 光效 · 预设色 · 画布底色 · 活动持久化', visibleInSimple: false },
2936
3385
  { id: 'space', label: '空间与存储', hint: '多空间路由 · 会话交接 · 数据目录迁移', visibleInSimple: true },
2937
3386
  ];
2938
3387
 
@@ -3994,6 +4443,7 @@
3994
4443
  index: { ...(prev.index || {}) },
3995
4444
  temp: { ...(prev.temp || {}) },
3996
4445
  tagTree: { ...(prev.tagTree || {}) },
4446
+ ui: { ...(prev.ui || {}) },
3997
4447
  // tools.disabled is an ARRAY: clone it so a cancelled edit cannot
3998
4448
  // mutate the previous draft's array in place.
3999
4449
  tools: {
@@ -4049,6 +4499,12 @@
4049
4499
  enableReflection: Boolean(draft.enableReflection),
4050
4500
  dreamIdleMinutes: Number(draft.dreamIdleMinutes),
4051
4501
  graphMaxEdges: Number(draft.graphMaxEdges),
4502
+ graphMaxNodes: Number(draft.graphMaxNodes),
4503
+ 'ui.graphGlowEnabled': Boolean((draft.ui || {}).graphGlowEnabled),
4504
+ 'ui.graphGlowPreset': (draft.ui || {}).graphGlowPreset || 'accent',
4505
+ 'ui.graphGlowCustom': normalizeHex((draft.ui || {}).graphGlowCustom),
4506
+ 'ui.graphCanvasTint': (draft.ui || {}).graphCanvasTint || 'auto',
4507
+ 'ui.graphActivityPersist': Boolean((draft.ui || {}).graphActivityPersist),
4052
4508
  storageBudgetMb: Number(draft.storageBudgetMb),
4053
4509
  'decay.halfLifeDays': Number(draft.decayHalfLifeDays),
4054
4510
  'activeSet.cap': Number(draft.activeSetCap),
@@ -4329,6 +4785,11 @@ h(
4329
4785
  { groupId: 'retention', label: '留存与归档', hint: 'raw 冷热分层 · 标签树 · 老化 · 存储图谱 · 删除复习', groupRefs },
4330
4786
  ...SettingsRetentionGroup(settingsBag),
4331
4787
  ),
4788
+ h(
4789
+ SettingsGroup,
4790
+ { groupId: 'graph', label: '图谱与光效', hint: '节点上限 · recall 光效 · 预设色 · 画布底色 · 活动持久化', groupRefs },
4791
+ ...SettingsGraphGroup(settingsBag),
4792
+ ),
4332
4793
  h(
4333
4794
  SettingsGroup,
4334
4795
  { groupId: 'space', label: '空间与存储', hint: '多空间路由 · 会话交接 · 数据目录迁移', groupRefs },
@@ -4385,6 +4846,9 @@ h(
4385
4846
  retryPolicy: decideRetry,
4386
4847
  // Pure geometry for the history view: testable without a DOM.
4387
4848
  ghostGraphParts,
4849
+ // v1.7.4 graph geometry: layout world, force model, overlap separation and
4850
+ // view fitting are pure functions, so the tests assert real numbers.
4851
+ graphGeometry: { computeLayout, separateOverlaps, layoutWorld, fitView, computeRadius, graphBounds, glowColors, mixHex },
4388
4852
  // v1.5.0 pure helpers. The panel/settings can only be exercised in a
4389
4853
  // browser, but these three carry every decision worth locking: the session
4390
4854
  // status line, query filtering (edge consistency) and soft space-follow.