# How to Set Up and Manage Persistent Goals Across Multiple Prime Agent Sessions

> Learn how to set up and manage persistent goals across multiple Prime Agent sessions. Prime Agent automatically reloads goals via _loadPersistedGoalState() to maintain context.

- Repository: [Prime Intellect/prime-agent](https://github.com/PrimeIntellect-ai/prime-agent)
- Tags: how-to-guide
- Published: 2026-08-18

---

**Prime Agent stores thread-goals as durable custom entries in the session transcript, automatically reloading them on restart via `AgentSession._loadPersistedGoalState()` to maintain context across sessions.**

Prime Agent, developed by PrimeIntellect-ai/prime-agent, provides a robust mechanism for maintaining objectives across restarts, interruptions, and child session creation. Unlike ephemeral session variables, **persistent goals** survive process termination by serializing state directly into the JSONL transcript via the `SessionManager`. This architecture ensures that long-running coding tasks maintain continuity without manual state management.

## Creating Persistent Goals

You can initialize a persistent goal using either the interactive slash command or the programmatic host-bridge API.

**Slash command method** (from the TUI or any client):

```typescript
await session.prompt("/goal Write a concise summary of the project README", {
    "--goal-token-budget": "500"
});

```

**Programmatic API method**:

```typescript
session.handleGoalHostRequest("goal.create", {
    objective: "Refactor authentication module",
    tokenBudget: 1000
});

```

Both methods invoke `AgentSession._startGoal()` internally, which constructs the initial `GoalState` object.

## The Persistence Mechanism

When a goal state changes, `AgentSession._persistGoalState()` writes a custom entry to the session transcript. The implementation in [`packages/coding-agent/src/core/agent-session.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/core/agent-session.ts) appends the state using the constant `GOAL_STATE_CUSTOM_TYPE` (defined in [`packages/coding-agent/src/core/goals.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/core/goals.ts) as `"thread_goal_state"`):

```typescript
// packages/coding-agent/src/core/agent-session.ts
this.sessionManager.appendCustomEntry(GOAL_STATE_CUSTOM_TYPE, goal);
this.sessionManager.flushNow();   // immediately durable

```

The `flushNow()` call ensures the entry is written to disk immediately, making the goal resistant to crashes or power loss.

## Reloading Goals on Session Restart

On session startup, the constructor calls `_loadPersistedGoalState()` to scan the transcript branch from newest to oldest. The method looks for the most recent `thread_goal_state` entry, validates it with `isPersistedGoalState()`, and normalizes the data:

```typescript
private _loadPersistedGoalState(): GoalState {
    const branch = this.sessionManager.getBranch();
    for (let i = branch.length - 1; i >= 0; i--) {
        const entry = branch[i];
        if (entry.type === "custom" &&
            entry.customType === GOAL_STATE_CUSTOM_TYPE &&
            isPersistedGoalState(entry.data)) {
            return normalizeGoalState(entry.data);
        }
    }
    return emptyGoalState();
}

```

If no persisted state is found, the session initializes an empty goal state. This logic is located in [`packages/coding-agent/src/core/agent-session.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/core/agent-session.ts) (lines 1475-1488).

## Seeding Initial Goals with CLI Flags

When starting a top-level session from the command line, use the `--goal` flag to seed an initial objective. The constructor checks `_isBranchSeedable()` to ensure the branch contains only bootstrap entries (`model_change`, `thinking_level_change`, `service_tier_change`) before creating the goal:

```typescript
if (this._rlmDepth === 0 && config.initialGoal && this._isBranchSeedable()) {
    this._goalState = this._startGoal(config.initialGoal.objective, config.initialGoal.tokenBudget);
    this._pendingNextTurnMessages.push(createGoalContextMessage(this._goalState, "continuation"));
}

```

This safety check (found in [`packages/coding-agent/src/core/agent-session.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/core/agent-session.ts) lines 1228-1233) prevents duplicate goal creation when resuming an existing session.

## Updating and Managing Goal State

All goal lifecycle operations—`goal.complete`, `goal.update`, and `goal.abort`—funnel through `AgentSession._setGoalState()`. This method normalizes the state, updates timestamps, optionally persists to storage, and emits a `goal_update` event:

```typescript
private _setGoalState(next: GoalState, options: { persist?: boolean } = {}): void {
    const normalized = normalizeGoalState({ ...next, updatedAt: Date.now() });
    this._goalState = normalized;
    if (options.persist !== false) this._persistGoalState(normalized);
    this._emitGoalUpdate();
}

```

Located in [`packages/coding-agent/src/core/agent-session.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/core/agent-session.ts) (lines 1443-1458), this centralized handler ensures consistency across all state transitions.

## Practical Code Examples

The following patterns demonstrate common workflows for managing persistent goals in Prime Agent:

```typescript
// 1️⃣ Create a new goal from the TUI
await session.prompt("/goal Implement user login with JWT");

// 2️⃣ Inspect the current persisted goal
const reply = session.handleGoalHostRequest("goal.get");
console.log(reply.goal?.objective);   // → "Implement user login..."

// 3️⃣ Update the objective mid-session
await session.prompt("/goal update Add refresh token support");

// 4️⃣ Mark the goal as complete from inside a tool
await session.prompt("/goal complete");

// 5️⃣ Restart the agent—the goal reloads automatically
const newSession = await AgentSession.create({ /* same session dir */ });
console.log(newSession.goalState.objective); // persists across restarts

```

The current goal is always accessible via `session.goalState`, and the `InteractiveMode` UI layer displays this context in the Goal context panel using `createGoalContextMessage()` from [`packages/coding-agent/src/core/goals.ts`](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/src/core/goals.ts).

## Summary

- **Create goals** using the `/goal` slash command or `handleGoalHostRequest("goal.create", ...)` API.
- **Persistence** works via `_persistGoalState()` writing `thread_goal_state` entries to the durable transcript through `SessionManager`.
- **Automatic reloading** scans transcript history via `_loadPersistedGoalState()` on every session start.
- **CLI seeding** with `--goal` only occurs when `_isBranchSeedable()` confirms a fresh session.
- **State updates** propagate through `_setGoalState()`, which normalizes data and emits update events.

## Frequently Asked Questions

### Where are Prime Agent goals physically stored?

Goals are stored as custom entries within the session's JSONL transcript file. The `AgentSession` class writes these entries with the type `"thread_goal_state"` using `SessionManager.appendCustomEntry()`, ensuring the data survives restarts and session clears.

### How does Prime Agent prevent goal duplication when resuming a session?

The `_isBranchSeedable()` method validates that the transcript branch contains only bootstrap entries (model changes, thinking level changes) before auto-seeding a goal from the `--goal` CLI flag. This prevents duplicate objectives from being created when reloading an existing session.

### Can I modify an existing goal without restarting the session?

Yes. Use the `/goal update <new objective>` command or invoke the host bridge API. Changes flow through `_setGoalState()`, which immediately persists the update via `_persistGoalState()` and broadcasts a `goal_update` event to listeners.

### What happens to my goal if the agent process crashes?

Goals remain intact because `_persistGoalState()` calls `SessionManager.flushNow()` to write entries to disk immediately upon state changes. When the agent restarts, `_loadPersistedGoalState()` retrieves the most recent `thread_goal_state` entry from the transcript branch.