Persistent project knowledge graph for coding agents. MCP server with semantic search, in-process embeddings, and web explorer.
TypeScript agentic-codingaiai-agentsclaude-codecode-contextcoding-agentembeddingsknowledge-graphllmmcpmcp-serveropencodepersistent-memorysqlitetypescript
feat: add timeline playback to web explorer
0xk3vin69d233406e07
diff --git a/package.json b/package.jsonindex aaf9062..0ea44fe 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "megamemory",- "version": "1.3.3",+ "version": "1.4.0","description": "MCP server that gives coding agents persistent project understanding via a knowledge graph","type": "module","main": "dist/index.js",diff --git a/src/index.ts b/src/index.tsindex 821727d..e289f71 100644--- a/src/index.ts+++ b/src/index.ts@@ -5,6 +5,7 @@ import { dirname, resolve } from "path";import { fileURLToPath } from "url";import pc from "picocolors";import { errorBold, validatePort } from "./cli-utils.js";+import { createTimelineLogger } from "./timeline.js";// ---- CLI routing ----@@ -165,6 +166,7 @@ async function startMcpServer() {path.join(process.cwd(), ".megamemory", "knowledge.db");const db = new KnowledgeDB(DB_PATH);+ const timeline = createTimelineLogger(db);const server = new McpServer({name: "megamemory",@@ -191,8 +193,24 @@ async function startMcpServer() {async (params) => {try {const result = await understand(db, { query: params.query, top_k: params.top_k });+ timeline.log({+ tool: "understand",+ params: { query: params.query, top_k: params.top_k },+ result_summary: `${result.matches.length} matches`,+ is_write: false,+ is_error: false,+ affected_ids: result.matches.map((match) => match.id),+ });return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };} catch (err) {+ timeline.log({+ tool: "understand",+ params: { query: params.query, top_k: params.top_k },+ result_summary: err instanceof Error ? err.message : String(err),+ is_write: false,+ is_error: true,+ affected_ids: [],+ });return formatError(err);}}@@ -227,8 +245,24 @@ async function startMcpServer() {edges: params.edges?.map((e) => ({ ...e, relation: e.relation as RelationType })),created_by_task: params.created_by_task,});+ timeline.log({+ tool: "create_concept",+ params: { name: params.name, kind: params.kind, parent_id: params.parent_id },+ result_summary: `created ${result.id}`,+ is_write: true,+ is_error: false,+ affected_ids: [result.id],+ });return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };} catch (err) {+ timeline.log({+ tool: "create_concept",+ params: { name: params.name, kind: params.kind, parent_id: params.parent_id },+ result_summary: err instanceof Error ? err.message : String(err),+ is_write: true,+ is_error: true,+ affected_ids: [],+ });return formatError(err);}}@@ -253,8 +287,24 @@ async function startMcpServer() {id: params.id,changes: { ...params.changes, kind: params.changes.kind as NodeKind | undefined },});+ timeline.log({+ tool: "update_concept",+ params: { id: params.id, changed_fields: Object.keys(params.changes) },+ result_summary: `updated ${params.id}`,+ is_write: true,+ is_error: false,+ affected_ids: [params.id],+ });return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };} catch (err) {+ timeline.log({+ tool: "update_concept",+ params: { id: params.id, changed_fields: Object.keys(params.changes) },+ result_summary: err instanceof Error ? err.message : String(err),+ is_write: true,+ is_error: true,+ affected_ids: [],+ });return formatError(err);}}@@ -276,8 +326,24 @@ async function startMcpServer() {relation: params.relation as RelationType,description: params.description,});+ timeline.log({+ tool: "link",+ params: { from: params.from, to: params.to, relation: params.relation },+ result_summary: `linked ${params.from} -> ${params.to}`,+ is_write: true,+ is_error: false,+ affected_ids: [params.from, params.to],+ });return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };} catch (err) {+ timeline.log({+ tool: "link",+ params: { from: params.from, to: params.to, relation: params.relation },+ result_summary: err instanceof Error ? err.message : String(err),+ is_write: true,+ is_error: true,+ affected_ids: [],+ });return formatError(err);}}@@ -293,8 +359,24 @@ async function startMcpServer() {async (params) => {try {const result = removeConcept(db, { id: params.id, reason: params.reason });+ timeline.log({+ tool: "remove_concept",+ params: { id: params.id },+ result_summary: `removed ${params.id}`,+ is_write: true,+ is_error: false,+ affected_ids: [params.id],+ });return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };} catch (err) {+ timeline.log({+ tool: "remove_concept",+ params: { id: params.id },+ result_summary: err instanceof Error ? err.message : String(err),+ is_write: true,+ is_error: true,+ affected_ids: [],+ });return formatError(err);}}@@ -307,8 +389,24 @@ async function startMcpServer() {async () => {try {const result = listRoots(db);+ timeline.log({+ tool: "list_roots",+ params: {},+ result_summary: `${result.roots.length} roots`,+ is_write: false,+ is_error: false,+ affected_ids: [],+ });return { content: [{ type: "text" as const, text: JSON.stringify({ ...result, stats: db.getStats() }, null, 2) }] };} catch (err) {+ timeline.log({+ tool: "list_roots",+ params: {},+ result_summary: err instanceof Error ? err.message : String(err),+ is_write: false,+ is_error: true,+ affected_ids: [],+ });return formatError(err);}}@@ -321,8 +419,24 @@ async function startMcpServer() {async () => {try {const result = listConflicts(db);+ timeline.log({+ tool: "list_conflicts",+ params: {},+ result_summary: `${result.conflicts.length} conflict groups`,+ is_write: false,+ is_error: false,+ affected_ids: [],+ });return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };} catch (err) {+ timeline.log({+ tool: "list_conflicts",+ params: {},+ result_summary: err instanceof Error ? err.message : String(err),+ is_write: false,+ is_error: true,+ affected_ids: [],+ });return formatError(err);}}@@ -347,8 +461,24 @@ async function startMcpServer() {resolved: params.resolved,reason: params.reason,});+ timeline.log({+ tool: "resolve_conflict",+ params: { merge_group: params.merge_group },+ result_summary: `resolved ${params.merge_group}`,+ is_write: true,+ is_error: false,+ affected_ids: [],+ });return { content: [{ type: "text" as const, text: JSON.stringify(result, null, 2) }] };} catch (err) {+ timeline.log({+ tool: "resolve_conflict",+ params: { merge_group: params.merge_group },+ result_summary: err instanceof Error ? err.message : String(err),+ is_write: true,+ is_error: true,+ affected_ids: [],+ });return formatError(err);}}diff --git a/src/web.ts b/src/web.tsindex 2ea2175..52c3fd6 100644--- a/src/web.ts+++ b/src/web.ts@@ -171,6 +171,217 @@ export async function runServe(port: number): Promise<void> {return { nodes, edges };}+ function parseBooleanParam(value: string | null): boolean {+ return value === "true" || value === "1";+ }++ function clampInt(value: string | null, defaultValue: number, min: number, max: number): number {+ const parsed = Number.parseInt(value ?? "", 10);+ if (!Number.isFinite(parsed)) return defaultValue;+ return Math.min(max, Math.max(min, parsed));+ }++ function safeJsonParse(raw: string): unknown {+ try {+ return JSON.parse(raw);+ } catch {+ return raw;+ }+ }++ type TimelineEntryView = {+ seq: number;+ timestamp: string;+ tool: string;+ params?: unknown;+ result_summary: string;+ is_write: boolean;+ is_error: boolean;+ affected_ids: string[];+ };++ type TimelineQueryOptions = {+ writesOnly?: boolean;+ tool?: string;+ since?: string;+ until?: string;+ limit?: number;+ };++ function parseAffectedIds(raw: string): string[] {+ const parsed = safeJsonParse(raw);+ if (!Array.isArray(parsed)) return [];+ return parsed.filter((value): value is string => typeof value === "string");+ }++ function buildNodeTimestampEntries(): TimelineEntryView[] {+ const staged: Array<{+ timestamp: string;+ tool: string;+ params?: unknown;+ result_summary: string;+ is_write: boolean;+ is_error: boolean;+ affected_ids: string[];+ order: number;+ }> = [];++ const nodes = db.getAllNodesRaw();+ for (const node of nodes) {+ if (node.created_at) {+ staged.push({+ timestamp: node.created_at,+ tool: "create_concept",+ params: { id: node.id, kind: node.kind, parent_id: node.parent_id },+ result_summary: `created ${node.id}`,+ is_write: true,+ is_error: false,+ affected_ids: [node.id],+ order: 0,+ });+ }++ if (node.updated_at && node.updated_at !== node.created_at) {+ staged.push({+ timestamp: node.updated_at,+ tool: "update_concept",+ params: { id: node.id },+ result_summary: `updated ${node.id}`,+ is_write: true,+ is_error: false,+ affected_ids: [node.id],+ order: 1,+ });+ }++ if (node.removed_at) {+ staged.push({+ timestamp: node.removed_at,+ tool: "remove_concept",+ params: { id: node.id },+ result_summary: `removed ${node.id}`,+ is_write: true,+ is_error: false,+ affected_ids: [node.id],+ order: 2,+ });+ }+ }++ staged.sort((a, b) => {+ const timestampCmp = a.timestamp.localeCompare(b.timestamp);+ if (timestampCmp !== 0) return timestampCmp;+ const orderCmp = a.order - b.order;+ if (orderCmp !== 0) return orderCmp;+ return (a.affected_ids[0] ?? "").localeCompare(b.affected_ids[0] ?? "");+ });++ return staged.map((entry, index) => ({+ seq: index + 1,+ timestamp: entry.timestamp,+ tool: entry.tool,+ params: entry.params,+ result_summary: entry.result_summary,+ is_write: entry.is_write,+ is_error: entry.is_error,+ affected_ids: entry.affected_ids,+ }));+ }++ function buildMergedTimelineEntries(options: TimelineQueryOptions = {}): {+ entries: TimelineEntryView[];+ source: "merged" | "timeline" | "node_timestamps";+ } {+ const syntheticEntries = buildNodeTimestampEntries()+ .filter((entry) => !options.tool || entry.tool === options.tool)+ .filter((entry) => !options.since || entry.timestamp >= options.since)+ .filter((entry) => !options.until || entry.timestamp <= options.until);++ const bounds = db.getTimelineBounds();+ const realEntries = bounds.count > 0+ ? db.getTimelineEntries({+ writesOnly: options.writesOnly,+ tool: options.tool,+ since: options.since,+ until: options.until,+ }).map((row) => ({+ seq: row.seq,+ timestamp: row.timestamp,+ tool: row.tool,+ params: safeJsonParse(row.params),+ result_summary: row.result_summary,+ is_write: row.is_write === 1,+ is_error: row.is_error === 1,+ affected_ids: parseAffectedIds(row.affected_ids),+ }))+ : [];++ const realCreateIds = new Set<string>();+ const realUpdateIds = new Set<string>();+ const realRemoveIds = new Set<string>();+ for (const entry of realEntries) {+ if (entry.tool === "create_concept") {+ for (const id of entry.affected_ids) realCreateIds.add(id);+ } else if (entry.tool === "update_concept") {+ for (const id of entry.affected_ids) realUpdateIds.add(id);+ } else if (entry.tool === "remove_concept") {+ for (const id of entry.affected_ids) realRemoveIds.add(id);+ }+ }++ const dedupedSyntheticEntries = syntheticEntries+ .filter((entry) => !options.writesOnly || entry.is_write)+ .filter((entry) => {+ const id = entry.affected_ids[0];+ if (!id) return true;+ if (entry.tool === "create_concept") return !realCreateIds.has(id);+ if (entry.tool === "update_concept") return !realUpdateIds.has(id);+ if (entry.tool === "remove_concept") return !realRemoveIds.has(id);+ return true;+ });++ const merged = [...realEntries, ...dedupedSyntheticEntries]+ .map((entry, idx) => ({ entry, idx }))+ .sort((a, b) => {+ const timestampCmp = a.entry.timestamp.localeCompare(b.entry.timestamp);+ if (timestampCmp !== 0) return timestampCmp;+ return a.idx - b.idx;+ })+ .map(({ entry }, idx) => ({+ ...entry,+ seq: idx + 1,+ }));++ const limited = typeof options.limit === "number" ? merged.slice(0, options.limit) : merged;++ const source = realEntries.length > 0 && dedupedSyntheticEntries.length > 0+ ? "merged"+ : realEntries.length > 0+ ? "timeline"+ : "node_timestamps";++ return { entries: limited, source };+ }++ function sampleEntries<T>(entries: T[], n: number): T[] {+ if (entries.length <= n) return entries;+ if (n <= 1) return [entries[0]];++ const sampled: T[] = [];+ const maxIndex = entries.length - 1;+ const step = maxIndex / (n - 1);+ const seen = new Set<number>();++ for (let i = 0; i < n; i += 1) {+ const index = i === n - 1 ? maxIndex : Math.round(i * step);+ if (seen.has(index)) continue;+ seen.add(index);+ sampled.push(entries[index]);+ }++ return sampled;+ }+function initializeSseSnapshot(): void {const nodes = db.getAllActiveNodes();const edges = db.getAllEdges();@@ -441,6 +652,89 @@ export async function runServe(port: number): Promise<void> {return;}+ if (pathname === "/api/timeline/bounds" && req.method === "GET") {+ const merged = buildMergedTimelineEntries();+ if (merged.entries.length > 0) {+ json(res, {+ first: merged.entries[0].timestamp,+ last: merged.entries[merged.entries.length - 1].timestamp,+ count: merged.entries.length,+ source: merged.source,+ });+ return;+ }++ json(res, { first: null, last: null, count: 0, source: "none" as const });+ return;+ }++ if (pathname === "/api/timeline/ticks" && req.method === "GET") {+ const n = clampInt(url.searchParams.get("n"), 100, 1, 500);+ const merged = buildMergedTimelineEntries();+ const ticks = sampleEntries(merged.entries, n).map((row) => ({+ seq: row.seq,+ timestamp: row.timestamp,+ tool: row.tool,+ result_summary: row.result_summary,+ }));+ json(res, { ticks, source: merged.source });+ return;+ }++ if (pathname === "/api/timeline" && req.method === "GET") {+ const writesOnly = parseBooleanParam(url.searchParams.get("writes_only"));+ const tool = (url.searchParams.get("tool") ?? "").trim();+ const since = (url.searchParams.get("since") ?? "").trim();+ const until = (url.searchParams.get("until") ?? "").trim();+ const limit = clampInt(url.searchParams.get("limit"), 1000, 1, 50000);+ const { entries, source } = buildMergedTimelineEntries({+ writesOnly,+ tool: tool || undefined,+ since: since || undefined,+ until: until || undefined,+ limit,+ });++ json(res, { entries, source });+ return;+ }++ if (pathname === "/api/graph/at" && req.method === "GET") {+ const t = (url.searchParams.get("t") ?? "").trim();+ if (!t) {+ json(res, { error: "Missing required query parameter: t" }, 400);+ return;+ }++ const nodes = db.getNodesAtTime(t).map((n) => ({+ id: n.id,+ name: n.name,+ kind: n.kind,+ summary: n.summary,+ parent_id: n.parent_id,+ edge_count: 0,+ }));++ const edges = db.getEdgesAtTime(t).map((e) => ({+ from: e.from_id,+ to: e.to_id,+ relation: e.relation,+ description: e.description,+ }));++ const edgeCounts = new Map<string, number>();+ for (const edge of edges) {+ edgeCounts.set(edge.from, (edgeCounts.get(edge.from) ?? 0) + 1);+ edgeCounts.set(edge.to, (edgeCounts.get(edge.to) ?? 0) + 1);+ }+ for (const node of nodes) {+ node.edge_count = edgeCounts.get(node.id) ?? 0;+ }++ json(res, { nodes, edges });+ return;+ }+notFound(res);})().catch((err: unknown) => {const message = err instanceof Error ? err.message : String(err);diff --git a/web/index.html b/web/index.htmlindex 15fed84..9790134 100644--- a/web/index.html+++ b/web/index.html@@ -383,6 +383,83 @@#empty-state.visible { display: block; }#empty-state h2 { font-size: 20px; font-weight: 600; margin-bottom: 8px; color: var(--text-dim); }#empty-state p { font-size: 13px; }++ /* ---- Timeline bar ---- */+ #timeline-bar {+ display: none;+ align-items: center;+ gap: 8px;+ padding: 6px 16px;+ background: var(--surface);+ border-top: 1px solid var(--border);+ z-index: 10;+ }+ #timeline-bar.active { display: flex; }++ #timeline-toggle {+ padding: 3px 10px;+ background: var(--surface2);+ border: 1px solid var(--border);+ border-radius: 4px;+ color: var(--text-dim);+ font-family: inherit;+ font-size: 11px;+ cursor: pointer;+ white-space: nowrap;+ }+ #timeline-toggle:hover { border-color: var(--accent); color: var(--text); }+ #timeline-toggle.live { background: #22c55e22; color: #22c55e; border-color: #22c55e44; }++ #timeline-slider {+ flex: 1;+ height: 4px;+ accent-color: var(--accent);+ cursor: pointer;+ }++ #timeline-display {+ font-size: 11px;+ color: var(--text-dim);+ white-space: nowrap;+ width: 340px;+ flex-shrink: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ }++ #timeline-controls { display: flex; align-items: center; gap: 6px; }++ #timeline-play {+ padding: 2px 8px;+ background: var(--surface2);+ border: 1px solid var(--border);+ border-radius: 4px;+ color: var(--text-dim);+ font-family: inherit;+ font-size: 12px;+ cursor: pointer;+ }+ #timeline-play:hover { border-color: var(--accent); color: var(--text); }++ #timeline-speed {+ background: var(--bg);+ border: 1px solid var(--border);+ border-radius: 4px;+ color: var(--text-dim);+ font-family: inherit;+ font-size: 11px;+ padding: 2px 4px;+ }++ #timeline-summary {+ font-size: 10px;+ color: var(--text-muted, var(--text-dim));+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ width: 300px;+ flex-shrink: 0;+ }</style></head><body>@@ -409,6 +486,22 @@</aside></main>+<div id="timeline-bar">+ <button id="timeline-toggle" class="live" title="Switch between Live and Timeline mode">● Live</button>+ <div id="timeline-controls" style="display:none">+ <button id="timeline-play" title="Play/Pause">▶</button>+ <select id="timeline-speed" title="Playback speed">+ <option value="100">Fast</option>+ <option value="250" selected>Normal</option>+ <option value="500">Slow</option>+ <option value="1000">Slower</option>+ </select>+ </div>+ <input id="timeline-slider" type="range" min="0" max="1" value="1" step="1" style="display:none" />+ <span id="timeline-display"></span>+ <span id="timeline-summary"></span>+</div>+<footer id="stats"></footer><script>@@ -451,6 +544,12 @@ let activeSearchIndex = -1;let searchRequestId = 0;let evtSource = null;let sseConnected = false;+let timelineMode = false;+let timelineSteps = [];+let timelineSource = 'none';+let timelineFetchId = 0;+let timelinePlayInterval = null;+let timelinePlaying = false;// ---- API ----@@ -463,6 +562,15 @@ async function fetchSemanticSearch(query, topK) {const data = await response.json();return { ok: response.ok, status: response.status, data };}+async function fetchTimelineBounds() {+ return (await fetch('/api/timeline/bounds')).json();+}+async function fetchTimelineSteps() {+ return (await fetch('/api/timeline?writes_only=true&limit=50000')).json();+}+async function fetchGraphAt(timestamp) {+ return (await fetch('/api/graph/at?t=' + encodeURIComponent(timestamp))).json();+}function setEmptyStateVisible(visible) {const el = document.getElementById('empty-state');@@ -495,6 +603,7 @@ function connectSSE() {}function handleSSE(msg) {+ if (timelineMode) return;if (!msg || !msg.type) return;switch (msg.type) {case 'init':@@ -801,10 +910,10 @@ function buildGraphData(data) {function initSimulation() {simulation = d3.forceSimulation([])- .force('charge', d3.forceManyBody().strength(d => d._hasChildren ? -300 : -180).distanceMin(15).distanceMax(500))- .force('center', d3.forceCenter(width / 2, height / 2).strength(0.04))- .force('collision', d3.forceCollide().radius(d => d.radius + 12).strength(0.6).iterations(2))- .force('link', d3.forceLink([]).id(d => d.id).distance(d => d.isParentEdge ? 90 : 200).strength(d => d.isParentEdge ? 0.4 : 0.15))+ .force('charge', d3.forceManyBody().strength(d => d._hasChildren ? -500 : -300).distanceMin(20).distanceMax(800))+ .force('center', d3.forceCenter(width / 2, height / 2).strength(0.02))+ .force('collision', d3.forceCollide().radius(d => d.radius + 35).strength(0.7).iterations(3))+ .force('link', d3.forceLink([]).id(d => d.id).distance(d => d.isParentEdge ? 120 : 260).strength(d => d.isParentEdge ? 0.35 : 0.12)).alphaDecay(0.015).velocityDecay(0.35).on('tick', () => {});@@ -946,7 +1055,7 @@ function drawEdges(now) {const cx = (sx + tx) * 0.5 + nx * curve;const cy = (sy + ty) * 0.5 + ny * curve;- const dimAlpha = edge.dimmed ? 0.08 : 0.65;+ const dimAlpha = edge.dimmed ? 0.08 : 0.45;const age = now - edge.birthTime;const progress = Math.max(0, Math.min(1, age / 350));const pulse = computePulse(edge.pulseTime, now);@@ -1002,7 +1111,7 @@ function drawEdges(now) {ctx.restore();}- if (!edge.isParentEdge && edge.relation && progress > 0.65) {+ if (!edge.isParentEdge && edge.relation && progress > 0.65 && zoom > 1.5) {const screenDistance = len * zoom;if (screenDistance <= 120) continue;const t = 0.5;@@ -1711,6 +1820,280 @@ function hexToRgba(hex, alpha) {return `rgba(${r},${g},${b},${alpha})`;}+// ---- Timeline ----++function stopTimelinePlayback() {+ if (timelinePlayInterval) {+ clearInterval(timelinePlayInterval);+ timelinePlayInterval = null;+ }+ timelinePlaying = false;+ const playBtn = document.getElementById('timeline-play');+ if (playBtn) playBtn.textContent = '▶';+}++function updateTimelineDisplay(stepIndex) {+ const display = document.getElementById('timeline-display');+ const summary = document.getElementById('timeline-summary');+ if (!display || !summary) return;++ if (stepIndex >= timelineSteps.length) {+ display.textContent = '● Live';+ summary.textContent = '';+ return;+ }++ const step = timelineSteps[stepIndex];+ display.textContent = `Step ${stepIndex + 1}/${timelineSteps.length} · ${step.tool} · ${step.timestamp}`;+ summary.textContent = step.result_summary || '';+}++async function scrubToStep(stepIndex) {+ if (!timelineMode) return;++ updateTimelineDisplay(stepIndex);+ const requestId = ++timelineFetchId;+ const prevPositions = new Map(nodes.map(node => [node.id, { x: node.x, y: node.y, vx: node.vx || 0, vy: node.vy || 0, birthTime: node.birthTime }]));+ const prevIds = new Set(nodes.map(node => node.id));+ const prevEdgeBirthTimes = new Map(+ edges.map(edge => {+ const sid = typeof edge.source === 'object' ? edge.source.id : edge.source;+ const tid = typeof edge.target === 'object' ? edge.target.id : edge.target;+ return [`${sid}|${tid}|${edge.relation}`, edge.birthTime];+ })+ );++ let data;+ if (stepIndex >= timelineSteps.length) {+ data = await fetchGraph();+ } else {+ data = await fetchGraphAt(timelineSteps[stepIndex].timestamp);+ }++ if (!timelineMode || requestId !== timelineFetchId) return;++ buildGraphData(data);+ const now = performance.now();+ for (const node of nodes) {+ const prev = prevPositions.get(node.id);+ if (prev) {+ node.x = prev.x;+ node.y = prev.y;+ node.vx = prev.vx;+ node.vy = prev.vy;+ node.birthTime = prev.birthTime;+ node.pulseTime = null;+ } else if (!prevIds.has(node.id)) {+ node.birthTime = now;+ }+ }+ for (const edge of edges) {+ const sid = typeof edge.source === 'object' ? edge.source.id : edge.source;+ const tid = typeof edge.target === 'object' ? edge.target.id : edge.target;+ const key = `${sid}|${tid}|${edge.relation}`;+ const prevBirth = prevEdgeBirthTimes.get(key);+ if (prevBirth !== undefined) {+ edge.birthTime = prevBirth;+ } else {+ edge.birthTime = now;+ }+ }++ refreshSimulation(0.15);+ setEmptyStateVisible(nodes.length === 0);+}++function startTimelinePlayback() {+ if (!timelineMode || timelineSteps.length === 0 || timelinePlaying) return;++ const slider = document.getElementById('timeline-slider');+ const speedSelect = document.getElementById('timeline-speed');+ const playBtn = document.getElementById('timeline-play');+ if (!slider || !speedSelect || !playBtn) return;++ const current = Number(slider.value);+ if (current >= timelineSteps.length) return;++ timelinePlaying = true;+ playBtn.textContent = '⏸';++ const speed = Number(speedSelect.value) || 250;+ timelinePlayInterval = setInterval(() => {+ if (!timelineMode) {+ stopTimelinePlayback();+ return;+ }+ const next = Number(slider.value) + 1;+ slider.value = String(next);+ void scrubToStep(next);+ if (next >= timelineSteps.length) {+ stopTimelinePlayback();+ }+ }, speed);+}++async function enterTimelineMode() {+ if (timelineMode) return;+ timelineMode = true;+ stopTimelinePlayback();++ const toggle = document.getElementById('timeline-toggle');+ const controls = document.getElementById('timeline-controls');+ const slider = document.getElementById('timeline-slider');+ if (!toggle || !controls || !slider) {+ timelineMode = false;+ return;+ }++ const payload = await fetchTimelineSteps();+ const steps = Array.isArray(payload.entries) ? payload.entries : [];+ if (steps.length === 0) {+ timelineMode = false;+ alert('No timeline entries available yet.');+ return;+ }++ timelineSteps = steps;+ timelineSource = payload.source || 'none';++ slider.min = '0';+ slider.max = String(steps.length);+ slider.value = String(steps.length);+ slider.style.display = '';+ controls.style.display = 'flex';++ toggle.classList.remove('live');+ toggle.textContent = '◷ Timeline';+ toggle.title = `Timeline source: ${timelineSource}`;++ if (evtSource) {+ evtSource.close();+ evtSource = null;+ sseConnected = false;+ }++ updateTimelineDisplay(steps.length);+}++async function exitTimelineMode() {+ if (!timelineMode) return;+ timelineMode = false;+ timelineFetchId += 1;+ stopTimelinePlayback();++ const toggle = document.getElementById('timeline-toggle');+ const controls = document.getElementById('timeline-controls');+ const slider = document.getElementById('timeline-slider');+ const display = document.getElementById('timeline-display');+ const summary = document.getElementById('timeline-summary');++ if (controls) controls.style.display = 'none';+ if (slider) {+ slider.style.display = 'none';+ slider.value = '1';+ slider.min = '0';+ slider.max = '1';+ }+ if (toggle) {+ toggle.classList.add('live');+ toggle.textContent = '● Live';+ toggle.title = 'Switch between Live and Timeline mode';+ }+ if (display) display.textContent = '';+ if (summary) summary.textContent = '';++ timelineSteps = [];+ timelineSource = 'none';++ const prevPositions = new Map(nodes.map(node => [node.id, { x: node.x, y: node.y, vx: node.vx || 0, vy: node.vy || 0, birthTime: node.birthTime }]));+ const prevEdgeBirthTimes = new Map(+ edges.map(edge => {+ const sid = typeof edge.source === 'object' ? edge.source.id : edge.source;+ const tid = typeof edge.target === 'object' ? edge.target.id : edge.target;+ return [`${sid}|${tid}|${edge.relation}`, edge.birthTime];+ })+ );+ const [graphData, stats] = await Promise.all([fetchGraph(), fetchStats()]);+ buildGraphData(graphData);+ const now = performance.now();+ for (const node of nodes) {+ const prev = prevPositions.get(node.id);+ if (!prev) continue;+ node.x = prev.x;+ node.y = prev.y;+ node.vx = prev.vx;+ node.vy = prev.vy;+ node.birthTime = prev.birthTime;+ node.pulseTime = null;+ }+ for (const edge of edges) {+ const sid = typeof edge.source === 'object' ? edge.source.id : edge.source;+ const tid = typeof edge.target === 'object' ? edge.target.id : edge.target;+ const key = `${sid}|${tid}|${edge.relation}`;+ const prevBirth = prevEdgeBirthTimes.get(key);+ if (prevBirth !== undefined) {+ edge.birthTime = prevBirth;+ } else {+ edge.birthTime = now;+ }+ }++ refreshSimulation(0.15);+ setEmptyStateVisible(graphData.nodes.length === 0);+ renderStats(stats);+ connectSSE();+}++function setupTimeline() {+ const bar = document.getElementById('timeline-bar');+ const toggle = document.getElementById('timeline-toggle');+ const slider = document.getElementById('timeline-slider');+ const play = document.getElementById('timeline-play');+ const speed = document.getElementById('timeline-speed');+ const display = document.getElementById('timeline-display');+ if (!bar || !toggle || !slider || !play || !speed) return;++ bar.classList.add('active');++ void fetchTimelineBounds().then((bounds) => {+ if (!display) return;+ if (!bounds || !bounds.count) {+ display.textContent = '● Live';+ return;+ }+ display.textContent = `● Live · ${bounds.count} events`;+ }).catch(() => {+ if (display) display.textContent = '● Live';+ });++ toggle.addEventListener('click', () => {+ if (timelineMode) {+ void exitTimelineMode();+ return;+ }+ void enterTimelineMode();+ });++ slider.addEventListener('input', () => {+ stopTimelinePlayback();+ void scrubToStep(Number(slider.value));+ });++ play.addEventListener('click', () => {+ if (timelinePlaying) {+ stopTimelinePlayback();+ return;+ }+ startTimelinePlayback();+ });++ speed.addEventListener('change', () => {+ if (!timelinePlaying) return;+ stopTimelinePlayback();+ startTimelinePlayback();+ });+}+// ---- Init ----async function init() {@@ -1720,7 +2103,7 @@ async function init() {window.addEventListener('resize', () => {setupCanvas();if (simulation) {- simulation.force('center', d3.forceCenter(width / 2, height / 2).strength(0.04));+ simulation.force('center', d3.forceCenter(width / 2, height / 2).strength(0.02));simulation.alpha(Math.max(simulation.alpha(), 0.3)).restart();}});@@ -1741,6 +2124,7 @@ async function init() {setupSearch();connectSSE();+ setupTimeline();}init();