# How Fork and Clone Session Functionality Works in Prime Agent

> Explore how Prime Agent's fork and clone session functionality creates isolated dialogue copies preserving Git metadata. Learn about SessionManager.forkFrom() and runtime.fork() for branching conversations.

- Repository: [Prime Intellect/prime-agent](https://github.com/PrimeIntellect-ai/prime-agent)
- Tags: internals
- Published: 2026-08-10

---

**Prime Agent enables conversation branching through a session management system that creates isolated copies of dialogue history using `SessionManager.forkFrom()` for file-level operations and `runtime.fork()` for interactive branching, preserving Git metadata and emitting specific lifecycle events during the transition.**

The PrimeIntellect-ai/prime-agent repository implements sophisticated session forking capabilities that allow developers to branch conversations at specific points or duplicate sessions for replay. Understanding how fork and clone session functionality works in Prime Agent requires examining the interaction between the session manager core and the runtime environment that manages conversation state.

## Session Manager Architecture and Fork Creation

The core implementation resides in [`packages/coding-agent/src/core/session-manager.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/core/session-manager.ts). This module handles the persistence layer for session branching, generating new JSONL session files that maintain historical context while establishing independent continuation paths.

### The forkFrom() Method Implementation

The `SessionManager.forkFrom(sourceFile, targetDir, sessionDir)` method creates a fresh session file by duplicating the source content while assigning a new **UUID-v7** identifier. This method performs three critical operations:

- Copies the source session's header, entries, and metadata into a new JSONL structure
- Records the origin path in the `forkFile` field to maintain provenance
- Captures the target Git state (commit hash, branch name, and remote URL) in the header's `git` field

The implementation also preserves **rlmDepth** (relative link-matrix depth) values for backward compatibility with legacy session formats, ensuring older forked sessions interoperate with current runtime logic.

## Runtime Fork Execution Flow

Interactive forking occurs through [`packages/coding-agent/src/core/runtime.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/core/runtime.ts) via the `runtime.fork(entryId, options)` method. This runtime-level operation coordinates the transition between conversation branches while maintaining application state consistency.

### Event Lifecycle and Position Control

When `runtime.fork()` executes, it triggers a specific event sequence defined in [`packages/coding-agent/src/core/events.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/core/events.ts):

1. Emits `session_before_fork` to signal impending branch creation
2. Shuts down the original runtime with `session_shutdown` (reason: "fork")
3. Initializes the new runtime with `session_start` (reason: "fork")

The method accepts a `position` option that accepts `"before"`, `"at"`, or `"after"` values, determining where the new branch inserts relative to the specified entry ID. This allows precise control over conversation divergence points.

## Fork vs. Clone: Operational Differences

Prime Agent distinguishes between two duplication modes through CLI flags and API behavior:

- **Fork** (`--fork` flag): Creates a *live* branch that inherits the original session's history but continues independently. Forked sessions retain selection metadata (such as highlighted code ranges) and support further editing and development.
- **Clone** (`--clone` or `-c` flag): Produces a static copy intended for replay or analysis. This operation assigns a fresh session ID without establishing a parent-child relationship, making it ideal for reviewing historic conversations without affecting active branches.

## Git Context and Metadata Isolation

When forking sessions, the system implements strict metadata isolation to prevent cross-session contamination. The new session header captures current repository state in the `git` field while explicitly stripping the source session's `git_state` field. This ensures that Git operations in the forked session reference the correct commit and branch context without inheriting stale state from the parent session.

The session manager also back-fills missing depth information for legacy forks, ensuring that older session files maintain compatibility with the newest runtime logic implemented in the Prime Agent core.

## Implementation Examples

The following TypeScript demonstrates programmatic forking and cloning:

```typescript
// Fork the current session at a specific entry point
await runtime.fork(userMessage.entryId, { position: "before" });

// Clone an existing session file for replay
const cloned = SessionManager.forkFrom(
  "/path/to/old-session.jsonl",   // source session
  "/tmp/new-session-dir",         // target directory
  "/tmp/new-session-dir"
);
await Runtime.load(cloned.getSessionFile()!);

```

CLI usage examples:

```bash

# Create a live fork of the current session

prime-agent --fork session.jsonl

# Generate a static clone for replay

prime-agent --clone old-session.jsonl

```

The test suite in [`packages/coding-agent/test/session-manager-fork.test.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/test/session-manager-fork.test.ts) validates these semantics, ensuring proper cancellation handling and depth preservation across fork operations.

## Summary

- **SessionManager.forkFrom()** in [`packages/coding-agent/src/core/session-manager.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/core/session-manager.ts) handles file-level session duplication using UUID-v7 identifiers and Git metadata capture.
- **runtime.fork()** in [`packages/coding-agent/src/core/runtime.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/core/runtime.ts) coordinates interactive branching through a three-phase event lifecycle (`session_before_fork`, `session_shutdown`, `session_start`).
- The `position` parameter supports "before", "at", and "after" insertion points for precise conversation branching.
- Forks create editable live branches with `--fork`, while clones create replay copies with `--clone` or `-c`.
- Git context isolation prevents cross-session contamination by capturing fresh repository state in the new header.

## Frequently Asked Questions

### What is the difference between fork and clone in Prime Agent?

**Forking creates an active branch that inherits conversation history but diverges independently**, maintaining metadata like code selections and supporting continued editing via the `--fork` flag. **Cloning produces a static replay copy** using `--clone` or `-c`, assigning a new session ID without establishing a parent-child relationship, making it suitable for reviewing past conversations without affecting active development branches.

### How does Prime Agent handle Git state when forking a session?

When forking, the system captures current repository information (commit hash, branch, remote URL) in the new session header's `git` field while explicitly removing the source session's `git_state` field. This isolation prevents Git operations in the forked session from referencing stale or incorrect repository states from the parent session.

### What event lifecycle occurs during a session fork?

The runtime emits `session_before_fork` before initiating the branch, followed by `session_shutdown` with reason "fork" on the original runtime, and concludes with `session_start` with reason "fork" on the new runtime instance. These events, defined in [`packages/coding-agent/src/core/events.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/core/events.ts), allow components to clean up resources and initialize state during the transition.

### How does the position parameter work in runtime.fork()?

The `position` option accepts three string values: `"before"` inserts the new branch prior to the specified entry, `"at"` branches directly at the entry point, and `"after"` creates the divergence following the entry. This parameter determines the exact insertion point in the conversation history relative to the `entryId` provided to the `runtime.fork()` method.