# How to Retrieve Original Bytes Using Caveman CCR Handles

> Retrieve original bytes from Caveman CCR handles using the CLI command or the TypeScript SDK. Easily recover source code with caveman mem recover.

- Repository: [Julius Brussee/caveman](https://github.com/JuliusBrussee/caveman)
- Tags: how-to-guide
- Published: 2026-09-06

---

**Use the `caveman mem recover <handle>` CLI command or call the `retrieve` method from the TypeScript SDK to fetch the original byte-exact source from a Compressed Code Representation (CCR) handle.**

The **Caveman** repository (JuliusBrussee/caveman) implements a lossless compression pipeline that stores code snapshots as CCR handles. These handles act as immutable references to your original bytes, enabling perfect round-trip recovery even after aggressive code transformations or AI-assisted edits.

## Understanding CCR Handles and Recovery

A **CCR (Compressed Code Representation)** handle is a unique identifier embedded during the compression workflow. When the Caveman agent runtime processes a transformation, it generates a `recovery_handle` and stores the byte-exact original in the local **CAVEMAN_CCR_DB** database. This guarantees that any compressed output can be reversed to its exact original state without data loss.

The retrieval system consists of four distinct stages: handle generation, database persistence, client request, and engine validation. Each stage is implemented across specific packages in the monorepo to separate concerns between the core agent, the π-extension API, and the CLI interface.

## The Retrieval Workflow

### Handle Generation in the Agent Runtime

When a transform produces CCR output, the agent runtime embeds a `recovery_handle` attribute into the generated markup. According to the source in [`packages/agent/src/runtime.ts`](https://github.com/JuliusBrussee/caveman/blob/main/packages/agent/src/runtime.ts) (around line 2700), the `engineRetrieve` call inserts a `<cave-compressed … recovery_handle=…>` tag into the response. Simultaneously, the runtime maintains an in-memory `handles` map that tracks active recovery tokens before they are persisted.

### Storage in the CCR Database

The **CAVEMAN_CCR_DB** serves as the persistent store for all byte arrays indexed by their recovery handles. The storage implementation resides in the same runtime module ([`packages/agent/src/runtime.ts`](https://github.com/JuliusBrussee/caveman/blob/main/packages/agent/src/runtime.ts)), where the handles map is flushed to disk. This ensures that handles remain available across process restarts and can be retrieved later via the CLI or SDK.

### Recovery Tool Interface

To access stored bytes, the **π-extension** exposes a dedicated recovery tool. In [`packages/pi-extension/src/recovery.ts`](https://github.com/JuliusBrussee/caveman/blob/main/packages/pi-extension/src/recovery.ts), the `retrieve` function constructs a request payload containing the `recovery_handle` and an optional query string, then forwards this to the engine's retrieval routine. This abstraction allows both the CLI and SDK to interact with the recovery database without direct filesystem access.

The CLI command implementation in [`packages/cli/src/index.ts`](https://github.com/JuliusBrussee/caveman/blob/main/packages/cli/src/index.ts) parses invocations of `caveman mem recover <handle>` and routes them through this π-extension interface.

### Engine-Side Validation and Lookup

The actual byte retrieval occurs inside the agent runtime. The `engineRetrieve` implementation (located around lines 3040–3044 in [`packages/agent/src/runtime.ts`](https://github.com/JuliusBrussee/caveman/blob/main/packages/agent/src/runtime.ts)) performs the following:

1. **Lookup**: Searches the CCR store for the provided handle
2. **Validation**: Checks if the handle is still in-scope; if not, it throws a `cave_recovery_handle_out_of_scope` error
3. **Usage Tracking**: Marks the handle as "used" to prevent stale-segment poisoning and ensure one-time retrieval semantics
4. **Filtering**: If a query parameter was provided, returns only the matching subset of bytes; otherwise returns the full array

The recovered bytes are then returned as a plain-text payload (or JSON envelope for programmatic callers). The TypeScript SDK ([`packages/sdk/typescript/src/index.ts`](https://github.com/JuliusBrussee/caveman/blob/main/packages/sdk/typescript/src/index.ts), around line 1702) decorates this response with a `recoveryHandle` field for typed access.

## Practical Code Examples

### CLI Usage

Recover the exact original source saved under a specific handle:

```bash

# Retrieve full original bytes

caveman mem recover ccr_abc123

```

### TypeScript SDK Implementation

Use the SDK to retrieve bytes programmatically within your application:

```typescript
import { CavemanClient } from '@caveman/sdk';

// Initialize client (assumes local CCR DB is reachable)
const client = new CavemanClient();

// Retrieve original bytes using the handle from a previous transform
const result = await client.recovery.retrieve({
  recovery_handle: 'ccr_abc123',
  // optional: filter on a query string to retrieve only a subset
  // query: 'function foo',
});

console.log(result.text); // Original source code as string

```

### Direct π-Extension API Call

For lower-level integration, import the Recovery module directly:

```typescript
import { Recovery } from '@caveman/pi-extension';

const recovered = await Recovery.retrieve({
  recovery_handle: 'ccr_abc123',
});

console.log(recovered.text);

```

## Summary

- **CCR handles** provide byte-exact references to original source code stored during Caveman compression operations.
- The retrieval pipeline spans [`packages/agent/src/runtime.ts`](https://github.com/JuliusBrussee/caveman/blob/main/packages/agent/src/runtime.ts) (storage and validation), [`packages/pi-extension/src/recovery.ts`](https://github.com/JuliusBrussee/caveman/blob/main/packages/pi-extension/src/recovery.ts) (API interface), and [`packages/cli/src/index.ts`](https://github.com/JuliusBrussee/caveman/blob/main/packages/cli/src/index.ts) (command parsing).
- Use `caveman mem recover <handle>` for command-line recovery or `client.recovery.retrieve()` for programmatic access.
- The engine validates handle scope and marks handles as used to prevent reuse attacks or stale data access.
- Optional query parameters allow retrieving filtered subsets of the original bytes rather than the entire payload.

## Frequently Asked Questions

### What is a CCR handle in Caveman?

A **CCR (Compressed Code Representation) handle** is a unique recovery token generated when the Caveman engine compresses or transforms code. It references the byte-exact original stored in the local CAVEMAN_CCR_DB database, enabling lossless retrieval of the pre-compression source.

### How does the engine validate CCR handles before retrieval?

According to the implementation in [`packages/agent/src/runtime.ts`](https://github.com/JuliusBrussee/caveman/blob/main/packages/agent/src/runtime.ts), the `engineRetrieve` function validates that the handle exists in the active CCR store and has not expired. If the handle is out of scope, the engine returns a `cave_recovery_handle_out_of_scope` error. Valid handles are marked as "used" immediately after retrieval to prevent duplicate access.

### Can I retrieve partial content from a CCR handle?

Yes. Both the SDK and π-extension support an optional `query` parameter in the retrieval request. When provided, the engine filters the stored byte array and returns only the subset matching your query string, useful for extracting specific functions or sections from large original files.

### Where are CCR handles physically stored?

Handles and their associated byte arrays are persisted in the **CAVEMAN_CCR_DB**, managed by the agent runtime in [`packages/agent/src/runtime.ts`](https://github.com/JuliusBrussee/caveman/blob/main/packages/agent/src/runtime.ts). This local database maintains the mapping between recovery handles and their original byte content, ensuring availability for later retrieval via the CLI or SDK.