How Session Cloning Works with ConversationAnalyzer and SessionSharing

Session cloning in the davila7/claude-code-templates repository uses ConversationAnalyzer to parse conversation files into structured data and SessionSharing to export, upload, download, and reinstall sessions into the ~/.claude/projects/ directory, enabling seamless conversation resumption across machines.

The davila7/claude-code-templates project provides tools for managing Claude Code sessions programmatically. Session cloning allows you to share entire conversation histories via temporary URLs and resume them on different workstations. This functionality relies on two core modules that handle message parsing and file system orchestration.

What Is Session Cloning?

Session cloning is a six-stage workflow that moves a Claude Code conversation from one machine to another while preserving tool-use correlations, token counts, and metadata. The process flows through export → upload → share URL → download → validate → install → resume.

Two modules coordinate this process:

Step 1: Exporting the Session

The cloning process begins with SessionSharing.exportSessionData(), which prepares the conversation for transmission.

// Located in cli-tool/src/session-sharing.js
await this.exportSessionData(conversationId, conversationData, options);

Inside exportSessionData, the method first loads the original conversation file using ConversationAnalyzer.getParsedConversation (lines 18-23 of ConversationAnalyzer.js). This returns a structured array where tool uses are correlated with their results.

By default, the export limits output to the 100 most recent messages via options.messageLimit. The method then re-serializes the parsed messages back to JSONL format (lines 44-57) and appends metadata including tool version and export timestamps (lines 75-95). The result is an exportData object containing the complete session payload.

Step 2: Uploading the Export

Once serialized, the session uploads to a temporary file host. The uploadToX0() method manages this transfer.

const url = await this.uploadToX0(exportData, conversationId);

This method writes the JSON object to a temporary file and executes curl -F "file=@${tmpFile}" ${this.uploadUrl} (lines 31-34). By default, uploadUrl points to https://x0.at (line 28), returning a plain-text URL suitable for sharing via Slack, email, or documentation.

Step 3: Downloading and Validating

On the receiving machine, the recipient triggers cloning via the CLI command npx claude-code-templates@latest --clone-session <url>. This invokes SessionSharing.cloneSession(), which orchestrates retrieval and verification.

const sessionData = await this.downloadSession(url);

The downloadSession method executes curl -L "<url>" with a 50 MiB buffer (lines 8-11) and parses the response as JSON (line 16). If the response is invalid JSON, the method throws a descriptive error (lines 20-22).

After download, validateSessionData(sessionData) enforces data integrity by checking for required fields—specifically version, conversation.id, and a non-empty messages array (lines 32-45 of validateSessionData).

Step 4: Installing the Cloned Session

With validated data, SessionSharing.installSession() writes the conversation to the local Claude Code directory structure.

const installResult = await this.installSession(sessionData, options);

The method performs four critical operations:

  1. Directory Creation: Builds the destination path at ~/.claude/projects/<sanitized-name> using the sanitizeProjectName helper (lines 48-54 and 60-68).
  2. File Writing: Persists the conversation as <conversationId>.jsonl (lines 73-80).
  3. Configuration Update: Creates or modifies settings.json to include sharedSession: true, import timestamps, and export metadata (lines 84-95).
  4. Resume Command Generation: Outputs the command claude --resume <conversationId> to stdout (lines 86-90).

Because installSession writes a standard Claude Code JSONL file, the installed session is indistinguishable from locally created conversations.

How ConversationAnalyzer Enables Session Cloning

The ConversationAnalyzer class ensures data fidelity throughout the clone lifecycle. When exporting, getParsedConversation calls parseAndCorrelateToolMessages to map tool invocations to their results, preserving execution context. When the cloned session is later opened in Claude Code, the same parsing logic reads the installed .jsonl file, ensuring token usage, model information, and tool correlations remain intact.

const analyzer = new ConversationAnalyzer(claudeDir, dataCache);
const parsed = await analyzer.getParsedConversation(conversationFilePath);

This symmetrical parsing guarantees that a cloned session behaves identically to its original.

Practical Implementation Example

The following example demonstrates the complete round-trip from export to clone:

const SessionSharing = require('./cli-tool/src/session-sharing');
const ConversationAnalyzer = require('./cli-tool/src/analytics/core/ConversationAnalyzer');
const path = require('path');

(async () => {
  // Initialize analyzer with Claude Code directory
  const analyzer = new ConversationAnalyzer(path.join(process.env.HOME, '.claude'));
  
  // Create sharing instance
  const sharing = new SessionSharing(analyzer);
  sharing.uploadUrl = 'https://x0.at'; // Default value, explicit for clarity

  // Define conversation metadata
  const convId = '2024-08-15-abc123';
  const convData = {
    project: 'my-awesome-app',
    filePath: `/home/user/.claude/projects/my-awesome-app/${convId}.jsonl`,
    created: new Date().toISOString(),
    lastModified: new Date().toISOString(),
    tokens: 0,
    modelInfo: {}
  };

  // Export and upload
  const exported = await sharing.exportSessionData(convId, convData);
  const shareUrl = await sharing.uploadToX0(exported, convId);
  console.log('Share this URL:', shareUrl);

  // On destination machine: clone and resume
  const result = await sharing.cloneSession(shareUrl);
  console.log('Installed at:', result.sessionPath);
  console.log('Resume with:', `claude --resume ${result.conversationId}`);
})();

Summary

  • Session cloning moves Claude Code conversations between machines via a structured export/upload/download/install workflow.
  • ConversationAnalyzer (cli-tool/src/analytics/core/ConversationAnalyzer.js) parses and correlates tool messages to ensure data integrity during export and re-import.
  • SessionSharing (cli-tool/src/session-sharing.js) orchestrates file operations, curl-based network transfers, and filesystem installation.
  • Cloned sessions install to ~/.claude/projects/<sanitized-name> with updated settings.json metadata.
  • The process preserves tool correlations, token counts, and model information through symmetrical parsing logic.

Frequently Asked Questions

What files does SessionSharing create when cloning a session?

SessionSharing.installSession() creates a <conversationId>.jsonl file containing the conversation history and a settings.json file (or updates an existing one) with flags indicating sharedSession: true, import timestamps, and original export metadata. These files reside in ~/.claude/projects/<sanitized-project-name>/.

How does SessionSharing validate imported sessions before installation?

The validateSessionData() method checks for three required fields: version, conversation.id, and messages. It verifies that the messages property exists and is a non-empty array. If any required field is missing, the method throws a descriptive error before any files are written to disk.

Can I customize the upload destination for shared sessions?

Yes. While the default uploadUrl is https://x0.at, you can override the uploadToX0() behavior or modify the uploadUrl property on the SessionSharing instance before calling export methods. The class uses standard curl commands, making it compatible with any file hosting service that accepts multipart form data uploads.

Where are cloned sessions stored locally?

Cloned sessions install into ~/.claude/projects/<sanitized-name>/, where <sanitized-name> is derived from the original project name via the sanitizeProjectName() helper. This directory contains the conversation JSONL file and configuration metadata required for Claude Code to resume the session using claude --resume <conversationId>.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →