I need to understand both issues before we brainstorm. Let me fetch them from Linear.
Assistant
Good, I have both issues. Now let me understand the current codebase to ground this brainstorm properly.
Assistant
Good, I have a solid understanding of both issues and the current codebase. Let me now synthesize what I've learned and present the brainstorm.
Brainstorm: ENT-221 + ENT-194 — State Tracking for Mid-Session Commits
The Core Problem
Both issues describe the same fundamental gap: the manual-commit strategy assumes a linear flow of UserPromptSubmit → agent work → Stop → user commits, but agents (especially Claude) can commit mid-conversation via Bash, breaking this assumption.
What happens today:
code
UserPromptSubmit → Agent works → Agent commits via Bash → Agent continues → Stop
↓ ↓ ↓
Session state prepare-commit-msg fires SaveChanges creates
initialized post-commit fires: checkpoint on shadow
(no shadow - condenses (empty shadow!) branch, but BaseCommit
branch yet) - resets CheckpointCount=0 is now wrong (HEAD moved)
- deletes shadow branch
- updates BaseCommit
Result: The condensed checkpoint has no/incomplete transcript. The post-Stop checkpoint may be orphaned or reference a stale base. The user loses session data.
ENT-194 specifically
When an agent does sequential commits in a single turn:
First commit triggers post-commit → condenses whatever exists (maybe nothing on shadow branch yet)
Second commit triggers post-commit again → condenses again (empty again)
Stop fires → creates checkpoint, but BaseCommit has shifted twice
ENT-221 specifically
Asks whether we need cross-hook state tracking — a way for hooks to know "we're in the middle of an agent session, don't condense yet."
Key Design Questions
Before proposing solutions, I want to surface some questions and tradeoffs:
Assistant
Got it — you're on board with deferring condensation until Stop. What would you like to clarify on the remaining questions? Or do you have additional context/constraints I should factor in?
User
are there any problems with concurrent access of the state file?
Assistant
Great question — this is critical if we're adding a phase/active flag that hooks will read. Let me check the current implementation.
Assistant
Yes — this is the right thing to worry about. Let me break down the concurrent access situation.
Current state: atomic writes, but no locking
Save() at state.go:170 does an atomic write (write to .tmp, rename), which prevents partial reads. But there's no protection against read-modify-write races — two processes could both Load(), modify independently, and Save(), with the second overwriting the first's changes.
Does this race actually happen today?
For a single session, the hooks are effectively sequential:
Each hook is a separate process, but git runs them sequentially, and the Bash call blocks until git commit returns. So no overlap within a single session.
For concurrent sessions (two agents, same directory), they have different session IDs → different state files → no conflict on writes. But PostCommit() calls ListForWorktree() which scans all state files — it could see a stale snapshot of another session's state. Low impact since it's just deciding whether to condense.
The real problem for the proposed "active" flag
The race condition isn't the concern. The concern is stale state on crash:
UserPromptSubmit sets active=true
Agent crashes / user kills terminal / network drops
Stop never fires → active=true forever
Next time user commits manually → post-commit sees active=true, defers condensation indefinitely
This means any detection mechanism needs a staleness check.
Assistant
Great question. Let me think through the checkpoint ID lifecycle across hooks in the deferred model.
The challenge
Today checkpoint IDs are ephemeral — generated in prepare-commit-msg, consumed in post-commit, done. With deferred condensation, we need the ID to survive across multiple commits and the eventual condensation.
Proposed flow
code
Agent commit #1:
prepare-commit-msg → generates checkpoint ID "abc123",
stores in state.PendingCheckpointID,
adds trailer to commit
post-commit → sees session is active → SKIPS condensation
(shadow branch + state preserved)
Agent commit #2:
prepare-commit-msg → reads state.PendingCheckpointID ("abc123"),
REUSES it, adds same trailer
post-commit → still active → skips again
Stop hook fires:
SaveChanges → writes final checkpoint to shadow branch
(full transcript, all files from entire session)
User commits manually:
prepare-commit-msg → session inactive, has PendingCheckpointID →
reuses "abc123", adds trailer
post-commit → session inactive → condenses from shadow branch
to entire/sessions at shard abc123
Clears PendingCheckpointID, sets LastCheckpointID
Key: one checkpoint ID per session-commit-cycle. All agent commits + the user's final commit share the same ID, pointing to one metadata entry that covers the entire session.
What lives in session state
The new/modified fields would be:
go
Assistant
Good point — let me address that directly.
The actual concurrent access risk
The concern isn't two hooks for the same session racing (those are sequential within a git commit), it's:
Scenario A: User commits in another terminal while agent is mid-session
code
Terminal 1 (agent): Terminal 2 (user):
UserPromptSubmit → writes state
Agent working...
Agent calls `git commit`
prepare-commit-msg (proc A) User runs `git commit`
reads state prepare-commit-msg (proc B)
generates PendingCheckpointID reads state (SAME version)
writes state generates DIFFERENT ID
post-commit (proc A) writes state (OVERWRITES A's ID!)
reads state post-commit (proc B)
updates BaseCommit reads state
writes state updates BaseCommit
writes state (OVERWRITES again!)
Proc A and proc B are independent OS processes — git doesn't serialize commits across terminals. Both do read-modify-write on the same state file, and the atomic rename only prevents partial reads, not lost updates.
Scenario B: Agent does rapid sequential commits — not a problem, git hooks within one git commit are sequential, and Bash blocks until the commit completes.
Impact in the proposed model
The lost update could cause:
PendingCheckpointID overwritten — one commit's trailer points to a checkpoint ID that doesn't match what's in state
BaseCommit overwritten — shadow branch naming could be wrong
CheckpointCount wrong — if both incremented from the same base value
Mitigation: file locking
The simplest robust fix is flock around read-modify-write cycles:
This is cross-platform on macOS/Linux (where this CLI runs), adds minimal overhead, and fully prevents lost updates.
Assistant
Good. Let me now consolidate everything into a complete design summary.
Design Summary: Cross-Hook State Tracking for Mid-Session Commits
Problem Statement
When an agent commits via Bash mid-session, post-commit condenses prematurely (often with incomplete/no data), resets state, and deletes the shadow branch. Subsequent checkpoints in the same session are lost or broken.
Design Decisions
Decision
Choice
Condense timing
Defer — skip condensation for active sessions
Condense trigger
On user commit (current model), after session is inactive
Active detection
EndedAt + LastInteractionTime (PR #165) with TTL
Checkpoint ID
Single PendingCheckpointID shared across all commits in a session
type State struct {
// ... existing ...
// PendingCheckpointID is generated on the first commit in an active
// session and reused for all subsequent commits until condensation.
PendingCheckpointID id.CheckpointID `json:"pending_checkpoint_id,omitempty"`
}
Hook Behavior Changes
prepare-commit-msg (with locking):
Check if session is active (EndedAt==nil && LastInteractionTime recent)
If active + no PendingCheckpointID → generate one, save to state
If active + has PendingCheckpointID → reuse it
Add trailer with checkpoint ID (same as today)
post-commit (with locking):
Check if session is active
If active → update BaseCommit to new HEAD, migrate shadow branch. condensation, shadow branch deletion, resetting CheckpointCount
Assistant
Good call. Let me work through the full state machine, including multi-session.
Session Phase States
code
┌─────────────┐
│ (none) │ No state file exists
└──────┬──────┘
│ SessionStart
▼
┌─────────────┐
│ IDLE │ State file exists, agent not actively working
└──┬───┬───┬──┘
│ │ │
│ │ │ UserPromptSubmit
│ │ ▼
│ │ ┌─────────────┐
│ │ │ ACTIVE │ Agent is working (between UserPromptSubmit and Stop)
│ │ └──┬───┬───┬──┘
│ │ │ │ │
│ │ │ │ │ git commit (agent-initiated)
│ │ │ │ └──► ACTIVE (self-loop: update BaseCommit, migrate shadow, skip condense)
│ │ │ │
│ │ │ │ Stop (SaveChanges)
│ │ │ └──► IDLE (checkpoint written to shadow branch)
│ │ │
│ │ │ SessionStop (agent crashes / force-quit while active)
│ │ └──► ENDED
│ │
│ │ git commit (user-initiated, between turns)
│ └──► IDLE (condense from shadow → entire/sessions, update BaseCommit)
│
│ SessionStop
▼
┌─────────────┐
│ ENDED │ Session fully closed
└──────┬──────┘
│ git commit (user commits after session ended)
└──► ENDED (condense any remaining data, clean up)
Transition Table
Current State
Event
Action
Next State
(none)
SessionStart
Create state file
IDLE
IDLE
UserPromptSubmit
Set phase=ACTIVE, calculate attribution
ACTIVE
ACTIVE
Stop
Assistant
Great feedback — several important corrections. Let me verify the SessionStart behavior and then revise the state machine.
Assistant
Confirmed — you're right. SessionStart does NOT create the state file. It only outputs a message and writes current-session.txt. The state file is created on UserPromptSubmit via InitializeSession().
Let me also check what claude -r (resume) looks like from the hooks' perspective.
Assistant
Good catches. Let me revise the state machine based on all your feedback.
Revised State Machine
Terminology note: I'm using "step" for ephemeral shadow branch checkpoints (what CheckpointCount tracks) and "checkpoint" for the permanent data on entire/checkpoints/v1.
code
Assistant
Two important additions:
ACTIVE_COMMITTED → IDLE condenses immediately at Stop — this makes sense. The agent's commits already exist on the branch; no reason to wait. So the rule becomes:
ACTIVE → IDLE (no mid-session commits): wait for user commit (current behavior)
ACTIVE_COMMITTED → IDLE: condense now, during Stop
All active sessions included in condensation — even sessions with no file changes get their transcript/context captured. Full picture of what was happening.
Remove current-session.txt mechanics — agreed, it's meaningless in multi-session world.
Let me update the state machine with these corrections, then write the plan.
Final State Machine
code
UNINITIALIZED ──UserPromptSubmit──► ACTIVE
ACTIVE ──Stop──► IDLE (no mid-session commits)
ACTIVE ──git commit──► ACTIVE_COMMITTED (agent committed)
ACTIVE_COMMITTED ──git commit──► ACTIVE_COMMITTED (more commits)
ACTIVE_COMMITTED ──Stop──► IDLE + CONDENSE (condense immediately!)
IDLE ──git commit──► IDLE + CONDENSE (user commit triggers condense)
IDLE ──UserPromptSubmit──► ACTIVE (next turn)
IDLE ──SessionStop──► ENDED
ENDED ──git commit──► ENDED + CONDENSE (remaining data)
ENDED ──SessionStart+UserPromptSubmit──► ACTIVE (resume, clear EndedAt)
TIMED_OUT (virtual) ──treated as ENDED──
I'll proceed to write the formal implementation plan now.
Assistant
I have extensive context from the brainstorm. Let me do targeted exploration of the specific code paths I'll need to modify, then design the plan.
Assistant
Good point — subagents add another dimension. Let me check how they currently interact with the session lifecycle.
Assistant
Good point. Subagents fit into the model like this:
Subagents run during ACTIVE state — they're spawned by the main agent within a turn
They write to the same shadow branch via SaveTaskCheckpoint() (same session state, same FilesTouched)
Multiple subagents can run concurrently — making the flock locking critical (multiple SaveTaskCheckpoint calls racing on the same state file)
Subagents CAN trigger git commits — same mid-session commit problem as the main agent
So subagents don't need their own phase in the state machine — they operate within ACTIVE. But they're the strongest motivation for the flock locking, since concurrent subagents are a real (not theoretical) race condition.
Now let me design the full implementation plan. I have all the context I need.
Assistant
Good. Let me verify a few implementation details before writing the final plan.
Assistant
Now I have a complete picture. Let me write the final plan.
Assistant
The plan covers all the decisions from our brainstorm including:
Phase state machine with ACTIVE, ACTIVE_COMMITTED, IDLE, ENDED
ACTIVE_COMMITTED → IDLE triggers immediate condensation at Stop
flock-based file locking for concurrent safety (subagents, multi-terminal)
PendingCheckpointID shared across all commits in a session
Shadow branch preserved while any session is ACTIVE
current-session.txt removal
Backward compatibility (empty phase = IDLE)
Regarding your question about subagents: they operate within the ACTIVE phase and write to the same shadow branch via SaveTaskCheckpoint(). The locking (Step 6) is critical for them since multiple subagents can call SaveTaskCheckpoint() concurrently, racing on the same state file. No separate subagent phases are needed — they're just concurrent writers within an ACTIVE session.
Assistant
Good questions. Let me check entire reset (the rewind reset command) and think through the stash/reset scenarios.
Assistant
entire reset and Session Phase
entire reset does:
Finds shadow branch for current HEAD (entire/<HEAD[:7]>-<worktreeID[:6]>)
Finds all session states where BaseCommit == HEAD
Deletes each session state file
Deletes the shadow branch
Impact on our model:entire reset nukes everything — state files, shadow branch, all phases. This is fine for IDLE/ENDED sessions. But if called while a session is ACTIVE or ACTIVE_COMMITTED:
The agent is still running, will try to SaveChanges later
SaveChanges will fail to find the session state → it falls back to initializeSession() (line 176 of manual_commit_git.go)
So it self-heals, but loses all previous checkpoint data
We should add a guard: if any session on the shadow branch has phase ACTIVE or ACTIVE_COMMITTED, warn/refuse unless --force.
git reset --hard or git stash while IDLE
Neither operation fires any git hooks (no prepare-commit-msg, post-commit). So the session phase stays IDLE and nothing happens until the next UserPromptSubmit.
git stash (no HEAD change):
Working directory cleaned, but HEAD unchanged
Shadow branch + session state untouched
git stash pop restores files
Next UserPromptSubmit: no migration needed (BaseCommit matches)
Safe. Data preserved.
git reset --hard (to HEAD, no target):
Cleans working directory to HEAD state
HEAD unchanged → no migration
Agent's uncommitted changes gone from working directory, but still on shadow branch
On next UserPromptSubmit → migrateShadowBranchIfNeeded() detects HEAD change
Migration renames shadow branch: →
Assistant
Now let me also add a test scenario for the reset case and clean up the integration test list.
Assistant
The plan now covers both edge cases. To summarize what I found:
entire reset — currently nukes everything. We should add a guard that refuses to reset while any session is ACTIVE/ACTIVE_COMMITTED (unless --force).
git stash while IDLE — safe, no hooks fire, no HEAD change.
git reset --hard while IDLE — working directory changes but shadow branch preserves data. Next UserPromptSubmit handles migration if HEAD changed.
git reset --hard <older> while ACTIVE_COMMITTED — the riskiest case. Our new post-commit (Step 4) handles this because it calls migrateShadowBranchIfNeeded() as part of the "update BaseCommit" logic for active sessions.
Shadow branch collision on backward reset — pre-existing issue, out of scope for this PR.
Assistant
Right — Ctrl-C (SIGINT) likely kills the agent process before SessionStop can fire. Let me verify what Claude Code does on SIGINT.
Assistant
Correct. Claude Code has a SessionEnd hook, but on Ctrl-C (SIGINT) or terminal close, there's no guarantee it fires. The session would be stuck in ACTIVE or ACTIVE_COMMITTED until the TTL expires.
Impact of being stuck in ACTIVE:
User commits → post-commit sees ACTIVE → skips condensation → user's commits have no metadata linked
This continues until LastInteractionTime exceeds TTL
The 30-minute TTL is too long for this. An agent that's genuinely working interacts every few seconds (tool calls, saves). If it's been 2+ minutes with no interaction, the session is almost certainly dead.
Proposed refinement: Use a tiered TTL:
Post-commit context (git hooks): 2-minute TTL. If LastInteractionTime > 2 min and phase is ACTIVE, treat as TIMED_OUT. This gives fast recovery after Ctrl-C while avoiding false positives (agents are chatty).
UserPromptSubmit context (new session starting): 30-minute TTL for cleanup of other sessions. More conservative since it's just housekeeping.
Additionally, we could add a cleanup sweep on UserPromptSubmit: when any session starts, scan other sessions in the same worktree and clean up stale ACTIVE phases. This provides natural garbage collection.
Assistant
What would you like to clarify about the Ctrl-C recovery approach?
User
there are some different possibilities here I think:
the ctrl-c when the agent is active, then you get:
code
❯ hello
⎿ Interrupted · What should Claude do instead?
essentially it's back to IDLE. I don't think there's a hook we can tap into for this (there may be an open Issue on claude code)
2) claude process is terminated - then we're in the tiered TTL world - though if we tap into the general tool use hooks we should see activity still, pushing out the ttl - or perhaps we're stuck on a permission request...
Assistant
Good distinction. Two separate scenarios with different characteristics:
Scenario 1: Ctrl-C interruption (agent survives)
Agent is back at prompt, session alive, but no hook fires
Session stuck in ACTIVE even though agent is idle at the prompt
If user types another prompt → UserPromptSubmit fires → transition works fine
If user commits immediately → post-commit sees ACTIVE → skips condensation (wrong)
No known hook for this. The data is safe on the shadow branch — it just won't condense until either the next Stop or the session truly ends
Scenario 2: Process killed (agent dies)
No hooks fire at all
TTL-based recovery kicks in
But: agent might be alive but blocked on permission prompt → looks inactive but isn't
Or: subagent/tool use hooks push out LastInteractionTime → TTL stays fresh even if main agent is idle
For scenario 2, the permission prompt case is interesting — the agent is alive and waiting for user input. If we set a 2-min TTL, a user who walks away from a permission prompt for 3 minutes then comes back and commits would get false-positive TIMED_OUT. But that's probably fine — condensation would happen, and the data is correct (the session was effectively idle during that time).
For scenario 1, I think the honest answer is: this is a gap we accept for now and track as a known limitation. The data is preserved (shadow branch), it just won't condense on that immediate commit. It'll condense on the next commit after Stop fires or the session ends.
Let me update the plan.
Assistant
Let me think through this systematically — checking each event against each phase for gaps:
Events we haven't discussed:
git rebase during ACTIVE session — prepare-commit-msg already skips during sequence operations (rebase, cherry-pick, revert). post-commit fires for each rebase-created commit though. With our changes, post-commit sees ACTIVE → transitions to ACTIVE_COMMITTED → migrates shadow branch per commit. After rebase completes, shadow branch is at the new HEAD. Seems fine, but many rapid shadow branch migrations could be noisy.
git rebase --abort after partial rebase — HEAD resets to pre-rebase state. No hooks fire on abort. Session state has updated BaseCommit from the partial rebase commits. On next UserPromptSubmit, migration detects HEAD change and renames shadow branch back. Works.
False-positive TIMED_OUT on permission prompts — Agent is alive but waiting for user to approve a tool use. LastInteractionTime is stale (> 2 min). User commits in another terminal → post-commit falsely treats as TIMED_OUT → condenses prematurely. Agent continues → SaveChanges creates new shadow branch, data accumulates fresh. Result: session data is split across two condensations. Not ideal but not data loss.
User removes trailer from commit while session is ACTIVE — prepare-commit-msg adds it, user deletes it in editor. post-commit checks for trailer, doesn't find one, exits without doing anything. Session stays ACTIVE. PendingCheckpointID preserved for next commit. Works correctly.
SaveChanges with no file changes — Agent ran but only chatted, no file modifications. Shadow branch commit still created with metadata. Condensation still captures transcript. This matches the design intent ("include all sessions even without file changes").
Auto-commit strategy — Phase field exists on session.State which both strategies share, but auto-commit ignores it. Our changes only modify manual-commit code paths. Auto-commit is unaffected.
I think the main notable gap is #3 (false-positive timeout on permission prompts). The impact is a split in session data — not data loss, just two condensation events instead of one. Given that permission prompts rarely exceed 2 minutes, and the fallback is graceful, I think it's acceptable.
Everything else looks covered. Let me finalize the plan.
Assistant
Also adding a note about rebase behavior since that's a non-obvious interaction:
Assistant
I believe we've covered all the meaningful edge cases. The plan documents:
Normal flow: ACTIVE → git commit → ACTIVE_COMMITTED → Stop → condense
User operations in IDLE: stash (safe), reset (migration handles it)
Yes — that's a useful recovery signal. If UserPromptSubmit fires and the session is already ACTIVE or ACTIVE_COMMITTED, we know the previous turn ended without a proper Stop. That means:
ACTIVE → UserPromptSubmit: Previous turn was interrupted (Ctrl-C) or Stop hook failed. The live transcript has uncaptured content from that turn.
ACTIVE_COMMITTED → UserPromptSubmit: Same, but the agent also committed during the interrupted turn. Shadow branch may have partial data but the final portion is uncaptured.
Recovery action: Before transitioning to ACTIVE for the new turn, we can do a catch-up checkpoint — read the live transcript from the last known position, create a shadow branch checkpoint for the interrupted turn's data. This ensures the interrupted turn's transcript is preserved.
code
UserPromptSubmit:
if phase == ACTIVE or ACTIVE_COMMITTED:
// Previous turn didn't complete properly
// Do catch-up: read transcript from CondensedTranscriptLines,
// create shadow branch checkpoint with whatever content exists
catchUpCheckpoint(state)
// Now start the new turn
phase = ACTIVE
calculate attribution
...
This doesn't fix the "user commits immediately after Ctrl-C" case (no UserPromptSubmit fires between interrupt and commit), but it ensures that if the user continues using the agent, the interrupted turn's data is captured before the new turn begins.
Assistant
Also update the Ctrl-C limitation section since this partially mitigates it:
Assistant
Good, I see the format. Let me read the current plan file and write it to the repo.
Assistant
Written to docs/plans/2026-02-06-session-phase-state-machine.md. What else did you want to discuss?
User
another couple of scenarios:
user chats with claude, creates some stuff - wants to bail. Closes claude, git restore, opens a new claude -> what happens now?
user chats with claude, creates some stuff - wants to bail. git restore, forgets they have claude open, opens a new claude -> what happens now?
Assistant
Good scenarios. Let me trace through both:
Scenario 1: Close Claude → git restore → new Claude
code
1. User works with Claude (turns happen: ACTIVE → IDLE → ACTIVE → IDLE)
Shadow branch has checkpoints with file changes
2. User closes Claude → SessionStop → Phase = ENDED, EndedAt set
3. User does `git restore .` → no hooks fire, working directory reset to HEAD
4. User opens new Claude → new session ID
→ SessionStart (informational only)
→ UserPromptSubmit → new session initialized, Phase = ACTIVE
State:
Old session: ENDED, CheckpointCount > 0, shadow branch has stale file data
New session: ACTIVE, same BaseCommit (HEAD unchanged), shares shadow branch
When user eventually commits:
post-commit sees old session (ENDED) → condenses it. The shadow branch checkpoint still has the reverted files. Transcript is accurate but file state is from before the restore.
post-commit sees new session → condenses new work.
Not broken, but the old session's condensed data includes file references for work the user abandoned. The transcript is still valuable though.
One issue: CountOtherActiveSessionsWithCheckpoints doesn't check EndedAt — it would show "1 other active conversation" for the ENDED session, which is misleading.
Scenario 2: git restore with Claude still open → new Claude
code
1. User works with Claude (ACTIVE or IDLE)
2. User does `git restore .` in another terminal → no hooks fire
3. User opens new Claude → new session starts
→ Concurrent session warning shown (old session has checkpoints)
4. Old Claude still running
→ Next Stop: SaveChanges captures current working directory (post-restore)
→ checkpoint shows "no changes" or only new changes
→ Old checkpoints on shadow branch still have pre-restore file data
Not broken — but the old session's earlier checkpoints have stale file snapshots. The next checkpoint captures the post-restore state correctly.
The deeper question
Both scenarios are about the user abandoning work without a mechanism to signal it. git restore doesn't fire hooks. There's no way to detect it happened.
Should we:
Accept this as a known scenario (data is safe, just includes abandoned work)?
Try to detect file state divergence on next checkpoint (diff working directory against last checkpoint)?
Provide an explicit "abandon session" command?
Assistant
Good observation. Today entire reset is blunt — it kills ALL sessions on the current HEAD's shadow branch. In the "abandon" scenario, the user wants to kill the old session but keep the new one alive. entire reset would nuke both since they share the same shadow branch.
The difference:
entire reset (current)
Targeted abandon
Scope
All sessions on current HEAD
Specific session by ID
Shadow branch
Deleted (affects all sessions)
Preserved (other sessions need it)
Session state
All cleared
Only target session cleared
Use case
"Start completely fresh"
"This particular session's work is abandoned"
So yes, entire reset could be made more targeted:
code
entire reset # Current behavior: clear everything for this HEAD
entire reset --session <id> # Clear one session, preserve shadow branch if others need it
entire reset --ended # Clear all ENDED sessions (cleanup abandoned work)
Or even an interactive mode: entire reset shows a picker of sessions and lets you choose which to clear.
This feels like a separate concern from the state machine work though.
Assistant
You're right to question this. Let me trace through what happens to the shadow branch and attribution.
Shadow branch with abandoned session data
The shadow branch has interleaved commits from both sessions, each tagged with Entire-Session: <session-id> trailer:
code
shadow branch:
commit 1: [Session A] - file1.txt modified, metadata for session A
commit 2: [Session A] - file1.txt + file2.txt, metadata for session A
commit 3: [Session B] - file3.txt modified, metadata for session B (after restore)
Each commit is a full tree snapshot (not a diff). WriteTemporary builds from the current working directory each time. So session B's commits don't include session A's reverted files — they capture the post-restore state.
Condensation
extractSessionData filters by session ID trailer — it only reads commits matching the target session. So:
Condensing session A: reads commits 1, 2 → gets the abandoned file data + transcript
Condensing session B: reads commit 3 → gets only post-restore data
No cross-contamination between sessions during condensation.
Attribution
Attribution is per-session:
Session A's attribution: baseTree → session A's last checkpoint tree — shows agent added lines to file1.txt, file2.txt
Session B's attribution: baseTree → session B's last checkpoint tree — shows only file3.txt changes
Attribution is correct per-session, but session A's condensed checkpoint will report "agent added X lines to file1.txt, file2.txt" — changes that the user subsequently reverted. This is historically accurate (the agent DID make those changes), but it inflates the aggregate stats if someone sums across checkpoints.
The real question
Is it problematic to condense session A's data at all? The user abandoned that work. Two perspectives:
Keep it: The transcript is valuable (shows what was tried). The file state is historical. Stats may be slightly inflated.
Drop it: The user explicitly reverted. Condensing abandoned work adds noise. Better to either not condense ENDED sessions automatically, or require explicit entire reset to clean up first.
I think the practical answer is: this is acceptable for now. The abandoned session's data is still accurate as a record of what happened. The user chose to revert, but the conversation history is preserved. If we want to be more surgical later, a targeted reset command handles it.
Should I add this as a documented edge case in the plan and move on, or do you want to dig deeper into the attribution impact?
Assistant
That's a clean set of rules. Let me formalize:
Condensation Eligibility
Phase
Has FilesTouched
Condense?
ACTIVE/ACTIVE_COMMITTED
Yes
Yes (include)
ACTIVE/ACTIVE_COMMITTED
No
Yes (context valuable, session ongoing)
IDLE
Yes
Yes (include)
IDLE
No
Yes (context valuable, session active)
ENDED
Yes
Yes (contributed to code)
ENDED
No
No (discard)
TIMED_OUT
Yes
Yes (contributed to code)
TIMED_OUT
No
No (discard)
Simplified rule: Discard only when session is ENDED/TIMED_OUT ANDlen(FilesTouched) == 0.
And for the explicit removal: a targeted entire reset --session <id> that clears just that session's state. The file changes from that session remain in the working directory (user handles them manually via git).
Let me update the plan with these rules and the targeted reset.
Assistant
Now let me also update the plan file at the repo level to match, and add the targeted reset as a task.
Assistant
Let me also update the plan to add the targeted reset and condensation eligibility to the relevant tasks.
Assistant
Also update the edge cases section to document the abandoned-work scenario.
Assistant
Plan updated with:
Condensation eligibility rules (ENDED + no files → discard)
Targeted entire reset --session (Step 8)
Active session guard on entire reset
Abandoned-work edge case documentation
Anything else you want to work through, or are we ready to finalize?
Assistant
Right! When SessionStart fires for a session that already has a state file (resume via claude -r or new session with same ID), the session should be IDLE — not back to UNINITIALIZED. Otherwise between SessionStart and the first UserPromptSubmit, the session is "off the grid" and a commit would miss it.
Updated transition:
code
ENDED ──SessionStart──> IDLE (re-entry, immediately condensable)
IDLE ──SessionStart──> IDLE (no-op, already condensable)
(none) ──SessionStart──> still UNINITIALIZED (no state file exists yet)
This means SessionStart needs to do a state file check:
If state file exists with Phase = ENDED → set Phase = IDLE, clear EndedAt
If state file exists with Phase = ACTIVE/ACTIVE_COMMITTED → leave as-is (stale, will timeout or catch-up on next UserPromptSubmit)
If state file exists with Phase = IDLE → no-op
If no state file → UNINITIALIZED (current behavior, wait for UserPromptSubmit)
Currently SessionStart is purely informational (shows a message, writes current_session.txt). This adds a small state mutation to it.
Assistant
Also need to update Step 3 to include the SessionStart logic:
Assistant
Good catch. Now SessionStart has actual work to do instead of being purely informational — it transitions ENDED → IDLE on re-entry so the session is immediately condensable. Anything else, or ready to finalize?
Assistant
I'll sync the repo doc (docs/plans/2026-02-06-session-phase-state-machine.md) with all our updates once plan mode exits — I can only edit the plan file right now.
For sequencing into multiple PRs, let me think about the dependency graph:
code
PR 1: File Locking (foundational, no behavior change)
└─ Step 1: flock-based LoadModifySave on StateStore
└─ Step 6: Migrate all call sites to use LoadModifySave
PR 2: Phase Field + State Machine (core behavior change)
└─ Step 2: Phase enum + PendingCheckpointID on both State types
└─ Step 3: Phase transitions in agent hooks (SessionStart, UserPromptSubmit, Stop, SessionStop)
└─ Step 4: Phase-aware PostCommit (defer condensation for active sessions)
└─ Step 5: Phase-aware PrepareCommitMsg (PendingCheckpointID reuse)
PR 3: Cleanup + Targeted Reset
└─ Step 7: Remove current-session.txt
└─ Step 8: Targeted entire reset --session
PR 4: Integration Tests + Docs
└─ Step 9: Integration tests
└─ Step 10: CLAUDE.md + docs updates
But PR 2 is still large. Could split further:
code
PR 2a: Phase field + basic transitions (UserPromptSubmit, Stop, SessionStop)
PR 2b: Phase-aware git hooks (PostCommit, PrepareCommitMsg) — this is the actual bug fix
Assistant
What would you like to clarify about the sequencing?
User
are we able to not push the testing all the way to the end?
Assistant
Yes, absolutely. Tests should travel with the code they verify. Let me rethink the sequencing with tests inline:
code
PR 1: File Locking
- LoadModifySave on StateStore
- Unit tests for locking (concurrent access, error propagation)
- Migrate all call sites to LoadModifySave
- Tests verifying existing behavior unchanged
PR 2: Phase Field + State Machine Core
- Phase enum + PendingCheckpointID on State types
- Phase transition unit tests + backward compat tests
- SessionStart re-entry logic (ENDED → IDLE)
- Agent hook transitions (UserPromptSubmit, Stop, SessionStop)
- Catch-up checkpoint on ACTIVE → ACTIVE detection
- Integration tests for phase transitions
PR 3: Phase-Aware Git Hooks (the actual bug fix)
- PostCommit: defer condensation for ACTIVE sessions
- PrepareCommitMsg: PendingCheckpointID reuse
- Condensation eligibility rules (ENDED + no files → discard)
- Shadow branch deletion guard (all sessions condensed)
- Integration tests: mid-session commit, sequential commits, concurrent sessions
PR 4: Cleanup + Polish
- Remove current-session.txt
- Targeted entire reset --session
- entire reset active session guard
- CLAUDE.md + docs updates
- Any remaining integration tests
Each PR is self-contained with its own tests. PR 1 is purely additive (no behavior change). PR 2 adds the state tracking without changing git hook behavior. PR 3 is the actual fix. PR 4 is cleanup.
Assistant
Let me update the plan with the final 4-PR sequencing.
Assistant
Now let me tag each remaining step with its PR:
Assistant
Plan is updated with 4-PR sequencing, each step tagged with its PR, tests inline with each PR. Ready to finalize?
Assistant
I need to update the repo doc to match the finalized plan. Let me read the current plan file to get the exact content.
Assistant
Now I'll overwrite the repo doc with the finalized plan content.
Assistant
Repo doc updated at docs/plans/2026-02-06-session-phase-state-machine.md. It now matches the finalized plan with all the design decisions from our brainstorm:
type State struct {
// ... existing fields ...
// PendingCheckpointID is set by prepare-commit-msg on the first
// commit in an active session. Reused for all subsequent commits
// until condensation clears it.
PendingCheckpointID id.CheckpointID `json:"pending_checkpoint_id,omitempty"`
// We can use LastInteractionTime (from PR #165) + EndedAt
// to determine if a session is active, avoiding a separate flag.
}
And the "is session active?" check in post-commit would be:
go
func isSessionActive(state *State) bool {
if state.EndedAt != nil {
return false // explicitly ended
}
// Use lastInteractionTime from PR #165 as liveness signal
if time.Since(state.LastInteractionTime) > 30*time.Minute {
return false // stale, treat as inactive
}
return true
}
One concern with this model
If the user never commits after the session ends (e.g., they git stash or discard), the checkpoint ID is burned — it's in the agent's commits but never condensed. The shadow branch still has the data though, so it's not lost — just not on entire/sessions yet.
Is that acceptable, or does condensation need to happen at Stop regardless of whether a user commit follows?
Skip
skip
skip
If inactive → normal flow (condense, reset, delete shadow branch)
SaveChanges (Stop hook):
No change — writes checkpoint to shadow branch as today
Shadow branch now has the full session's data (never prematurely deleted)
Shadow Branch Migration on Mid-Session Commit
When post-commit updates BaseCommit for an active session, it must also rename the shadow branch:
This is the same migration logic already in UserPromptSubmit (for pull/rebase). We should extract it to a shared helper.
Concurrency: StateStore Locking
go
// LoadModifySave atomically reads, modifies, and writes a session state.
func (s *StateStore) LoadModifySave(ctx context.Context, sessionID string,
fn func(*State) error) error {
// flock on <session-id>.json.lock
// Load → fn(state) → Save
// unlock
}
All hook code paths that do read-modify-write use this instead of separate Load/Save calls.
One open concern
After an agent's mid-session commit, the shadow branch gets migrated to the new BaseCommit. But the shadow branch's existing commits reference the old base tree. Does SaveChanges (which appends to the shadow branch) handle this correctly, or does it assume the shadow branch root matches BaseCommit?
Condense from shadow → entire/sessions, delete shadow branch (if no other sessions need it), reset CheckpointCount
IDLE
IDLE
UserPromptSubmit
Set phase=ACTIVE, calculate attribution
ACTIVE
IDLE
SessionStop
Set EndedAt
ENDED
ENDED
git commit
Condense any remaining data, clean up state
ENDED
Multi-Session Interactions
Two sessions (A, B) in the same worktree, same BaseCommit → share shadow branch:
code
Time ──────────────────────────────────────────────────────►
Session A: IDLE ──► ACTIVE ─────────────────────► IDLE ────► ...
Session B: IDLE ──────────► ACTIVE ──► IDLE ──────────────► ...
│
│ Agent B commits via Bash
▼
post-commit fires, checks ALL sessions:
Session A: ACTIVE → skip condense, update BaseCommit
Session B: ACTIVE → skip condense, update BaseCommit
Shadow branch: migrate (shared by both)
Key multi-session rules for post-commit:
Iterate all sessions for this worktree (already does this)
For each session, check phase independently
If ANY session is ACTIVE → don't delete shadow branch after condensing others
Only delete shadow branch when ALL sessions on it are condensed or ended
code
Scenario: B finishes first, user commits
Session A: ACTIVE (still working)
Session B: IDLE (has uncondensed data on shadow)
User commits:
post-commit:
Session A: ACTIVE → skip condense, update BaseCommit
Session B: IDLE → condense B's data to entire/sessions
Shadow branch: DO NOT DELETE (A still needs it)
Migrate shadow to new HEAD
Later, A finishes (Stop), user commits again:
post-commit:
Session A: IDLE → condense A's data
No other sessions on shadow → DELETE shadow branch
How to track which sessions have been condensed
We need a way to know if a session's data has been written to entire/sessions already, so post-commit doesn't condense it twice and knows when the shadow branch can be deleted.
Options:
Existing CondensedTranscriptLines — if > 0, this session has been partially/fully condensed. But it doesn't distinguish "condensed from this shadow branch epoch" vs "condensed in a previous commit cycle."
New field CondensedForCommit — stores the commit hash that triggered condensation. If it matches a commit reachable from HEAD, this session's data is already condensed.
Or simpler: the existing CheckpointCount reset to 0 on condensation already signals "nothing to condense." We just need to not delete the shadow branch if other sessions still have CheckpointCount > 0.
SessionStart creates no state — UNINITIALIZED is the real starting state. State file only created on first UserPromptSubmit.
ACTIVE_COMMITTED — explicit intermediate state where agent has committed but data isn't on entire/checkpoints/v1 yet. Useful for entire status ("2 commits pending condensation").
ENDED is not terminal — claude -r fires SessionStart + UserPromptSubmit, which clears EndedAt and transitions back to ACTIVE. (Currently InitializeSession doesn't clear EndedAt — that's a bug we'd fix.)
TIMED_OUT is virtual — not a stored phase. Hooks compute it from LastInteractionTime > TTL. Behaviorally equivalent to ENDED (condensation allowed, shadow branch cleanup allowed).
IDLE always has uncondensed data — if Stop fired, there's at least one step on the shadow branch. The distinction between "idle with data" and "idle without data" is just CheckpointCount > 0 (or whatever we rename it to).
How post-commit decides what to do
code
post-commit:
for each session on this worktree:
if session.phase == ACTIVE or ACTIVE_COMMITTED:
→ update BaseCommit
→ migrate shadow branch
→ store PendingCheckpointID (if not set)
→ SKIP condensation
if session.phase == IDLE or ENDED or TIMED_OUT:
→ condense to entire/checkpoints/v1
→ reset step count
→ set LastCheckpointID
if ALL sessions condensed (no ACTIVE sessions remain):
→ delete shadow branch
else:
→ keep shadow branch (active sessions still need it)
Does this capture the model you had in mind? Specifically:
Is ACTIVE_COMMITTED worth tracking as a separate phase, or is "ACTIVE + PendingCheckpointID is set" sufficient?
Should TIMED_OUT be a stored value or stay virtual?
entire/<old[:7]>-<wt>
entire/<new[:7]>-<wt>
Collision risk: if the older commit already had a shadow branch, it gets overwritten silently
git reset --hard <older-commit> while ACTIVE_COMMITTED:
Same as above but worse — the agent is still running
When agent does another commit, post-commit fires with wrong BaseCommit
Migration hasn't happened yet (that's done on UserPromptSubmit, not post-commit)
Currently post-commit doesn't migrate — it just reads BaseCommit from state
This is the gap: post-commit uses state.BaseCommit to find the shadow branch, but HEAD has moved. The shadow branch is still at the old name. Post-commit would fail to find sessions or find the wrong shadow branch.
However, with our new model where post-commit skips condensation for ACTIVE sessions and only updates BaseCommit + migrates, this is actually handled. The migration in post-commit (Step 4) would rename the shadow branch.