Skip to content

#1 Persistent memory for AI coding agents based on real-world benchmarks

feat: session replay tab + JSONL transcript import

Rohit Ghumare11bef18927ab
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e235fa47..b91dc9bc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,18 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
## [Unreleased]
+## [0.8.13] — 2026-04-17
+
+### Added
+
+- Session replay: new "Replay" tab in the viewer that plays any stored session as a scrubbable timeline with prompt, response, tool-call, and tool-result events. Keyboard bindings: space to play/pause, arrow keys to step, speed selector (0.5×–4×).
+- JSONL transcript import via `agentmemory import-jsonl [path]` CLI subcommand and `POST /agentmemory/replay/import-jsonl`. Default path `~/.claude/projects`, or pass an explicit file/directory. Imports are recorded in the audit log.
+- New iii functions `mem::replay::load`, `mem::replay::sessions`, and `mem::replay::import-jsonl`, each routed through the same HMAC-authed API trigger as other endpoints.
+
+### Security
+
+- JSONL import rejects symlinks, paths containing sensitive terms (`secret`, `credential`, `.env`, etc.), and skips malformed lines without aborting the batch.
+
## [0.8.12] — 2026-04-16
### Added
diff --git a/README.md b/README.md
index d72ee92e..820d20f8 100644
--- a/README.md
+++ b/README.md
@@ -302,6 +302,22 @@ npx @agentmemory/agentmemory demo
Open `http://localhost:3113` to watch the memory build live.
+### Session Replay
+
+Every session agentmemory records is replayable. Open the viewer, pick the **Replay** tab, and scrub through the timeline: prompts, tool calls, tool results, and responses render as discrete events with play/pause, speed control (0.5×–4×), and keyboard shortcuts (space to toggle, arrows to step).
+
+Already have older Claude Code JSONL transcripts you want to bring in?
+
+```bash
+# Import everything under the default ~/.claude/projects
+npx @agentmemory/agentmemory import-jsonl
+
+# Or import a single file
+npx @agentmemory/agentmemory import-jsonl ~/.claude/projects/-my-project/abc123.jsonl
+```
+
+Imported sessions show up in the Replay picker alongside native ones. Under the hood each entry routes through the `mem::replay::load`, `mem::replay::sessions`, and `mem::replay::import-jsonl` iii functions — no side-channel servers.
+
### Upgrade / Maintenance
Use the maintenance command when you intentionally want to update your local runtime:
diff --git a/package.json b/package.json
index 485278c6..aa0f21d6 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "@agentmemory/agentmemory",
- "version": "0.8.12",
+ "version": "0.8.13",
"description": "Persistent memory for AI coding agents, powered by iii-engine's three primitives",
"type": "module",
"main": "dist/index.mjs",
diff --git a/packages/mcp/package.json b/packages/mcp/package.json
index 7aac3b83..6c2f8008 100644
--- a/packages/mcp/package.json
+++ b/packages/mcp/package.json
@@ -1,6 +1,6 @@
{
"name": "@agentmemory/mcp",
- "version": "0.8.12",
+ "version": "0.8.13",
"description": "Standalone MCP server for agentmemory — thin shim that re-exposes @agentmemory/agentmemory's MCP entrypoint",
"type": "module",
"bin": {
@@ -28,7 +28,7 @@
"homepage": "https://github.com/rohitg00/agentmemory#readme",
"bugs": "https://github.com/rohitg00/agentmemory/issues",
"dependencies": {
- "@agentmemory/agentmemory": "~0.8.12"
+ "@agentmemory/agentmemory": "~0.8.13"
},
"publishConfig": {
"access": "public",
diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json
index c2cbd9d4..27837d0e 100644
--- a/plugin/.claude-plugin/plugin.json
+++ b/plugin/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "agentmemory",
- "version": "0.8.12",
+ "version": "0.8.13",
"description": "Persistent memory for AI coding agents -- captures tool usage, compresses via LLM, injects context into future sessions. 12 hooks, 44 MCP tools, 4 skills, real-time viewer.",
"author": {
"name": "Rohit Ghumare",
diff --git a/src/cli.ts b/src/cli.ts
index 69f7c91a..9bd31593 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -34,6 +34,7 @@ Commands:
demo Seed sample sessions and show recall in action
upgrade Upgrade local deps + iii runtime (best effort)
mcp Start standalone MCP server (no engine required)
+ import-jsonl [p] Import Claude Code JSONL transcripts (default: ~/.claude/projects)
Options:
--help, -h Show this help
@@ -798,11 +799,69 @@ async function runMcp(): Promise<void> {
await import("./mcp/standalone.js");
}
+async function runImportJsonl(): Promise<void> {
+ const nonFlagArgs = args.slice(1).filter((a) => !a.startsWith("-"));
+ const pathArg = nonFlagArgs[0];
+ const port = getRestPort();
+ const base = `http://localhost:${port}`;
+
+ try {
+ await fetch(`${base}/agentmemory/livez`, {
+ signal: AbortSignal.timeout(2000),
+ });
+ } catch {
+ p.log.error(`agentmemory is not running on port ${port}. Start it first.`);
+ process.exit(1);
+ }
+
+ const body: Record<string, unknown> = {};
+ if (pathArg) body["path"] = pathArg;
+
+ const headers: Record<string, string> = { "content-type": "application/json" };
+ const secret = process.env["AGENTMEMORY_SECRET"];
+ if (secret) headers["authorization"] = `Bearer ${secret}`;
+
+ p.log.info(`Importing JSONL from ${pathArg || "~/.claude/projects"}…`);
+ const spinner = p.spinner();
+ spinner.start("scanning files");
+
+ try {
+ const res = await fetch(`${base}/agentmemory/replay/import-jsonl`, {
+ method: "POST",
+ headers,
+ body: JSON.stringify(body),
+ });
+ const json = (await res.json()) as {
+ success?: boolean;
+ error?: string;
+ imported?: number;
+ sessionIds?: string[];
+ observations?: number;
+ };
+ if (!res.ok || json.success === false) {
+ spinner.stop("failed");
+ p.log.error(json.error || `HTTP ${res.status}`);
+ process.exit(1);
+ }
+ spinner.stop(
+ `imported ${json.imported} file(s), ${json.observations} observation(s) across ${json.sessionIds?.length || 0} session(s)`,
+ );
+ if (json.sessionIds && json.sessionIds.length > 0) {
+ p.log.info(`View at http://localhost:${port + 2} → Replay tab`);
+ }
+ } catch (err) {
+ spinner.stop("failed");
+ p.log.error(err instanceof Error ? err.message : String(err));
+ process.exit(1);
+ }
+}
+
const commands: Record<string, () => Promise<void>> = {
status: runStatus,
demo: runDemo,
upgrade: runUpgrade,
mcp: runMcp,
+ "import-jsonl": runImportJsonl,
};
const handler = commands[args[0] ?? ""] ?? main;
diff --git a/src/functions/export-import.ts b/src/functions/export-import.ts
index e7824a8f..29258cdd 100644
--- a/src/functions/export-import.ts
+++ b/src/functions/export-import.ts
@@ -176,7 +176,7 @@ export function registerExportImportFunction(sdk: ISdk, kv: StateKV): void {
const strategy = data.strategy || "merge";
const importData = data.exportData;
- const supportedVersions = new Set(["0.3.0", "0.4.0", "0.5.0", "0.6.0", "0.6.1", "0.7.0", "0.7.2", "0.7.3", "0.7.4", "0.7.5", "0.7.6", "0.7.7", "0.7.9", "0.8.0", "0.8.1", "0.8.2", "0.8.3", "0.8.4", "0.8.5", "0.8.6", "0.8.7", "0.8.8", "0.8.9", "0.8.10", "0.8.11", "0.8.12"]);
+ const supportedVersions = new Set(["0.3.0", "0.4.0", "0.5.0", "0.6.0", "0.6.1", "0.7.0", "0.7.2", "0.7.3", "0.7.4", "0.7.5", "0.7.6", "0.7.7", "0.7.9", "0.8.0", "0.8.1", "0.8.2", "0.8.3", "0.8.4", "0.8.5", "0.8.6", "0.8.7", "0.8.8", "0.8.9", "0.8.10", "0.8.11", "0.8.12", "0.8.13"]);
if (!supportedVersions.has(importData.version)) {
return {
success: false,
diff --git a/src/functions/replay.ts b/src/functions/replay.ts
new file mode 100644
index 00000000..b575b4ad
--- /dev/null
+++ b/src/functions/replay.ts
@@ -0,0 +1,230 @@
+import { homedir } from "node:os";
+import { lstat, readFile, readdir } from "node:fs/promises";
+import { resolve, join, isAbsolute } from "node:path";
+import type { ISdk } from "iii-sdk";
+import type {
+ CompressedObservation,
+ RawObservation,
+ Session,
+} from "../types.js";
+import type { StateKV } from "../state/kv.js";
+import { KV, generateId } from "../state/schema.js";
+import { parseJsonlText } from "../replay/jsonl-parser.js";
+import { projectTimeline, type Timeline } from "../replay/timeline.js";
+import { safeAudit } from "./audit.js";
+import { logger } from "../logger.js";
+
+const SENSITIVE_PATH_TERMS = [
+ "secret",
+ "credential",
+ "private_key",
+ ".env",
+ "id_rsa",
+ "token",
+];
+
+function isSensitive(path: string): boolean {
+ const lower = path.toLowerCase();
+ return SENSITIVE_PATH_TERMS.some((t) => lower.includes(t));
+}
+
+async function isSymlink(path: string): Promise<boolean> {
+ try {
+ const st = await lstat(path);
+ return st.isSymbolicLink();
+ } catch {
+ return false;
+ }
+}
+
+function rawFromCompressed(obs: CompressedObservation): RawObservation {
+ return {
+ id: obs.id,
+ sessionId: obs.sessionId,
+ timestamp: obs.timestamp,
+ hookType: "post_tool_use",
+ toolName: undefined,
+ toolInput: undefined,
+ toolOutput: undefined,
+ userPrompt: obs.type === "conversation" ? obs.narrative : undefined,
+ assistantResponse: undefined,
+ raw: { title: obs.title, narrative: obs.narrative, facts: obs.facts },
+ };
+}
+
+function isRawShape(o: unknown): o is RawObservation {
+ if (!o || typeof o !== "object") return false;
+ const r = o as Record<string, unknown>;
+ return typeof r.hookType === "string";
+}
+
+async function loadObservations(
+ kv: StateKV,
+ sessionId: string,
+): Promise<RawObservation[]> {
+ const rows = await kv.list<RawObservation | CompressedObservation>(
+ KV.observations(sessionId),
+ );
+ return rows.map((r) => (isRawShape(r) ? r : rawFromCompressed(r as CompressedObservation)));
+}
+
+async function findJsonlFiles(root: string, limit = 200): Promise<string[]> {
+ const out: string[] = [];
+ async function walk(dir: string) {
+ if (out.length >= limit) return;
+ let names: string[];
+ try {
+ names = await readdir(dir);
+ } catch {
+ return;
+ }
+ for (const name of names) {
+ if (out.length >= limit) return;
+ const full = join(dir, name);
+ let st;
+ try {
+ st = await lstat(full);
+ } catch {
+ continue;
+ }
+ if (st.isSymbolicLink()) continue;
+ if (st.isDirectory()) {
+ await walk(full);
+ } else if (st.isFile() && name.endsWith(".jsonl")) {
+ out.push(full);
+ }
+ }
+ }
+ await walk(root);
+ return out;
+}
+
+export function registerReplayFunctions(sdk: ISdk, kv: StateKV): void {
+ sdk.registerFunction(
+ "mem::replay::load",
+ async (data: { sessionId: string }): Promise<
+ | { success: true; timeline: Timeline; session: Session | null }
+ | { success: false; error: string }
+ > => {
+ if (!data?.sessionId || typeof data.sessionId !== "string") {
+ return { success: false, error: "sessionId is required" };
+ }
+ const session = await kv.get<Session>(KV.sessions, data.sessionId);
+ const observations = await loadObservations(kv, data.sessionId);
+ const timeline = projectTimeline(observations);
+ return { success: true, timeline, session };
+ },
+ );
+
+ sdk.registerFunction(
+ "mem::replay::sessions",
+ async (): Promise<{ success: true; sessions: Session[] }> => {
+ const sessions = await kv.list<Session>(KV.sessions);
+ sessions.sort((a, b) => (b.startedAt || "").localeCompare(a.startedAt || ""));
+ return { success: true, sessions };
+ },
+ );
+
+ sdk.registerFunction(
+ "mem::replay::import-jsonl",
+ async (
+ data: { path?: string; maxFiles?: number } = {},
+ ): Promise<
+ | {
+ success: true;
+ imported: number;
+ sessionIds: string[];
+ observations: number;
+ }
+ | { success: false; error: string }
+ > => {
+ const defaultRoot = join(homedir(), ".claude", "projects");
+ const rawPath = data.path || defaultRoot;
+ if (typeof rawPath !== "string" || rawPath.length === 0) {
+ return { success: false, error: "path must be a non-empty string" };
+ }
+ const abs = isAbsolute(rawPath) ? resolve(rawPath) : resolve(rawPath);
+ if (isSensitive(abs)) {
+ return { success: false, error: "refusing to process sensitive-looking path" };
+ }
+ if (await isSymlink(abs)) {
+ return { success: false, error: "symlinks are not supported" };
+ }
+
+ let stat;
+ try {
+ stat = await lstat(abs);
+ } catch {
+ return { success: false, error: "path not found" };
+ }
+
+ let files: string[] = [];
+ if (stat.isDirectory()) {
+ files = await findJsonlFiles(abs, data.maxFiles || 200);
+ } else if (stat.isFile() && abs.endsWith(".jsonl")) {
+ files = [abs];
+ } else {
+ return { success: false, error: "path must be a .jsonl file or directory" };
+ }
+
+ if (files.length === 0) {
+ return { success: true, imported: 0, sessionIds: [], observations: 0 };
+ }
+
+ const sessionIds: string[] = [];
+ let observationCount = 0;
+
+ for (const file of files) {
+ if (await isSymlink(file)) continue;
+ let text: string;
+ try {
+ text = await readFile(file, "utf-8");
+ } catch (err) {
+ logger.warn("replay: failed to read jsonl", {
+ file,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ continue;
+ }
+
+ const parsed = parseJsonlText(text, generateId("sess"));
+ if (parsed.observations.length === 0) continue;
+
+ const existing = await kv.get<Session>(KV.sessions, parsed.sessionId);
+ if (!existing) {
+ const session: Session = {
+ id: parsed.sessionId,
+ project: parsed.project,
+ cwd: parsed.cwd,
+ startedAt: parsed.startedAt,
+ endedAt: parsed.endedAt,
+ status: "completed",
+ observationCount: parsed.observations.length,
+ tags: ["jsonl-import"],
+ };
+ await kv.set(KV.sessions, session.id, session);
+ }
+
+ for (const obs of parsed.observations) {
+ await kv.set(KV.observations(parsed.sessionId), obs.id, obs);
+ observationCount++;
+ }
+ sessionIds.push(parsed.sessionId);
+ }
+
+ await safeAudit(kv, "import", "mem::replay::import-jsonl", sessionIds, {
+ source: "jsonl",
+ path: abs,
+ files: files.length,
+ observations: observationCount,
+ });
+
+ return {
+ success: true,
+ imported: files.length,
+ sessionIds,
+ observations: observationCount,
+ };
+ },
+ );
+}
diff --git a/src/index.ts b/src/index.ts
index 0970b74f..8965ea0a 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -76,6 +76,7 @@ import { registerQueryExpansionFunction } from "./functions/query-expansion.js";
import { registerTemporalGraphFunctions } from "./functions/temporal-graph.js";
import { registerRetentionFunctions } from "./functions/retention.js";
import { registerCompressFileFunction } from "./functions/compress-file.js";
+import { registerReplayFunctions } from "./functions/replay.js";
import { registerApiTriggers } from "./triggers/api.js";
import { registerEventTriggers } from "./triggers/events.js";
import { registerMcpEndpoints } from "./mcp/server.js";
@@ -241,6 +242,7 @@ async function main() {
registerTemporalGraphFunctions(sdk, kv, provider);
registerRetentionFunctions(sdk, kv);
registerCompressFileFunction(sdk, kv, provider);
+ registerReplayFunctions(sdk, kv);
console.log(
`[agentmemory] v0.6 advanced retrieval: sliding-window, query-expansion, temporal-graph, retention-scoring`,
);
diff --git a/src/replay/jsonl-parser.ts b/src/replay/jsonl-parser.ts
new file mode 100644
index 00000000..3e8487a1
--- /dev/null
+++ b/src/replay/jsonl-parser.ts
@@ -0,0 +1,180 @@
+import type { HookType, RawObservation } from "../types.js";
+import { generateId } from "../state/schema.js";
+
+interface JsonlEntry {
+ type?: string;
+ uuid?: string;
+ sessionId?: string;
+ timestamp?: string;
+ cwd?: string;
+ message?: {
+ role?: string;
+ content?: unknown;
+ };
+ toolUseResult?: unknown;
+ [k: string]: unknown;
+}
+
+export interface ParsedTranscript {
+ sessionId: string;
+ project: string;
+ cwd: string;
+ startedAt: string;
+ endedAt: string;
+ observations: RawObservation[];
+}
+
+function deriveProject(cwd: string): string {
+ if (!cwd) return "unknown";
+ const parts = cwd.split("/").filter(Boolean);
+ return parts[parts.length - 1] || "unknown";
+}
+
+function toText(content: unknown): string {
+ if (typeof content === "string") return content;
+ if (!Array.isArray(content)) return "";
+ const parts: string[] = [];
+ for (const item of content) {
+ if (!item || typeof item !== "object") continue;
+ const entry = item as Record<string, unknown>;
+ if (entry.type === "text" && typeof entry.text === "string") {
+ parts.push(entry.text);
+ }
+ }
+ return parts.join("\n");
+}
+
+function extractToolUses(content: unknown): Array<{ id: string; name: string; input: unknown }> {
+ if (!Array.isArray(content)) return [];
+ const out: Array<{ id: string; name: string; input: unknown }> = [];
+ for (const item of content) {
+ if (!item || typeof item !== "object") continue;
+ const entry = item as Record<string, unknown>;
+ if (entry.type === "tool_use") {
+ out.push({
+ id: typeof entry.id === "string" ? entry.id : "",
+ name: typeof entry.name === "string" ? entry.name : "unknown",
+ input: entry.input,
+ });
+ }
+ }
+ return out;
+}
+
+function extractToolResults(content: unknown): Array<{ toolUseId: string; output: unknown; isError: boolean }> {
+ if (!Array.isArray(content)) return [];
+ const out: Array<{ toolUseId: string; output: unknown; isError: boolean }> = [];
+ for (const item of content) {
+ if (!item || typeof item !== "object") continue;
+ const entry = item as Record<string, unknown>;
+ if (entry.type === "tool_result") {
+ out.push({
+ toolUseId: typeof entry.tool_use_id === "string" ? entry.tool_use_id : "",
+ output: entry.content,
+ isError: entry.is_error === true,
+ });
+ }
+ }
+ return out;
+}
+
+export function parseJsonlText(text: string, fallbackSessionId?: string): ParsedTranscript {
+ const lines = text.split("\n").filter((l) => l.trim().length > 0);
+ const entries: JsonlEntry[] = [];
+ for (const line of lines) {
+ try {
+ const parsed = JSON.parse(line);
+ if (parsed && typeof parsed === "object") entries.push(parsed as JsonlEntry);
+ } catch {
+ // skip malformed lines
+ }
+ }
+
+ let sessionId = fallbackSessionId || "";
+ let cwd = "";
+ let firstTs = "";
+ let lastTs = "";
+
+ const observations: RawObservation[] = [];
+
+ for (const entry of entries) {
+ if (entry.sessionId && !sessionId) sessionId = entry.sessionId;
+ if (entry.cwd && !cwd) cwd = entry.cwd;
+ const ts = entry.timestamp || new Date().toISOString();
+ if (!firstTs) firstTs = ts;
+ lastTs = ts;
+
+ const role = entry.message?.role;
+ const content = entry.message?.content;
+
+ if (entry.type === "user" && role === "user") {
+ const toolResults = extractToolResults(content);
+ if (toolResults.length > 0) {
+ for (const result of toolResults) {
+ observations.push({
+ id: generateId("obs"),
+ sessionId: sessionId || "imported",
+ timestamp: ts,
+ hookType: (result.isError ? "post_tool_failure" : "post_tool_use") as HookType,
+ toolName: undefined,
+ toolInput: { toolUseId: result.toolUseId },
+ toolOutput: result.output,
+ raw: entry,
+ });
+ }
+ } else {
+ const text = toText(content);
+ if (text.trim().length > 0) {
+ observations.push({
+ id: generateId("obs"),
+ sessionId: sessionId || "imported",
+ timestamp: ts,
+ hookType: "prompt_submit" as HookType,
+ userPrompt: text,
+ raw: entry,
+ });
+ }
+ }
+ } else if (entry.type === "assistant" && role === "assistant") {
+ const text = toText(content);
+ const tools = extractToolUses(content);
+ if (text.trim().length > 0) {
+ observations.push({
+ id: generateId("obs"),
+ sessionId: sessionId || "imported",
+ timestamp: ts,
+ hookType: "stop" as HookType,
+ assistantResponse: text,
+ raw: entry,
+ });
+ }
+ for (const tool of tools) {
+ observations.push({
+ id: generateId("obs"),
+ sessionId: sessionId || "imported",
+ timestamp: ts,
+ hookType: "pre_tool_use" as HookType,
+ toolName: tool.name,
+ toolInput: tool.input,
+ raw: { toolUseId: tool.id, entry },
+ });
+ }
+ } else if (entry.type === "summary" || entry.type === "system") {
+ // ignore meta entries
+ }
+ }
+
+ const effectiveSessionId = sessionId || generateId("sess");
+ for (const obs of observations) {
+ if (obs.sessionId === "imported") obs.sessionId = effectiveSessionId;
+ }
+
+ return {
+ sessionId: effectiveSessionId,
+ project: deriveProject(cwd),
+ cwd: cwd || process.cwd(),
+ startedAt: firstTs || new Date().toISOString(),
+ endedAt: lastTs || new Date().toISOString(),
+ observations,
+ };
+}
diff --git a/src/replay/timeline.ts b/src/replay/timeline.ts
new file mode 100644
index 00000000..03e8051d
--- /dev/null
+++ b/src/replay/timeline.ts
@@ -0,0 +1,166 @@
+import type { RawObservation } from "../types.js";
+
+export type TimelineEventKind =
+ | "prompt"
+ | "response"
+ | "tool_call"
+ | "tool_result"
+ | "tool_error"
+ | "hook"
+ | "session_start"
+ | "session_end";
+
+export interface TimelineEvent {
+ id: string;
+ sessionId: string;
+ ts: string;
+ offsetMs: number;
+ durationMs: number;
+ kind: TimelineEventKind;
+ label: string;
+ body?: string;
+ toolName?: string;
+ toolInput?: unknown;
+ toolOutput?: unknown;
+}
+
+export interface Timeline {
+ sessionId: string;
+ startedAt: string;
+ endedAt: string;
+ totalDurationMs: number;
+ eventCount: number;
+ events: TimelineEvent[];
+}
+
+const DEFAULT_CHARS_PER_SEC = 40;
+const MIN_EVENT_MS = 300;
+const MAX_EVENT_MS = 20_000;
+
+function kindFromHook(obs: RawObservation): TimelineEventKind {
+ switch (obs.hookType) {
+ case "session_start":
+ return "session_start";
+ case "session_end":
+ return "session_end";
+ case "prompt_submit":
+ return "prompt";
+ case "stop":
+ return obs.assistantResponse ? "response" : "hook";
+ case "pre_tool_use":
+ return "tool_call";
+ case "post_tool_use":
+ return "tool_result";
+ case "post_tool_failure":
+ return "tool_error";
+ default:
+ return "hook";
+ }
+}
+
+function labelFor(obs: RawObservation, kind: TimelineEventKind): string {
+ switch (kind) {
+ case "prompt":
+ return truncate(obs.userPrompt || "User prompt", 80);
+ case "response":
+ return truncate(obs.assistantResponse || "Assistant response", 80);
+ case "tool_call":
+ return `${obs.toolName || "tool"} ▸ call`;
+ case "tool_result":
+ return `${obs.toolName || "tool"} ▸ result`;
+ case "tool_error":
+ return `${obs.toolName || "tool"} ▸ error`;
+ case "session_start":
+ return "Session start";
+ case "session_end":
+ return "Session end";
+ default:
+ return obs.hookType;
+ }
+}
+
+function truncate(text: string, max: number): string {
+ if (text.length <= max) return text;
+ return text.slice(0, max - 1) + "…";
+}
+
+function bodyFor(obs: RawObservation, kind: TimelineEventKind): string | undefined {
+ if (kind === "prompt") return obs.userPrompt;
+ if (kind === "response") return obs.assistantResponse;
+ return undefined;
+}
+
+function estimateDurationMs(ev: TimelineEvent): number {
+ const chars =
+ (ev.body?.length || 0) +
+ (typeof ev.toolInput === "string" ? ev.toolInput.length : 0) +
+ (typeof ev.toolOutput === "string" ? ev.toolOutput.length : 0);
+ if (chars === 0) return MIN_EVENT_MS;
+ const ms = Math.round((chars / DEFAULT_CHARS_PER_SEC) * 1000);
+ return Math.max(MIN_EVENT_MS, Math.min(MAX_EVENT_MS, ms));
+}
+
+export function projectTimeline(observations: RawObservation[]): Timeline {
+ if (observations.length === 0) {
+ const now = new Date().toISOString();
+ return {
+ sessionId: "",
+ startedAt: now,
+ endedAt: now,
+ totalDurationMs: 0,
+ eventCount: 0,
+ events: [],
+ };
+ }
+
+ const sorted = [...observations].sort((a, b) =>
+ a.timestamp.localeCompare(b.timestamp),
+ );
+
+ const startedAt = sorted[0].timestamp;
+ const startMs = Date.parse(startedAt);
+ const events: TimelineEvent[] = [];
+
+ let syntheticOffset = 0;
+ const allSameTs = sorted.every((o) => o.timestamp === startedAt);
+
+ for (const obs of sorted) {
+ const kind = kindFromHook(obs);
+ const body = bodyFor(obs, kind);
+ const obsMs = Date.parse(obs.timestamp);
+ const offsetMs = allSameTs
+ ? syntheticOffset
+ : Number.isFinite(obsMs) && Number.isFinite(startMs)
+ ? Math.max(0, obsMs - startMs)
+ : syntheticOffset;
+
+ const event: TimelineEvent = {
+ id: obs.id,
+ sessionId: obs.sessionId,
+ ts: obs.timestamp,
+ offsetMs,
+ durationMs: 0,
+ kind,
+ label: labelFor(obs, kind),
+ body,
+ toolName: obs.toolName,
+ toolInput: obs.toolInput,
+ toolOutput: obs.toolOutput,
+ };
+ event.durationMs = estimateDurationMs(event);
+ events.push(event);
+ syntheticOffset += event.durationMs;
+ }
+
+ const last = events[events.length - 1];
+ const totalDurationMs = last.offsetMs + last.durationMs;
+
+ return {
+ sessionId: sorted[0].sessionId,
+ startedAt,
+ endedAt: sorted[sorted.length - 1].timestamp,
+ totalDurationMs,
+ eventCount: events.length,
+ events,
+ };
+}
diff --git a/src/triggers/api.ts b/src/triggers/api.ts
index 6691be4c..a5da2b72 100644
--- a/src/triggers/api.ts
+++ b/src/triggers/api.ts
@@ -319,6 +319,80 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/compress-file", http_method: "POST" },
});
+ sdk.registerFunction("api::replay::load",
+ async (req: ApiRequest): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ const sessionId = asNonEmptyString(req.query_params?.["sessionId"]);
+ if (!sessionId) {
+ return { status_code: 400, body: { error: "sessionId is required" } };
+ }
+ const result = await sdk.trigger({
+ function_id: "mem::replay::load",
+ payload: { sessionId },
+ });
+ return { status_code: 200, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::replay::load",
+ config: { api_path: "/agentmemory/replay/load", http_method: "GET" },
+ });
+
+ sdk.registerFunction("api::replay::sessions",
+ async (req: ApiRequest): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ const result = await sdk.trigger({ function_id: "mem::replay::sessions" });
+ return { status_code: 200, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::replay::sessions",
+ config: { api_path: "/agentmemory/replay/sessions", http_method: "GET" },
+ });
+
+ sdk.registerFunction("api::replay::import",
+ async (
+ req: ApiRequest<{ path?: string; maxFiles?: number }>,
+ ): Promise<Response> => {
+ const authErr = checkAuth(req, secret);
+ if (authErr) return authErr;
+ const body = (req.body ?? {}) as Record<string, unknown>;
+ const payload: { path?: string; maxFiles?: number } = {};
+ if (body.path !== undefined) {
+ if (typeof body.path !== "string" || body.path.trim().length === 0) {
+ return {
+ status_code: 400,
+ body: { error: "path must be a non-empty string" },
+ };
+ }
+ payload.path = body.path;
+ }
+ if (body.maxFiles !== undefined) {
+ if (!Number.isInteger(body.maxFiles) || (body.maxFiles as number) < 1) {
+ return {
+ status_code: 400,
+ body: { error: "maxFiles must be a positive integer" },
+ };
+ }
+ payload.maxFiles = body.maxFiles as number;
+ }
+ const result = await sdk.trigger({
+ function_id: "mem::replay::import-jsonl",
+ payload,
+ });
+ return { status_code: 202, body: result };
+ },
+ );
+ sdk.registerTrigger({
+ type: "http",
+ function_id: "api::replay::import",
+ config: { api_path: "/agentmemory/replay/import-jsonl", http_method: "POST" },
+ });
+
sdk.registerFunction("api::session::start",
async (
req: ApiRequest<{ sessionId: string; project: string; cwd: string }>,
diff --git a/src/types.ts b/src/types.ts
index af9c15ff..883697ba 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -252,7 +252,7 @@ export interface ExportPagination {
}
export interface ExportData {
- version: "0.3.0" | "0.4.0" | "0.5.0" | "0.6.0" | "0.6.1" | "0.7.0" | "0.7.2" | "0.7.3" | "0.7.4" | "0.7.5" | "0.7.6" | "0.7.9" | "0.8.0" | "0.8.1" | "0.8.2" | "0.8.3" | "0.8.4" | "0.8.5" | "0.8.6" | "0.8.7" | "0.8.8" | "0.8.9" | "0.8.10" | "0.8.11" | "0.8.12";
+ version: "0.3.0" | "0.4.0" | "0.5.0" | "0.6.0" | "0.6.1" | "0.7.0" | "0.7.2" | "0.7.3" | "0.7.4" | "0.7.5" | "0.7.6" | "0.7.9" | "0.8.0" | "0.8.1" | "0.8.2" | "0.8.3" | "0.8.4" | "0.8.5" | "0.8.6" | "0.8.7" | "0.8.8" | "0.8.9" | "0.8.10" | "0.8.11" | "0.8.12" | "0.8.13";
exportedAt: string;
sessions: Session[];
observations: Record<string, CompressedObservation[]>;
diff --git a/src/version.ts b/src/version.ts
index 8804ae26..bf1e842e 100644
--- a/src/version.ts
+++ b/src/version.ts
@@ -1 +1 @@
-export const VERSION: "0.3.0" | "0.4.0" | "0.5.0" | "0.6.0" | "0.6.1" | "0.7.0" | "0.7.2" | "0.7.3" | "0.7.4" | "0.7.5" | "0.7.6" | "0.8.1" | "0.8.2" | "0.8.3" | "0.8.4" | "0.8.5" | "0.8.6" | "0.8.7" | "0.8.8" | "0.8.9" | "0.8.10" | "0.8.11" | "0.8.12" = "0.8.12";
+export const VERSION: "0.3.0" | "0.4.0" | "0.5.0" | "0.6.0" | "0.6.1" | "0.7.0" | "0.7.2" | "0.7.3" | "0.7.4" | "0.7.5" | "0.7.6" | "0.8.1" | "0.8.2" | "0.8.3" | "0.8.4" | "0.8.5" | "0.8.6" | "0.8.7" | "0.8.8" | "0.8.9" | "0.8.10" | "0.8.11" | "0.8.12" | "0.8.13" = "0.8.13";
diff --git a/src/viewer/index.html b/src/viewer/index.html
index e7a2c396..f1769b82 100644
--- a/src/viewer/index.html
+++ b/src/viewer/index.html
@@ -579,6 +579,34 @@
.loading { color: var(--ink-faint); padding: 20px; text-align: center; font-style: italic; font-family: var(--font-body); }
+ .replay-controls { display: flex; align-items: center; gap: 6px; padding: 10px 0; flex-wrap: wrap; font-family: var(--font-ui); font-size: 12px; }
+ .replay-controls button { padding: 4px 10px; border: 1px solid var(--border); background: var(--bg); color: var(--ink); cursor: pointer; font-family: var(--font-ui); font-size: 12px; }
+ .replay-controls button:hover { background: var(--bg-alt); }
+ .replay-controls button.active { background: var(--ink); color: var(--bg); }
+ .replay-controls .sep { width: 12px; }
+ .replay-progress { height: 3px; background: var(--border-light); margin: 4px 0 12px 0; }
+ .replay-progress-bar { height: 100%; background: var(--ink); transition: width 100ms linear; }
+ .replay-grid { display: grid; grid-template-columns: 340px 1fr; gap: 16px; align-items: start; }
+ .replay-list { max-height: 60vh; overflow-y: auto; border: 1px solid var(--border); }
+ .replay-event { display: grid; grid-template-columns: 90px 1fr 60px; gap: 8px; padding: 6px 10px; border-bottom: 1px solid var(--border-light); font-family: var(--font-ui); font-size: 11px; cursor: default; }
+ .replay-event:hover { background: var(--bg-alt); }
+ .replay-event-active { background: var(--bg-alt); border-left: 2px solid var(--ink); }
+ .replay-event-kind { font-size: 9px; text-transform: uppercase; letter-spacing: 0.1em; color: var(--ink-muted); align-self: center; }
+ .replay-event-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .replay-event-time { text-align: right; font-family: var(--font-mono); color: var(--ink-muted); }
+ .replay-event-prompt .replay-event-kind { color: var(--blue, #0366d6); }
+ .replay-event-response .replay-event-kind { color: var(--green, #2ea043); }
+ .replay-event-tool_call .replay-event-kind { color: var(--orange, #bf8700); }
+ .replay-event-tool_result .replay-event-kind { color: var(--ink-muted); }
+ .replay-event-tool_error .replay-event-kind { color: var(--red, #cf222e); }
+ .replay-detail { border: 1px solid var(--border); padding: 14px; max-height: 60vh; overflow-y: auto; font-family: var(--font-body); font-size: 13px; }
+ .replay-detail-header { margin-bottom: 6px; }
+ .replay-body { background: var(--bg-alt); padding: 10px; white-space: pre-wrap; word-break: break-word; font-family: var(--font-mono); font-size: 12px; }
+ .replay-tool { margin-top: 10px; font-family: var(--font-ui); font-size: 12px; }
+ .replay-tool-block { margin-top: 8px; }
+ .replay-tool-block pre { background: var(--bg-alt); padding: 10px; max-height: 240px; overflow: auto; font-family: var(--font-mono); font-size: 11px; white-space: pre-wrap; word-break: break-word; }
+ .muted { color: var(--ink-muted); font-size: 11px; }
+
.metric-table { width: 100%; border-collapse: collapse; font-size: 12px; }
.metric-table th { padding: 6px 8px; font-size: 9px; text-transform: uppercase; letter-spacing: 0.12em; color: var(--ink-muted); border-bottom: 2px solid var(--border); text-align: left; font-family: var(--font-ui); font-weight: 600; }
.metric-table td { padding: 5px 8px; border-bottom: 1px solid var(--border-light); }
@@ -782,6 +810,7 @@
<button data-tab="audit">Audit</button>
<button data-tab="activity">Activity</button>
<button data-tab="profile">Profile</button>
+ <button data-tab="replay">Replay</button>
</div>
<div id="view-dashboard" class="view active"></div>
@@ -795,6 +824,7 @@
<div id="view-audit" class="view"></div>
<div id="view-activity" class="view"></div>
<div id="view-profile" class="view"></div>
+ <div id="view-replay" class="view"></div>
<div id="modal-overlay" class="modal-overlay">
<div class="modal" id="modal"></div>
@@ -871,6 +901,7 @@
actions: { loaded: false, items: [], frontier: [], statusFilter: '', search: '' },
crystals: { loaded: false, items: [], search: '' },
profile: { loaded: false, projects: [], selectedProject: '', data: null },
+ replay: { loaded: false, sessions: [], selectedId: '', timeline: null, cursor: 0, playing: false, speed: 1, timer: null, startAt: 0, offsetAt: 0 },
ws: null
};
@@ -957,6 +988,7 @@
case 'audit': if (!state.audit.loaded) await loadAudit(); break;
case 'activity': if (!state.activity.loaded) await loadActivity(); break;
case 'profile': if (!state.profile.loaded) await loadProfile(); break;
+ case 'replay': if (!state.replay.loaded) await loadReplay(); break;
}
}
@@ -3006,11 +3038,239 @@
var auditIndex = parseInt(target.getAttribute('data-audit-index') || '', 10);
if (!Number.isNaN(auditIndex)) toggleAuditDetail(auditIndex);
}
+ if (action === 'replay-select') {
+ var rSid = target.getAttribute('data-session-id');
+ if (rSid) selectReplaySession(rSid);
+ return;
+ }
+ if (action === 'replay-toggle-play') { toggleReplayPlay(); return; }
+ if (action === 'replay-step') {
+ var d = parseInt(target.getAttribute('data-dir') || '1', 10);
+ stepReplay(d);
+ return;
+ }
+ if (action === 'replay-speed') {
+ var sp = parseFloat(target.getAttribute('data-speed') || '1');
+ setReplaySpeed(sp);
+ return;
+ }
+ if (action === 'replay-reset') { resetReplay(); return; }
+ if (action === 'replay-import') { runReplayImport(); return; }
+ if (action === 'replay-refresh') { refreshReplaySessions(); return; }
});
document.getElementById('modal-overlay').addEventListener('click', function(e) {
if (e.target === this) closeModal();
});
+ async function loadReplay() {
+ var el = document.getElementById('view-replay');
+ el.innerHTML = '<div class="loading">Loading sessions…</div>';
+ var res = await apiGet('replay/sessions');
+ state.replay.sessions = (res && res.sessions) || [];
+ state.replay.loaded = true;
+ renderReplay();
+ }
+
+ async function refreshReplaySessions() {
+ state.replay.loaded = false;
+ await loadReplay();
+ }
+
+ function renderReplay() {
+ var el = document.getElementById('view-replay');
+ var sessions = state.replay.sessions || [];
+ var options = '<option value="">— pick a session —</option>' + sessions.map(function(s) {
+ var label = (s.project || 'unknown') + ' · ' + (s.id || '').slice(0, 8) + ' · ' + (s.observationCount || 0) + ' obs';
+ return '<option value="' + esc(s.id) + '"' + (s.id === state.replay.selectedId ? ' selected' : '') + '>' + esc(label) + '</option>';
+ }).join('');
+
+ var tl = state.replay.timeline;
+ var hasTl = tl && tl.events && tl.events.length > 0;
+ var cursorEvent = hasTl ? tl.events[Math.min(state.replay.cursor, tl.events.length - 1)] : null;
+ var progress = hasTl && tl.totalDurationMs > 0 ? Math.min(100, (state.replay.offsetAt / tl.totalDurationMs) * 100) : 0;
+
+ el.innerHTML =
+ '<div class="toolbar">' +
+ '<select id="replay-session-select">' + options + '</select>' +
+ '<button data-action="replay-refresh">Refresh</button>' +
+ '<span class="sep"></span>' +
+ '<input type="text" id="replay-import-path" placeholder="~/.claude/projects or file.jsonl" style="width:280px">' +
+ '<button data-action="replay-import">Import JSONL</button>' +
+ '</div>' +
+ (hasTl
+ ? '<div class="replay-controls">' +
+ '<button data-action="replay-step" data-dir="-1" title="Previous (←)">◀</button>' +
+ '<button data-action="replay-toggle-play" title="Play/Pause (Space)">' + (state.replay.playing ? '❚❚ Pause' : '▶ Play') + '</button>' +
+ '<button data-action="replay-step" data-dir="1" title="Next (→)">▶</button>' +
+ '<button data-action="replay-reset" title="Reset">⟲</button>' +
+ '<span class="sep"></span>' +
+ '<span>Speed</span>' +
+ ['0.5', '1', '2', '4'].map(function(sp) {
+ var active = Math.abs(state.replay.speed - parseFloat(sp)) < 0.01;
+ return '<button data-action="replay-speed" data-speed="' + sp + '"' + (active ? ' class="active"' : '') + '>' + sp + '×</button>';
+ }).join('') +
+ '<span class="sep"></span>' +
+ '<span>' + (state.replay.cursor + 1) + ' / ' + tl.eventCount + '</span>' +
+ '</div>' +
+ '<div class="replay-progress"><div class="replay-progress-bar" style="width:' + progress.toFixed(1) + '%"></div></div>' +
+ '<div class="replay-grid">' +
+ '<div class="replay-list" id="replay-list">' +
+ tl.events.map(function(ev, i) {
+ var active = i === state.replay.cursor ? ' replay-event-active' : '';
+ return '<div class="replay-event replay-event-' + esc(ev.kind) + active + '" data-replay-idx="' + i + '">' +
+ '<span class="replay-event-kind">' + esc(ev.kind) + '</span>' +
+ '<span class="replay-event-label">' + esc(ev.label) + '</span>' +
+ '<span class="replay-event-time">' + (ev.offsetMs / 1000).toFixed(1) + 's</span>' +
+ '</div>';
+ }).join('') +
+ '</div>' +
+ '<div class="replay-detail">' + renderReplayDetail(cursorEvent) + '</div>' +
+ '</div>'
+ : '<div class="empty">Pick a session to replay, or import Claude Code JSONL transcripts from ~/.claude/projects.</div>');
+
+ var sel = document.getElementById('replay-session-select');
+ if (sel) sel.addEventListener('change', function() { selectReplaySession(sel.value); });
+ }
+
+ function renderReplayDetail(ev) {
+ if (!ev) return '<div class="empty">No event selected.</div>';
+ var blocks = [];
+ blocks.push('<div class="replay-detail-header"><b>' + esc(ev.label) + '</b> <span class="muted">' + esc(ev.kind) + '</span></div>');
+ if (ev.ts) blocks.push('<div class="muted">' + esc(formatTime(ev.ts)) + '</div>');
+ if (ev.body) {
+ blocks.push('<pre class="replay-body">' + esc(ev.body) + '</pre>');
+ }
+ if (ev.toolName) {
+ blocks.push('<div class="replay-tool"><b>Tool:</b> ' + esc(ev.toolName) + '</div>');
+ }
+ if (ev.toolInput !== undefined && ev.toolInput !== null) {
+ var inp = typeof ev.toolInput === 'string' ? ev.toolInput : JSON.stringify(ev.toolInput, null, 2);
+ blocks.push('<div class="replay-tool-block"><b>Input</b><pre>' + esc(truncate(inp, 4000)) + '</pre></div>');
+ }
+ if (ev.toolOutput !== undefined && ev.toolOutput !== null) {
+ var out = typeof ev.toolOutput === 'string' ? ev.toolOutput : JSON.stringify(ev.toolOutput, null, 2);
+ blocks.push('<div class="replay-tool-block"><b>Output</b><pre>' + esc(truncate(out, 4000)) + '</pre></div>');
+ }
+ return blocks.join('');
+ }
+
+ async function selectReplaySession(sessionId) {
+ stopReplayTimer();
+ state.replay.selectedId = sessionId;
+ state.replay.timeline = null;
+ state.replay.cursor = 0;
+ state.replay.offsetAt = 0;
+ state.replay.playing = false;
+ if (!sessionId) { renderReplay(); return; }
+ var el = document.getElementById('view-replay');
+ el.innerHTML = '<div class="loading">Loading replay…</div>';
+ var res = await apiGet('replay/load?sessionId=' + encodeURIComponent(sessionId));
+ if (res && res.success && res.timeline) {
+ state.replay.timeline = res.timeline;
+ } else {
+ state.replay.timeline = { events: [], eventCount: 0, totalDurationMs: 0 };
+ }
+ renderReplay();
+ }
+
+ function toggleReplayPlay() {
+ if (!state.replay.timeline || state.replay.timeline.eventCount === 0) return;
+ if (state.replay.playing) {
+ stopReplayTimer();
+ } else {
+ startReplayTimer();
+ }
+ renderReplay();
+ }
+
+ function startReplayTimer() {
+ state.replay.playing = true;
+ state.replay.startAt = Date.now();
+ var baseOffset = state.replay.offsetAt;
+ if (state.replay.timer) clearInterval(state.replay.timer);
+ state.replay.timer = setInterval(function() {
+ if (!state.replay.timeline) return;
+ var elapsed = (Date.now() - state.replay.startAt) * state.replay.speed;
+ state.replay.offsetAt = baseOffset + elapsed;
+ var events = state.replay.timeline.events;
+ var newCursor = state.replay.cursor;
+ for (var i = newCursor; i < events.length; i++) {
+ if (events[i].offsetMs <= state.replay.offsetAt) newCursor = i;
+ else break;
+ }
+ var changed = newCursor !== state.replay.cursor;
+ state.replay.cursor = newCursor;
+ if (state.replay.offsetAt >= state.replay.timeline.totalDurationMs) {
+ state.replay.offsetAt = state.replay.timeline.totalDurationMs;
+ stopReplayTimer();
+ renderReplay();
+ return;
+ }
+ if (changed) renderReplay();
+ }, 100);
+ }
+
+ function stopReplayTimer() {
+ state.replay.playing = false;
+ if (state.replay.timer) {
+ clearInterval(state.replay.timer);
+ state.replay.timer = null;
+ }
+ }
+
+ function stepReplay(dir) {
+ if (!state.replay.timeline) return;
+ stopReplayTimer();
+ var next = state.replay.cursor + dir;
+ if (next < 0) next = 0;
+ if (next >= state.replay.timeline.eventCount) next = state.replay.timeline.eventCount - 1;
+ state.replay.cursor = next;
+ state.replay.offsetAt = state.replay.timeline.events[next].offsetMs;
+ renderReplay();
+ }
+
+ function setReplaySpeed(sp) {
+ if (!sp || sp <= 0) return;
+ var wasPlaying = state.replay.playing;
+ stopReplayTimer();
+ state.replay.speed = sp;
+ if (wasPlaying) startReplayTimer();
+ renderReplay();
+ }
+
+ function resetReplay() {
+ stopReplayTimer();
+ state.replay.cursor = 0;
+ state.replay.offsetAt = 0;
+ renderReplay();
+ }
+
+ async function runReplayImport() {
+ var input = document.getElementById('replay-import-path');
+ var pathVal = input ? input.value.trim() : '';
+ var body = {};
+ if (pathVal) body.path = pathVal;
+ var el = document.getElementById('view-replay');
+ var prior = el.innerHTML;
+ el.innerHTML = '<div class="loading">Importing JSONL…</div>';
+ var res = await apiPost('replay/import-jsonl', body);
+ if (!res || res.success === false) {
+ el.innerHTML = prior;
+ alert((res && res.error) || 'Import failed');
+ return;
+ }
+ alert('Imported ' + (res.imported || 0) + ' file(s), ' + (res.observations || 0) + ' observation(s)');
+ await refreshReplaySessions();
+ }
+
+ document.addEventListener('keydown', function(e) {
+ if (state.activeTab !== 'replay') return;
+ if (e.target && (e.target.tagName === 'INPUT' || e.target.tagName === 'SELECT' || e.target.tagName === 'TEXTAREA')) return;
+ if (e.key === ' ') { e.preventDefault(); toggleReplayPlay(); }
+ else if (e.key === 'ArrowLeft') { e.preventDefault(); stepReplay(-1); }
+ else if (e.key === 'ArrowRight') { e.preventDefault(); stepReplay(1); }
+ });
+
loadTab('dashboard');
connectWs();
startDashboardAutoRefresh();
diff --git a/test/export-import.test.ts b/test/export-import.test.ts
index fa5dd5c4..dd980aac 100644
--- a/test/export-import.test.ts
+++ b/test/export-import.test.ts
@@ -119,7 +119,7 @@ describe("Export/Import Functions", () => {
it("export produces valid ExportData structure", async () => {
const result = (await sdk.trigger("mem::export", {})) as ExportData;
- expect(result.version).toBe("0.8.12");
+ expect(result.version).toBe("0.8.13");
expect(result.exportedAt).toBeDefined();
expect(result.sessions.length).toBe(1);
expect(result.sessions[0].id).toBe("ses_1");
diff --git a/test/fixtures/jsonl/basic.jsonl b/test/fixtures/jsonl/basic.jsonl
new file mode 100644
index 00000000..18f9a2a9
--- /dev/null
+++ b/test/fixtures/jsonl/basic.jsonl
@@ -0,0 +1,2 @@
+{"type":"user","uuid":"u1","sessionId":"sess-basic","timestamp":"2026-04-17T10:00:00.000Z","cwd":"/Users/alice/project","message":{"role":"user","content":[{"type":"text","text":"Fix the login bug"}]}}
+{"type":"assistant","uuid":"a1","sessionId":"sess-basic","timestamp":"2026-04-17T10:00:05.000Z","message":{"role":"assistant","content":[{"type":"text","text":"Looking into it now."}]}}
diff --git a/test/fixtures/jsonl/errors.jsonl b/test/fixtures/jsonl/errors.jsonl
new file mode 100644
index 00000000..63c98a80
--- /dev/null
+++ b/test/fixtures/jsonl/errors.jsonl
@@ -0,0 +1,4 @@
+{"type":"user","uuid":"u1","sessionId":"sess-err","timestamp":"2026-04-17T12:00:00.000Z","cwd":"/tmp/x","message":{"role":"user","content":[{"type":"text","text":"Run tests"}]}}
+not-valid-json-line
+{"type":"assistant","uuid":"a1","sessionId":"sess-err","timestamp":"2026-04-17T12:00:01.000Z","message":{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"Bash","input":{"command":"npm test"}}]}}
+{"type":"user","uuid":"u2","sessionId":"sess-err","timestamp":"2026-04-17T12:00:02.000Z","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"exit 1","is_error":true}]}}
diff --git a/test/fixtures/jsonl/tool-use.jsonl b/test/fixtures/jsonl/tool-use.jsonl
new file mode 100644
index 00000000..f96f5bed
--- /dev/null
+++ b/test/fixtures/jsonl/tool-use.jsonl
@@ -0,0 +1,4 @@
+{"type":"user","uuid":"u1","sessionId":"sess-tool","timestamp":"2026-04-17T11:00:00.000Z","cwd":"/Users/bob/repo","message":{"role":"user","content":[{"type":"text","text":"List the files"}]}}
+{"type":"assistant","uuid":"a1","sessionId":"sess-tool","timestamp":"2026-04-17T11:00:02.000Z","message":{"role":"assistant","content":[{"type":"tool_use","id":"toolu_1","name":"Bash","input":{"command":"ls"}}]}}
+{"type":"user","uuid":"u2","sessionId":"sess-tool","timestamp":"2026-04-17T11:00:03.000Z","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"README.md\nsrc\n"}]}}
+{"type":"assistant","uuid":"a2","sessionId":"sess-tool","timestamp":"2026-04-17T11:00:04.000Z","message":{"role":"assistant","content":[{"type":"text","text":"Two entries."}]}}
diff --git a/test/replay.test.ts b/test/replay.test.ts
new file mode 100644
index 00000000..af8fd35e
--- /dev/null
+++ b/test/replay.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, it } from "vitest";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { parseJsonlText } from "../src/replay/jsonl-parser.js";
+import { projectTimeline } from "../src/replay/timeline.js";
+
+const fx = (name: string) =>
+ readFileSync(join(__dirname, "fixtures/jsonl", name), "utf-8");
+
+describe("parseJsonlText", () => {
+ it("parses basic user/assistant exchange", () => {
+ const out = parseJsonlText(fx("basic.jsonl"));
+ expect(out.sessionId).toBe("sess-basic");
+ expect(out.project).toBe("project");
+ expect(out.cwd).toBe("/Users/alice/project");
+ expect(out.observations).toHaveLength(2);
+ expect(out.observations[0].hookType).toBe("prompt_submit");
+ expect(out.observations[0].userPrompt).toBe("Fix the login bug");
+ expect(out.observations[1].hookType).toBe("stop");
+ expect(out.observations[1].assistantResponse).toBe("Looking into it now.");
+ });
+
+ it("parses tool_use + tool_result pairs", () => {
+ const out = parseJsonlText(fx("tool-use.jsonl"));
+ expect(out.sessionId).toBe("sess-tool");
+ const kinds = out.observations.map((o) => o.hookType);
+ expect(kinds).toEqual([
+ "prompt_submit",
+ "pre_tool_use",
+ "post_tool_use",
+ "stop",
+ ]);
+ const toolCall = out.observations[1];
+ expect(toolCall.toolName).toBe("Bash");
+ expect((toolCall.toolInput as { command: string }).command).toBe("ls");
+ const toolResult = out.observations[2];
+ expect(toolResult.toolOutput).toBe("README.md\nsrc\n");
+ });
+
+ it("tolerates malformed lines and marks tool errors", () => {
+ const out = parseJsonlText(fx("errors.jsonl"));
+ const errObs = out.observations.find((o) => o.hookType === "post_tool_failure");
+ expect(errObs).toBeDefined();
+ expect(errObs?.toolOutput).toBe("exit 1");
+ });
+
+ it("falls back to generated sessionId when missing", () => {
+ const text = JSON.stringify({
+ type: "user",
+ timestamp: "2026-01-01T00:00:00.000Z",
+ message: { role: "user", content: [{ type: "text", text: "hi" }] },
+ });
+ const out = parseJsonlText(text);
+ expect(out.sessionId).toMatch(/^sess_/);
+ });
+
+ it("returns empty observations for blank input", () => {
+ const out = parseJsonlText("");
+ expect(out.observations).toHaveLength(0);
+ });
+});
+
+describe("projectTimeline", () => {
+ it("preserves ordering and computes offsets from real timestamps", () => {
+ const parsed = parseJsonlText(fx("tool-use.jsonl"));
+ const tl = projectTimeline(parsed.observations);
+ expect(tl.eventCount).toBe(4);
+ expect(tl.events[0].kind).toBe("prompt");
+ expect(tl.events[1].kind).toBe("tool_call");
+ expect(tl.events[2].kind).toBe("tool_result");
+ expect(tl.events[3].kind).toBe("response");
+ expect(tl.events[0].offsetMs).toBe(0);
+ expect(tl.events[3].offsetMs).toBeGreaterThan(0);
+ });
+
+ it("synthesizes pacing when all timestamps identical", () => {
+ const parsed = parseJsonlText(fx("basic.jsonl"));
+ for (const obs of parsed.observations) obs.timestamp = "2026-04-17T10:00:00.000Z";
+ const tl = projectTimeline(parsed.observations);
+ expect(tl.events[0].offsetMs).toBe(0);
+ expect(tl.events[1].offsetMs).toBeGreaterThanOrEqual(300);
+ });
+
+ it("returns empty timeline for no observations", () => {
+ const tl = projectTimeline([]);
+ expect(tl.eventCount).toBe(0);
+ expect(tl.totalDurationMs).toBe(0);
+ expect(tl.events).toHaveLength(0);
+ });
+
+ it("marks errored tool results as tool_error kind", () => {
+ const parsed = parseJsonlText(fx("errors.jsonl"));
+ const tl = projectTimeline(parsed.observations);
+ expect(tl.events.some((e) => e.kind === "tool_error")).toBe(true);
+ });
+});