# Manage session state, resumption, and forking

Resume known sessions, refresh changed evidence, and fork from an identified baseline.
Learn how session continuity differs from current workspace state and filesystem isolation. A cache TTL change illustrates targeted re-analysis, revision-specific test evidence, and verified handoffs for resumed, forked, or fresh sessions.

Author: LearningPathX Editorial Team
Content version: 1.0
Published: 2026-12-04T00:33:08.511301+00:00
HTML: https://learningpathx.com/material/CCAR-F/manage-session-state-resumption-and-forking.html

Knowledge domain: Agentic Architecture & Orchestration
Tags: Context Management / State Management / Evidence Validation

## Manage session state, resumption, and forking

## Learning objectives

By the end of this topic, you should be able to:

* Resume a specific investigation rather than accidentally selecting another conversation.
* Distinguish conversation continuity from current workspace state.
* Fork a checked analysis baseline without assuming filesystem isolation.
* Choose targeted re-analysis or a fresh, verified handoff when prior observations are stale.

## Identify the session you intend to continue

A saved session contains a record of conversation, tool observations and decisions. Resuming it can preserve useful continuity across work sittings. It does not recreate a live environment exactly as it was or make old observations current again.

The supplied CLI material distinguishes an explicit named or identified resume from continuing the most recent local conversation. For example, a named investigation can be selected with:

```bash
claude --resume oauth-migration
```

In the described interface, `--continue` selects the most recent session, while `--resume` without a target opens a selector. Check these forms against the installed CLI help rather than assuming that every resume form means "latest."

For a programmatic workflow, retain the actual session identifier returned by the supported SDK event or result. Check the release's field and option names. A display name, a worker identifier and a session identifier are not interchangeable. Associate sessions with the correct user, workspace and task; do not resume another user's conversation merely because its identifier is available.

## Restore history without trusting stale observations

A prior file read is evidence of the file at the time it was read. If another process changes the file, resuming the conversation does not update that observation. Re-read the changed files and the conclusions that depend on them.

Record the workspace location, revision or file fingerprints, previous findings and current changes. Confirm the active model, available tools and permission settings rather than assuming every historical setting can be restored. A retired model, provider-specific identifier or unavailable agent can change what continuation is possible.

A session checkpoint is also different from version control. Conversational recovery does not necessarily undo external commands, background edits or changes made outside that checkpoint system. Inspect the actual working tree and use an appropriate recorded baseline to recover files.

## Re-analyze the affected dependency path

Inform the resumed agent about specific changes: file paths, relevant differences, approved requirements and checks already rerun. "Continue" is weaker than "Re-read the changed cache implementation and its tests, then revisit the earlier TTL conclusion." The original source prompt is “I have updated src/main.py and tests/test\_main.py. Please re-read these files and update your analysis based on the changes.” It identifies concrete affected paths, but remains a request: actual current reads and any impacted callers are still required before changing conclusions.

Targeted re-analysis can reuse still-valid work while updating the affected dependency path. It should not assume that only the named lines matter: a changed return type can affect callers, tests and documentation. Conversely, restarting a complete repository exploration without a reason wastes effort and may discard useful checked findings.

Separate the status of old and new evidence. A test result from revision R7 cannot be reported as a passing test of R8\. If the current test has not run, state that explicitly rather than inheriting a historical success flag.

## Fork an analysis baseline deliberately

Forking creates a separate conversational branch from a selected saved baseline. The original and new branch need distinguishable session identities so each can be continued independently. This is useful when comparing two test strategies or refactoring approaches that should begin from the same established analysis.

The source uses the term `fork_session` alongside release-specific command and option variants. Confirm the supported interface before invoking it. Do not assume that a conceptual `fork` example is directly executable in every SDK.

A fork separates conversational evolution; it does not necessarily create a separate checkout. Parallel branches that edit the same files can still interfere. Use separate worktrees or another explicit ownership/isolation arrangement when independent editing requires it. Record the common starting revision and inspect the resulting changes before combining them.

Forks also inherit assumptions from their starting snapshot. They are not automatically clean-slate reviewers. Use a fresh context with an explicit evidence packet when avoiding those inherited conclusions is more important than preserving the history.

## Start fresh when a verified handoff is clearer

A fresh session can be preferable when old tool results dominate the history, the goal has changed or several old instructions conflict with the current task. Give it a structured summary containing the goal, current source versions, approved decisions, checked facts, unresolved issues and next action.

Verify that summary against the original evidence and current workspace. A shorter summary can omit an important exception; starting fresh does not repair an incorrect summary. Keep the original material accessible so the new session can inspect a deciding detail.

Persisting a progress file can support continuity without keeping all raw exploration in the active context. Protect its scope and audience: saved notes are neither a complete transcript nor an automatically authoritative source. Include enough provenance to distinguish a checked result from a proposed next step.

## Distinguish caching, freshness and context capacity

Prompt caching can reduce repeated processing of an eligible request prefix. Its lifetime and reuse depend on the configured service behavior. It does not fetch new file contents, update old tool results or expand the model's usable context without limit.

A stale observation remains stale even if no cache is used. A cache expiry does not itself invalidate every source fact. Decide what to re-read from changes in the task and evidence, not from a universal token-count or inactivity threshold copied from a particular product example.

When comparing continuation approaches, include any summarization call, subsequent input size and lost-detail risk. A compressed handoff may reduce later context use but does not establish a universal monetary saving or better accuracy for every task.

## Worked example: continue an investigation after a change

In this invented code review, session S1 inspected revision R7\. An approved change in R8 sets the cache TTL to 300 seconds instead of 600 and updates `src/cache.py` and `tests/test_cache.py`. The old report's test result applies only to R7.

A useful handoff for either a resumed or fresh session is:

```json
{
  "goal": "Review the cache TTL change without unrelated refactoring.",
  "previous_revision": "R7",
  "current_revision": "R8",
  "changed_files": ["src/cache.py", "tests/test_cache.py"],
  "approved_requirement": "TTL is 300 seconds in R8.",
  "historical_result": "Tests passed for R7; this is not an R8 result.",
  "unresolved": "Current implementation and tests still need inspection.",
  "next_action": "Read both changed files, inspect callers affected by TTL behavior, and run the relevant current tests."
}
```

The agent can preserve unrelated checked findings while replacing the old TTL assumption. If two branches compare unit-test and integration-test strategies, both should begin from R8 with the same approved requirement. Their summaries should identify the actual inspected revision and whether any tests ran.

A supported interim report is: "The earlier test result covers R7\. R8 requires a 300-second TTL; current validation is pending." Reporting the old pass as an R8 pass would misrepresent the evidence. This scenario is a teaching example, not an executed CLI session or repository test.

## Preserve exact selection, naming and identifier boundaries

The source's detailed account gives `--continue` as latest-directory continuation and targeted `--resume <name-or-id>` or bare `--resume`/interactive `/resume` as a selection path. Its later targeted-analysis section and final tip instead call bare `--resume` the latest-session command. Those statements conflict. Retain the detailed distinction and verify the actual installed interface and loaded identity rather than silently substitute unrelated latest history. A not-found or ambiguous selection remains an explicit unresolved outcome.

In the supplied naming snapshot, control/invisible characters are replaced by spaces, names are capped at 200 characters and a name empty after sanitation is rejected. Live duplicate names receive variants. A renamed, sanitized or similar display name is not an immutable identifier. Capture the accepted name and actual resolved session ID, then confirm the selected user's workspace/task. The source's exact empty-name and `No conversation found to continue` messages are interface-specific diagnostics, not proof a different session should be loaded. Two complete expected naming-transformation fixtures under that source rule are `{"raw_name":"audit\u0000notes","sanitized_name":"audit notes","status":"accepted_naming_shape"}` and `{"raw_name":"\u0000","sanitized_name":null,"status":"rejected_after_sanitization"}`. The second is rejected rather than saved as an empty name. These are illustrative transformed values, not observed CLI responses or a guarantee that a particular name resolves to the intended history. That source says local transcript files are saved continuously, allowing saved-history recovery after exit or /clear; it auto-generates a name from history when none is supplied. This concerns stored history, not restoration of live files. Its empty-name text is `That name is empty once invisible characters are removed. Usage: /rename <name>`. A not-found continuation in the actual current directory and rejected /rename remain explicit failures rather than reasons to substitute another conversation.

For a narrow editorial check of that length boundary, consider only nonempty, already sanitized ASCII names. The JavaScript expressions below specify each input string exactly; derive the length from the string, rather than accepting a separate caller-supplied length. This local shape check does not invoke the CLI or establish uniqueness, access, or the selected session identity.

