How Persistent Goal Tracking Functions Across Terminal Sessions in Prime Agent
Persistent goal tracking works by serializing the current GoalState as a custom JSONL entry (thread_goal_state) to a per-directory session file, then rehydrating that state when a new terminal session starts in the same working directory.
Prime Agent, an open-source coding agent from PrimeIntellect-ai, maintains continuity for user goals even across terminal restarts. Rather than storing goals in ephemeral memory, the system uses a durable session file format that persists to disk after every turn. This ensures that long-running objectives, token budgets, and completion status survive process termination.
Session File Architecture and Storage Location
Prime Agent stores session data in JSONL (line-delimited JSON) files located under the user's home directory. The exact path follows a hashing scheme based on the current working directory:
~/.pi/agent/sessions/<cwd-hash>.jsonl
This design isolates sessions per project directory, allowing independent goal tracking across multiple codebases.
The SessionManager class in packages/coding-agent/src/core/session-manager.ts handles all read/write operations. It appends entries atomically and provides compaction utilities to prevent unbounded file growth.
Goal State Serialization with createGoalContextMessage
When you create a goal using the /goal command, the GoalState object is constructed with fields like:
objective: The human-readable goal descriptiontokenBudget: Maximum tokens allocated to the goalstatus: One of"active","complete", or"abandoned"tokensUsed: Running counter of consumed tokenscreatedAt/updatedAt: Timestamps for tracking
The function createGoalContextMessage() in packages/coding-agent/src/core/goals.ts (around line 154) wraps this state into a custom entry:
// Simplified representation of the custom entry structure
{
"type": "custom",
"customType": "thread_goal_state",
"content": {
"objective": "write a summary of the latest PR",
"tokenBudget": 50,
"status": "active",
"tokensUsed": 0,
"updatedAt": "2025-01-15T09:23:17Z"
},
"timestamp": "2025-01-15T09:23:17Z"
}
This entry is appended to the session file after each turn where the goal state changes.
Session Rehydration on Terminal Restart
When Prime Agent launches in a directory with an existing session file, the AgentSession class in packages/coding-agent/src/core/agent-session.ts performs rehydration:
- Locate session file: Uses
SessionManagerto find the most recent session for the current working directory - Scan for latest goal state: Reads the JSONL file backwards to find the most recent
thread_goal_stateentry - Reconstruct
GoalState: Deserializes the entry into an in-memoryGoalStateobject - Inject continuation message: Calls
createGoalContextMessage(this._goalState, "continuation")to prepend context to the first turn
This logic appears around line 1348 in agent-session.ts, where the restored goal state is pushed onto _pendingNextTurnMessages before any user interaction.
Complete Goal Lifecycle Example
# Terminal Session 1: Create a goal
$ cd ~/my-project
$ prime-agent
> /goal create {"objective":"Refactor auth middleware to use JWT","tokenBudget":200}
Goal created: "Refactor auth middleware to use JWT" (budget: 200 tokens)
> /goal status
Status: active | Used: 0 / 200 tokens
# Work on the goal... then close terminal
^D
# Terminal Session 2: Resume automatically
$ cd ~/my-project
$ prime-agent
# Goal state restored from ~/.pi/agent/sessions/<hash>.jsonl
> /goal status
Status: active | Used: 47 / 200 tokens # Previous progress preserved
> /goal finish
Goal marked complete. Final usage: 125 tokens
# Persistence continues: completed goals remain queryable
$ prime-agent
> /goal history
- [2025-01-15] "Refactor auth middleware to use JWT" — complete (125 tokens)
Key Implementation Files
| File | Purpose | Direct Link |
|---|---|---|
packages/coding-agent/src/core/goals.ts |
GoalState interface, createGoalContextMessage() builder |
source |
packages/coding-agent/src/core/agent-session.ts |
Session lifecycle, goal rehydration on init | source |
packages/coding-agent/src/core/session-manager.ts |
JSONL file I/O, compaction, atomic writes | source |
scripts/session-transcripts.ts |
Debug utility to extract and inspect session content | source |
scripts/session-context-stats.mjs |
Analytics for goal distribution and token usage across sessions | source |
Comparison: In-Memory vs. Persistent Goal Tracking
| Approach | Behavior on Terminal Exit | Use Case |
|---|---|---|
| In-memory only | Goal state lost | Ephemeral tasks, single-session workflows |
| Prime Agent's persistent tracking | Goal state restored from thread_goal_state entry |
Long-running objectives, multi-day projects, team handoffs |
The persistent approach enables workflows like:
- Checkpoint resume: Close laptop, reopen later, continue same goal
- Cross-terminal coordination: Multiple terminal windows share state via the same session file
- Audit and accountability: Completed goals with token usage remain queryable via
/goal history
Summary
- Storage mechanism: Per-directory JSONL session files under
~/.pi/agent/sessions/ - Serialization:
GoalStatewrapped inthread_goal_statecustom entries viacreateGoalContextMessage() - Persistence trigger: Appended after each turn by
AgentSession - Recovery: Scanned and rehydrated on session initialization in
agent-session.ts - Durability guarantees: Atomic appends and compaction prevent data loss even on crash
Frequently Asked Questions
How does Prime Agent prevent goal state corruption if the terminal crashes?
The SessionManager uses atomic append operations to write JSONL entries. Each entry is a complete, self-contained line—there are no partial writes that could corrupt the file structure. On rehydration, the parser reads line by line and ignores malformed entries, falling back to the last valid thread_goal_state.
Can I manually inspect or migrate goal data between machines?
Yes. Session files are plain JSONL. You can copy ~/.pi/agent/sessions/ to another machine, or use the session-transcripts.ts script to export readable transcripts. The session-context-stats.mjs utility also provides aggregated views of goal history and token consumption.
What happens if I run Prime Agent in two terminals simultaneously in the same directory?
Both instances read from the same session file but do not coordinate writes. The last process to append an entry wins. For active goal modifications, this creates a last-write-wins scenario. For read-only goal queries, both sessions see consistent state. To avoid conflicts, Prime Agent is designed primarily for single-terminal-per-directory usage.
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:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →