# How ai-memory `run <harness>` Manages Workstream Sessions and Visible Events

> Discover how ai-memory run <harness> manages workstream sessions by acquiring leases, preparing event deltas, and orchestrating cross-harness context via environment variables and an immutable SQLite ledger.

- Repository: [Fabio Akita/ai-memory](https://github.com/akitaonrails/ai-memory)
- Tags: how-to-guide
- Published: 2026-08-22

---

**`ai-memory run` creates a managed workstream that acquires a 90-second renewable lease, prepares a portable delta of visible events, and orchestrates cross-harness sessions by injecting context via environment variables and persisting only user-visible messages to an immutable SQLite ledger.**

The `ai-memory` CLI from the [akitaonrails/ai-memory](https://github.com/akitaonrails/ai-memory) repository provides a unified interface for AI coding agents. When you execute `ai-memory run <harness>`, the tool does not merely spawn a subprocess; it establishes a durable **workstream session** that transcends individual harnesses like Claude Code, Codex, or OpenCode. This article examines the exact mechanisms governing lease management, event visibility, and cross-session continuity.

## Lease Acquisition and Concurrency Control

Before launching any harness, `ai-memory run` must secure exclusive access to the logical workstream. The system prevents concurrent terminal sessions from corrupting shared state through a time-bound locking mechanism.

In [`crates/ai-memory-store/src/workstream.rs`](https://github.com/akitaonrails/ai-memory/blob/main/crates/ai-memory-store/src/workstream.rs), the launcher resolves the workspace project and repository fingerprints, then opens a **90-second renewable lease** defined by the constant `LEASE_MICROS` (lines 14–15). This lease is stored in the SQLite-backed workstream store. If a second terminal attempts to acquire the lease while the first is still active, the request fails immediately with a *busy* error (lines 77–93). This guarantees exactly-once execution semantics for any given workstream at a specific point in time.

## Workstream Selection and Run Preparation

Once the lease is secured, the system identifies which logical workstream to bind to the current execution context.

The `select_workstream` function (lines 64–70) returns a `PreparedWorkstreamRun` struct containing:

- **`run_id`**: A unique `ManagedRunId` identifying this specific execution
- **`workstream_id`** and **`workstream_name`**: The logical container (defaults to `default` on first use)
- **`agent`**: The target harness (e.g., `claude`, `codex`)
- **Native session id**: Pre-existing session identifier if resuming
- **Cursor metadata**: `sync_after` and `sync_through` timestamps defining the event window
- **Adoption flag**: Boolean indicating whether the launcher may claim an existing native session

This preparation phase (lines 55–78) ensures the launcher knows exactly which slice of history the child process has not yet observed.

## Session Initialization and Event Injection

With the run context prepared, `ai-memory` bridges the managed workstream and the native harness through environment variables and lifecycle hooks.

The wrapper injects `AI_MEMORY_RUN_ID` into the child process environment. According to [`docs/managed-workstreams.md`](https://github.com/akitaonrails/ai-memory/blob/main/docs/managed-workstreams.md) (section "What happens on each run", steps 1–4), this allows the `SessionStart` lifecycle hook to construct a **portable delta**—the bounded set of visible events the child has missed—and deliver it via the `ManagedRunContext` struct. The harness receives this delta as an initialization packet, enabling seamless context restoration regardless of which AI agent was previously active in the workstream.

## Native Harness Execution

The launcher differentiates between harness-native arguments and managed-mode flags.

Native arguments such as `--session-id` (for Claude) or `--resume` (for Codex) are passed through unmodified. The `ai-memory` wrapper contributes only two managed-specific flags: `--yolo` (skip confirmation prompts) and `--fresh` (ignore existing state). This minimal intervention ensures the underlying agent behaves exactly as it would in standalone mode while remaining tethered to the central ledger.

## Post-Run Event Extraction and Ledger Persistence

When the child process exits, the system performs a unidirectional synchronization from the native transcript back to the persistent store.

As documented in [`docs/managed-workstreams.md`](https://github.com/akitaonrails/ai-memory/blob/main/docs/managed-workstreams.md) (steps 4–5), `ai-memory` opens the native transcript **read-only** and extracts **visible user/assistant messages, completed tool calls, and compaction summaries**. These are appended to the `workstream_events` table in the SQLite database. Hidden reasoning traces, ephemeral images, and provider-specific metadata are intentionally dropped; the system records these omissions as *extraction-loss* annotations to maintain transparency about what was not preserved.

This design creates an immutable, searchable ledger containing only the semantically relevant interactions, stripped of vendor-specific noise.

## Cross-Harness Event Retrieval

The accumulated history remains accessible across harness switches and shell sessions.

Because the ledger persists in SQLite, users can query visible events from inside an active managed session or from any external shell. The `ai-memory workstream-search` command (implemented in [`crates/ai-memory-cli/src/commands/workstream_search.rs`](https://github.com/akitaonrails/ai-memory/blob/main/crates/ai-memory-cli/src/commands/workstream_search.rs)) retrieves events with their source harness, role, and sequence. This enables scenarios like searching for a decision made in Claude Code while currently running under Codex, ensuring continuity of context without manual copy-paste operations.

## Summary

- **Lease-based concurrency**: A 90-second renewable lease (`LEASE_MICROS`) in [`workstream.rs`](https://github.com/akitaonrails/ai-memory/blob/main/workstream.rs) prevents concurrent workstream modification.
- **Structured preparation**: `PreparedWorkstreamRun` encapsulates run identifiers, cursor positions, and adoption rights before harness launch.
- **Environment injection**: `AI_MEMORY_RUN_ID` enables the `SessionStart` hook to deliver portable event deltas to the child process.
- **Selective persistence**: Only visible messages and tool completions are written to `workstream_events`; hidden reasoning is logged as extraction-loss.
- **Cross-harness search**: The immutable ledger supports `workstream-search` across all historical sessions regardless of originating harness.

## Frequently Asked Questions

### How does ai-memory prevent two terminals from editing the same workstream simultaneously?

`ai-memory run` acquires a 90-second renewable lease through the SQLite store at startup (defined as `LEASE_MICROS` in [`workstream.rs`](https://github.com/akitaonrails/ai-memory/blob/main/workstream.rs) lines 14–15). If another process holds the lease, the second terminal receives a *busy* error and exits immediately (lines 77–93). The lease auto-renews during active execution, ensuring continuity without risking concurrent writes.

### What exactly constitutes a "visible event" in the workstream ledger?

Visible events include explicit user messages, assistant responses, completed tool call results, and compaction summaries. According to [`managed-workstreams.md`](https://github.com/akitaonrails/ai-memory/blob/main/managed-workstreams.md), the system intentionally excludes hidden reasoning chains, embedded images, and provider-specific metadata. These exclusions are tracked as *extraction-loss* annotations to document what information was discarded during the import phase.

### Can I switch from Claude Code to Codex without losing conversation history?

Yes. When you execute `ai-memory run codex --yolo` after previously using Claude, the launcher prepares a `ManagedRunContext` containing the portable delta of events the Codex session has not seen. The `SessionStart` hook injects this history via the `AI_MEMORY_RUN_ID` environment variable, allowing Codex to resume the logical workstream with full awareness of prior interactions stored in the `workstream_events` table.

### Where is the workstream history physically stored?

The visible event ledger persists in a SQLite database managed by `ai-memory-store`, specifically within the `workstream_events` table. This file resides in the project's `.ai-memory` directory or the configured global path. Because the store is file-based, you can query it using `ai-memory workstream-search` from any directory or inspect it directly with SQLite tools.