| Exact teaching input construction | Derived ASCII characters | Expected local length-shape result |
| --- | --- | --- |
| `"n".repeat(199)` | 199 | Within the stated 200-character cap; actual client selection is still unchecked. |
| `"n".repeat(200)` | 200 | At the stated cap, included in this local shape; actual client selection is still unchecked. |
| `"n".repeat(201)` | 201 | Outside the stated cap; the actual client's overlong-name handling is unknown. |

These inputs are ASCII so their derived character counts are unambiguous for this illustration. The source does not establish whether a particular client rejects, truncates, or otherwise handles an overlong name; do not turn the third result into an invented CLI response. Retain the sanitation and empty-name fixtures above and verify the actual accepted name and resolved identity through the supported interface.

Running background entries can appear with a `bg` marker in the source picker, but are not directly resumed there. Its `claude agents` attach/management path or an appropriately stopped state is distinct from selecting saved history. Seeing `bg` neither means completion nor authorizes interrupting another operation; use only the actual supported authorized lifecycle action.

For the source SDK account, session ID can come from actual `ResultMessage.session_id`; the TypeScript init `SystemMessage` exposes it directly, whereas Python uses `SystemMessage.data["session_id"]`. These are source-version interface descriptions. Its mixed `query()`/`options`/messages/prompt forms are illustrative and not a universal tested signature. Capture a real returned ID, associate it with the intended user/workflow and pass it through the actual supported resume option. A variable named sessionId does not create identity. Worker continuation instead needs the actual returned `agentId` in its supporting interface. The source describes built-in Explore/Plan as one-shot without agentId and custom workers as an option for resumable work; do not invent an identifier or memory for a nonresumable worker. Fresh delegation, explicit inherited fork and supported worker resume have different input boundaries.

## Re-establish the effective environment

Historical model selection is subject to retirement, `availableModels`, actual launch `--model`/`ANTHROPIC_MODEL` overrides and provider-specific deployment resolution such as the source Amazon Bedrock or Google Cloud examples. Confirm the permitted available model actually selected. An override can change selection where supported; it grants no access and does not establish the same historical model executed.

The source custom-agent lookup checks the original trusted directory and then the resume directory. A missing definition can fall back to default tools/system prompt with a warning naming the missing agent. Its permission-mode account restores prior mode except plan and bypassPermissions, which reset to the default new-session mode. Treat those as source-client conditions and inspect actual definitions, trust, tools and effective permissions before relying on an old role's restrictions. Resume or fork cannot create new authority, and inherited context may contain sensitive inputs inappropriate for another worker. The saved custom-agent identity described by the source comes from `--agent` or the `agent` setting. When the definition cannot be resolved, its proposed explicit --agent replacement is a separate supported selection to inspect under actual task/policy, not proof the previous role returned or authority expanded.

Local transcript files do not implement cross-host continuity. The source proposes a `SessionStore` mirror of locally written history; a name alone proves neither implementation, synchronization, user identity/access nor concurrent-writer safety. Verify the actual accessible intended transcript/version and real storage/concurrency policy. A missing store, stale mirror or simultaneous writer conflict stays explicit rather than loading any available similarly named session. An alternative is a validated application-state packet with actual results, decisions, diffs, evidence references and gaps. Source TypeScript `listSessions()`/`getSessionMessages()` and Python `list_sessions()`/`get_session_messages()` are supported-interface retrieval examples, not proof any messages were retrieved here.

When diagnosing unavailable history or handing work to another worker or host, retain only the nonsecret workspace/project/account/worker identity needed to identify the intended context. If credential context is relevant, record the credential identity or an approved secret-store reference, not actual keys, tokens, or passwords in prompts, logs, or handoffs. Knowing a session ID, path, or secret reference does not authorize retrieving a secret or accessing the referenced history. Sharing configuration does not by itself authorize sharing or using credentials. Use only the permitted identity and access context; otherwise preserve the blocked state and the required authorized next action rather than silently switching accounts or widening permissions.

## Keep branching and recovery interfaces separate

A session branch copies the selected parent's baseline at the moment of branching and gets its own actual ID; branch creation leaves the parent's existing history/identity unchanged. The parent can legitimately continue afterward. New observations do not automatically merge between the two evolving histories, and a distinct ID alone proves neither correct baseline nor completed exploration. A fresh reviewer differs because it need not inherit the parent's prior assumptions; isolated intermediate worker outputs do not imply isolated input history for an explicit fork. In the source context-isolation account, intermediate worker tool calls stay in the worker and the final message returns to the parent; this is not live shared memory or filesystem isolation. More specifically, the source branch-point copy includes parent conversation history, system prompt, tool context and historical model configuration. Actual model availability, definition lookup and effective permissions still need the separate checks above.

For the CLI (Command Line Interface), SDK and Agent-tool surfaces, the source interactive Agent `fork` type and default fork-mode account are distinct from explicit `/subtask`, its historical `/fork` command in v2.1.161–v2.1.211, SDK per-query fork/fork\_session terminology and launch `--fork-session`. Its `CLAUDE_CODE_FORK_SUBAGENT=1/0` controls the described fork-mode availability rather than every SDK's branching call. The background panel/final-result behavior belongs to that source interface. Confirm actual flags, request/response shapes and support rather than combine these into one executable universal signature. Its concrete interactive example is `/subtask Draft comprehensive test cases for the auth module`; the source says explicit /subtask can start that side task regardless of the automatic fork-mode toggle, names it from its first task words and returns its final result from the background panel. This source-client behavior is not permission to bypass task/access restrictions. In the source SDK scenario, an original JWT-analysis session supplies the captured session\_id, the OAuth2 alternative uses per-query `options={"fork":True,"session_id":session_id}`, and the actually returned forked\_id is retained separately; continuing JWT work uses the original session\_id. One listing uses `await client.query(prompt=..., options=...)`, another `client.query(messages=..., options=...)`. Those are quoted source-shape fragments, not complete or cross-version verified Python/TypeScript calls; even the source forkedId/forked\_id naming differs.

Conversational branches can still edit the same files. Before independent editing, inspect each actual checkout/worktree, shared paths and effective access; use a real isolated worktree or explicit ownership where required. In the source launch account, `--fork-session` starts from the launch directory and leaves the original worktree untouched. A deleted worktree can produce a notice, clear the binding and fall back to the launch directory; missing/untrusted Git metadata can prevent re-entry, including a missing HEAD/base-branch case. These are scoped recovery descriptions, not proof a particular current branch has a valid checkout. Inspect actual resulting paths/bytes and do not assume that inherited permissions or a recovered transcript isolate file effects. One source no-commits/base-branch example reports `Failed to resolve base branch "HEAD": git rev-parse failed`. Diagnose actual repository/metadata state rather than assuming every similarly worded failure has that one cause or authorizes worktree repair.

Here SKILL refers to a `SKILL.md` definition with YAML frontmatter and Markdown under `.claude/skills`; its terminology identifies the checkpoint example without adding skill-authoring objectives. The source checkpoint account covers a foreground skill with `context: fork` and `background: false`, while background subagent/default forked-skill edits are outside that described rewind coverage. This is separate from restoring a transcript. Inspect actual affected files and select an authorized checkpoint/version-control/manual recovery using its recorded baseline; verify resulting bytes. No arbitrary revert or successful rollback is authorized or proved by a session-resume command.

## Save a complete, inspectable continuation packet

The cache example above is invented and its R7/R8 results are scenario premises rather than executed tests. One extended teaching continuation packet is:

```json
{
  "goal": "Review only the R8 cache TTL change and affected behavior.",
  "session_baseline": {"parent": "S1", "previous_revision": "R7", "current_revision": "R8"},
  "actual_progress_in_scenario": "The prior R7 review exists in the scenario; current R8 file inspection and tests remain pending.",
  "decisions": ["Use the approved 300-second TTL requirement.", "Retain unrelated findings only if their inputs remain unchanged."],
  "evidence_locations": [
    {"path": "src/cache.py", "revision": "R8", "status": "requires current read"},
    {"path": "tests/test_cache.py", "revision": "R8", "status": "requires current read and actual test"},
    {"path": "historical R7 review", "revision": "R7", "status": "scenario premise; not evidence of an R8 pass"}
  ],
  "changed_state": {"ttl_requirement_seconds": 300, "previous_requirement_seconds": 600},
  "unresolved": ["Current implementation, affected callers and current test outcomes are unverified."],
  "next_action": "Read changed code and tests, inspect affected callers, compare current evidence to the approved requirement, then run authorized current checks."
}
```

In a real continuation, save the actual packet to a permitted accessible location and identify its revision/time/evidence; the receiving context must actually retrieve it and recheck critical current inputs. A filename such as NOTES.md does not deliver memory by itself. Omitted detail leaves active context, but the original transcript or evidence artifact can remain available for a deciding question; preserve its retrievable reference. A concise summary is not automatically current or self-verifying. The source NOTES.md demonstration records “for the last 1,234 steps I have been training my Pokémon in Route 1”, resets context and then actually reads the note into the new session. The count and game state are illustrative source content, not this investigation's progress or a universal memory limit; the stored note still needs relevant current evidence checks.

## Separate cache, UI and evidence conditions

Prompt caching applies to eligible reusable request prefixes under actual supporting breakpoints/lifetime rules, which the source describes for tools, system, messages and eligible thinking blocks. Its short/extended examples include 5 minutes and 1 hour, with an illustrative `cache_control` ephemeral `ttl: "1h"`. A warm prefix can still contain an outdated file fact, while expiry alone does not invalidate an unchanged fact. Historical storage, logical evidence freshness and prompt-cache reuse are different mechanisms. Its complete illustrative cache fragment is `{"cache_control":{"type":"ephemeral","ttl":"1h"}}`. This is a supporting-API fragment, not a complete request or a universal setting for every saved session.

The source summary dialog is an interface example requiring both inactivity over one hour and history over 100,000 tokens. Under that stated strict conjunction, 59 minutes/100,001 tokens, exactly 60 minutes/100,001 and 61 minutes/exactly 100,000 do not meet it; 61 minutes/100,001 does. Unknown time/size cannot establish eligibility. This is not a universal cache-expiry or evidence-validity law. For this teaching threshold check, inactivity is a nonnegative finite duration in minutes and history size is a nonnegative integer token count, excluding booleans. Zero minutes or zero tokens is valid but does not trigger the dialog. Negative values, a boolean or numeric string, and a fractional token count are invalid inputs rather than evidence of eligibility; missing inputs remain unknown. The real client still needs its actual clock/measurement contract.

Its “Resume from summary” runs one full-history `/compact` summarization request, then keeps the summary, recent exchanges and up to five recently read files in later active context. “Resume full session as-is” retains history; “Don't ask me again” retains full history and suppresses later such dialogs. Account the initial full-history compaction cost before comparing later reduced requests. Omitted information is no longer in that active summary context, not proved deleted from every original transcript/artifact store.

Read actual metrics in their supported units: input/output tokens describe different request categories; cache-creation/write and cache-read tokens describe reuse activity. The source `cache_creation_input_tokens` equals its `ephemeral_5m_input_tokens` plus `ephemeral_1h_input_tokens` write categories; for an illustrative 2,000 + 1,000 token write this is 3,000 tokens. It is not a dollar amount or proof a tool executed freshly. A high input/output ratio can reflect a large correct source or reusable prefix; repeated old steps, latency and old-file references motivate diagnosis but do not establish staleness from one ratio. Pricing and total resource/cost comparisons need the actual category/model/rate/workload basis, including compaction and retries. Source automatic server-tool cache-write claims likewise require actual supported metrics; cached bytes are not current facts. Concretely, the source names web search and unrequested ephemeral\_5m\_input\_tokens writes as an automatic server-tool caching example. Interpret that report only under the actual API/tool metrics; the write counter alone is not proof the source stayed fresh or that every web-search implementation has that behavior.

For its thinking-retention matrix, the source describes prior thinking blocks stripped after non-tool-result user blocks on earlier Opus/Sonnet and all Haiku models in that source account, versus retention by default on Opus 4.5+/Sonnet 4.6+. Keep the actual model/version/message-trigger/cache-support qualifiers; this is neither current-product verification nor access to private reasoning. Cached protocol blocks and model conclusions still require the task's actual evidence checks.

Choose targeted re-analysis when earlier inputs remain valid: provide actual changed paths/diffs and reread necessary current callers/tests before replacing dependent conclusions. Widespread changes may justify a fresh validated packet or isolated investigator with sufficient evidence. Neither a requested reread, a copied summary nor a new session establishes that the refreshed investigation or current tests actually completed.

## Summary

Resume a known session when its context remains useful, re-read changed evidence and track the revision behind each result. Fork to explore a shared baseline, with separate file isolation when needed. Start fresh with a verified summary when that gives a clearer state; neither a saved conversation nor a cache guarantees freshness.
