The new code unconditionally falls back to transcript extraction when FilesTouched is empty. Let me check if this matters in practice.
Assistant
Let me check the PrepareTranscript implementation to understand the cost of a double call.
Assistant
Here's my evaluation of the two issues (threads 1+3 are the same issue, threads 2+4 are the same issue):
Issue 1: Dropped IsActive() guard at Site 2 — Valid, minor behavioral change.
The old code at Site 2 only fell back to transcript extraction when state.Phase.IsActive(). The new resolveFilesTouched() falls back unconditionally. For IDLE/ENDED sessions with empty FilesTouched (rare — SaveStep populates it), the new code would unnecessarily parse the transcript. The downstream shouldCondenseWithOverlapCheck handles it correctly, so it won't cause incorrect condensation, but it's extra work and technically violates the "no behavior change" claim.
Fix: restore the guard at the call site.
Issue 2: Double PrepareTranscript in sessionHasNewContentFromLiveTranscript — Valid performance concern.
hasNewTranscriptWork calls PrepareTranscript, then resolveFilesTouched → extractModifiedFilesFromLiveTranscript calls it again. For OpenCode this runs opencode export twice. For Claude Code it calls waitForTranscriptFlush twice (second call is fast since file exists, but still wasteful).
Fix: in sessionHasNewContentFromLiveTranscript, bypass resolveFilesTouched and call extractModifiedFilesFromLiveTranscript directly since hasNewTranscriptWork already prepared the transcript. Actually — better approach: extract PrepareTranscript to the caller so both methods skip it.
Want me to fix both?
User
issue 1: yes, but also add some unit test coverage to cover this case please
then let's tackle issue 2
Assistant
Starting with issue 1. Let me read the current state and fix it.
Assistant
The fix: resolveFilesTouched transcript fallback should only fire for ACTIVE sessions at this call site. The cleanest way is to check FilesTouched first (fast path), then only call resolveFilesTouched for the transcript fallback when ACTIVE.
Actually, looking at this again — the guard belongs in resolveFilesTouched itself. The plan doc says the offset is always CheckpointTranscriptStart and the transcript fallback only makes sense for ACTIVE sessions (when SaveStep hasn't been called yet). Let me check Site 1 (condensation) to confirm.
Assistant
Good — Site 1 is always called for mid-session commits (no shadow branch). The guard is already at the caller level (line 165). Site 1 is fine.
The issue is only at Site 2. The transcript fallback should be gated on IsActive() since for IDLE/ENDED sessions FilesTouched was already populated by SaveStep. Let me fix it at the call site rather than in resolveFilesTouched (which should remain a general-purpose method).
Assistant
Now let me write a unit test for this. Let me find the existing PostCommit test patterns.
Assistant
Good, TestPostCommit_IdleSessionEmptyFilesTouched_NotCondensed is close to what I need. Let me read it for the test pattern.
Assistant
Now let me understand setupSessionWithCheckpoint to set up the test properly.
Assistant
Good. Now I need to write a test that verifies: for an IDLE session with empty FilesTouched but a transcript containing file modifications, the carry-forward does NOT fall back to transcript extraction (returns empty). Let me write the test.
Assistant
Now let me look at the existing test for resolveFilesTouched to understand the Gemini transcript format used in testing.
Assistant
Now I have enough context. Let me write a focused unit test for resolveFilesTouched that verifies the ACTIVE vs non-ACTIVE behavior, plus a test at the carry-forward level. The unit test on resolveFilesTouched itself is best since the behavior lives there... but actually, the guard is at the call site (PostCommit), not in resolveFilesTouched. So the test should verify the PostCommit behavior.
Actually, let me also write a direct unit test for resolveFilesTouched to document that it does NOT have an IsActive() guard — that's intentional since Site 1 (condensation) needs it for all phases. Then a PostCommit test to verify the call-site guard.
Assistant
Let me add the unit test for resolveFilesTouched covering the FilesTouched fast-path, and a PostCommit test that verifies IDLE sessions don't get transcript fallback.
Assistant
Now add the PostCommit-level test verifying IDLE sessions skip transcript fallback for carry-forward.
Assistant
The test file needs assert and require imports. Let me check what's already imported.
Assistant
No assert/require imports. This file uses raw t.Errorf. Let me update my test to use the same style.
Assistant
Now the PostCommit-level test for the IDLE carry-forward guard. I'll add it after the existing TestPostCommit_IdleSessionEmptyFilesTouched_NotCondensed.
Assistant
Now let me run the tests to verify everything passes.
Assistant
All new tests pass. Now let me run the full suite.
Assistant
All green. Issue 1 is fixed. Now let me tackle issue 2: double PrepareTranscript.
The problem is in sessionHasNewContentFromLiveTranscript: both hasNewTranscriptWork and resolveFilesTouched (via extractModifiedFilesFromLiveTranscript) call PrepareTranscript. The cleanest fix: extractModifiedFilesFromLiveTranscript already has its own PrepareTranscript call. Since hasNewTranscriptWork prepares first, the second call in extractModifiedFilesFromLiveTranscript is redundant. Let me look at the options.
Assistant
The cleanest approach: extractModifiedFilesFromLiveTranscript has its own PrepareTranscript call because it needs to be self-contained when called from resolveFilesTouched directly (e.g., from condensation). But in sessionHasNewContentFromLiveTranscript, hasNewTranscriptWork already prepared.
The simplest fix: skip resolveFilesTouched in this function and call extractModifiedFilesFromLiveTranscript directly, since we know:
hasNewTranscriptWork already prepared the transcript
We need transcript-based files regardless of state.FilesTouched (the growth check already confirmed new work)
Wait — actually resolveFilesTouched is still correct here. If state.FilesTouched is non-empty (hook populated), we should use it and skip transcript extraction entirely (which also skips the second PrepareTranscript). The double call only happens when FilesTouched is empty AND the session is ACTIVE. That's the transcript fallback path.
The right fix: make extractModifiedFilesFromLiveTranscript skip PrepareTranscript when the caller already did it. I'll add a prepared parameter.
Actually, simplest: extract a prepareTranscriptIfNeeded call before both methods in sessionHasNewContentFromLiveTranscript, and have both methods skip their own PrepareTranscript. But that changes too many signatures.
Simplest real fix: in sessionHasNewContentFromLiveTranscript, if resolveFilesTouched returns results from state.FilesTouched (the fast path), there's no double call. The double call only happens on the fallback. So let me just call extractModifiedFilesFromLiveTranscript directly here, since hasNewTranscriptWork already prepared.
Assistant
Actually, a comment isn't enough — the double PrepareTranscript is a real performance issue for OpenCode (runs opencode export twice). Let me revert that comment and do a proper fix.
The cleanest approach: in this one call site, avoid resolveFilesTouched since hasNewTranscriptWork already prepared the transcript. Inline the two-tier resolution to skip the redundant call.
Assistant
Wait — I need to think about this more carefully. The code still calls extractModifiedFilesFromLiveTranscript which internally calls PrepareTranscript. Let me restructure properly.
The right fix: move PrepareTranscript out of extractModifiedFilesFromLiveTranscript into resolveFilesTouched. Then extractModifiedFilesFromLiveTranscript becomes a pure extraction function, and sessionHasNewContentFromLiveTranscript can call it directly without the double-prepare.
Assistant
Now let me implement the fix: move PrepareTranscript from extractModifiedFilesFromLiveTranscript into resolveFilesTouched, so extractModifiedFilesFromLiveTranscript becomes a pure extraction function.
Assistant
Good. Now I'll:
Move PrepareTranscript from extractModifiedFilesFromLiveTranscript to resolveFilesTouched
extractModifiedFilesFromLiveTranscript becomes a pure extraction function (no prepare)
sessionHasNewContentFromLiveTranscript calls extractModifiedFilesFromLiveTranscript directly (transcript already prepared by hasNewTranscriptWork)
Assistant
Now remove PrepareTranscript from extractModifiedFilesFromLiveTranscript:
Assistant
Now I need to create the prepareTranscriptForState helper. Let me also update sessionHasNewContentFromLiveTranscript to call extractModifiedFilesFromLiveTranscript directly.
Assistant
The logCtx in extractModifiedFilesFromLiveTranscript was defined before the removed PrepareTranscript block. Let me check and fix.
Assistant
Need to add logCtx back to extractModifiedFilesFromLiveTranscript:
Assistant
Now create the prepareTranscriptForState helper. Let me check if there's already a similar helper.
Assistant
There's already prepareTranscriptIfNeeded(ctx, ag, path). Let me create prepareTranscriptForState that wraps it with the IsActive guard and agent lookup from state.
Assistant
Now let me verify the build compiles:
Assistant
Compiles clean. Now run fmt, lint, and tests:
Assistant
All green. Both issues are fixed. Let me summarize what was done:
Issue 1 fix: Restored IsActive() guard at Site 2 (PostCommit carry-forward). IDLE/ENDED sessions now copy state.FilesTouched directly without transcript fallback. Added two tests:
TestResolveFilesTouched_PrefersStateFallsBackToTranscript — unit test covering all 4 resolution paths
TestPostCommit_IdleSession_NoTranscriptFallbackForCarryForward — regression test verifying IDLE sessions don't trigger transcript extraction for carry-forward
Issue 2 fix: Extracted PrepareTranscript from extractModifiedFilesFromLiveTranscript into resolveFilesTouched (via new prepareTranscriptForState helper). Now:
Let me check the current state of the affected files.
Assistant
Let me check the CondenseSession path for the double-prepare concern.
Assistant
Here's my assessment of the 4 threads:
Thread 1 (test file - Windows paths in JSON): Not applicable. This project targets macOS/Linux only, and filepath.Join produces forward slashes on those platforms. No Windows CI.
Thread 2 (common.go - merged comment blocks): Valid. The doc comment for prepareTranscriptIfNeeded (defined at line 1445) got merged into the comment block for prepareTranscriptForState (line 1434). Easy fix — separate them.
Thread 3 (condensation - double PrepareTranscript): Valid observation. CondenseSession calls prepareTranscriptIfNeeded before extractSessionDataFromLiveTranscript, then resolveFilesTouched inside that function calls prepareTranscriptForState again. Both are needed though: the first is for the os.ReadFile at line 517, the second is inside resolveFilesTouched (which other callers depend on). It's idempotent but wasteful for OpenCode. This goes away in Phase 1+ when transcript fallback is eliminated.
After passing review: code-simplifier (polish and refine)
Launch Review Agents
Sequential approach (one at a time):
Easier to understand and act on
Each report is complete before next
Good for interactive review
Parallel approach (user can request):
Launch all agents simultaneously
Faster for comprehensive review
Results come back together
Assistant
5 files changed — production code + tests. Launching all applicable review agents in parallel: code review, test analysis, error handling, and comment analysis.
Comment analyzer done. 1 critical terminology issue and 2 improvement suggestions on comment precision. Waiting for the other 3 agents...
User
Positive Findings
Location: /Users/alex/workspace/cli/.worktrees/2/cmd/entire/cli/strategy/manual_commit_hooks.go:1372-1377 -- The resolveFilesTouched doc comment is excellent. It clearly states the function's purpose, its resolution strategy (prefer state, fall back to transcript), the directive that "all call sites that need 'what files did the agent touch?' should use this," and that it handles PrepareTranscript internally so callers do not need to worry about it. This is a good canonical reference pattern.
Location: /Users/alex/workspace/cli/.worktrees/2/cmd/entire/cli/strategy/manual_commit_hooks.go:1449-1454 -- The extractModifiedFilesFromLiveTranscript updated doc comment properly documents the precondition that callers must ensure the transcript is prepared, and gives concrete examples of how (prepareTranscriptForState or hasNewTranscriptWork). This "contract" documentation is valuable for preventing future bugs where someone adds a new call site without preparing the transcript first.
Location: /Users/alex/workspace/cli/.worktrees/2/cmd/entire/cli/strategy/manual_commit_hooks.go:899-902 -- The inline comment in postCommitProcessSession accurately explains why the IsActive() guard exists and correctly states that IDLE/ENDED sessions already have FilesTouched populated by SaveStep/mergeFilesTouched. This is a good example of documenting the "why" rather than the "what."
Location: /Users/alex/workspace/cli/.worktrees/2/cmd/entire/cli/strategy/manual_commit_condensation.go:532 -- The condensation comment ("Resolve files touched: prefers hook-populated state, falls back to transcript extraction") is concise and accurately summarizes the behavior of resolveFilesTouched without redundantly restating implementation details. Good signal-to-noise ratio.
<total_tokens>73696</total_tokens><tool_uses>18</tool_uses><duration_ms>99657</duration_ms>
Full transcript available at: /private/tmp/claude-501/-Users-alex-workspace-cli--worktrees-2/tasks/a88a0b18dae028e78.output
User
Recommended Removals
None. All comments in this PR carry meaningful context that a future maintainer would benefit from.
// prepareTranscriptForState ensures the transcript is up-to-date for the given session.
// Only prepares for ACTIVE sessions — IDLE/ENDED sessions are already flushed.
// Resolves the agent from state.AgentType internally. Safe to call multiple times
// (idempotent), but callers should avoid redundant calls for performance.
Current state: The comment claims the function is "idempotent." Strictly, idempotency means calling it multiple times produces the same result as calling it once. Looking at the underlying PrepareTranscript implementations -- Claude Code's waitForTranscriptFlush waits for a sentinel with a timeout, and OpenCode's runs opencode export -- these are not truly idempotent. They re-execute side effects on every call (re-waiting for flush, re-running export). The outcome may be the same if nothing changed, but the function is not free of side effects on repeated calls. The parenthetical "(idempotent)" could mislead a reader into thinking repeated calls are free, which contradicts the immediately following clause "but callers should avoid redundant calls for performance."
Suggestion: Remove the "(idempotent)" claim since the very next clause contradicts it. The comment already conveys what matters: "callers should avoid redundant calls for performance." A cleaner version:
go
// prepareTranscriptForState ensures the transcript is up-to-date for the given session.
// Only prepares for ACTIVE sessions — IDLE/ENDED sessions are already flushed.
// Resolves the agent from state.AgentType internally. Multiple calls are safe but
// not free — callers should avoid redundant calls for performance.
// hasNewTranscriptWork checks if the agent has done work since the last condensation.
// Uses agent-delegated GetTranscriptPosition() — does NOT do file extraction.
// All call sites that need "has the agent done new work?" should use this.
//
// Returns false if: no transcript path, unknown agent type, agent doesn't implement
// TranscriptAnalyzer, or GetTranscriptPosition fails. This is intentional fail-safe
// behavior: callers treat false as "no new work detected", which conservatively
// skips condensation on errors.
Issue: The comment says "callers treat false as 'no new work detected', which conservatively skips condensation on errors." This is accurate for the sessionHasNewContentFromLiveTranscript call site (line 1336), where false causes an early return of (false, nil), skipping that session. However, the other path into sessionHasNewContentFromLiveTranscript is called from sessionHasNewContent (line 1207), and when sessionHasNewContent returns (false, nil), the caller in postCommitProcessSession (line 888-891) treats errors as hasNew = true (fail-open), but treats a false return as genuinely no new work -- so the "conservatively skips condensation" claim is accurate there.
But there is a deeper concern: hasNewTranscriptWork is also called indirectly through sessionsWithNewContent (via sessionHasNewContent -> sessionHasNewContentFromLiveTranscript), and in the prepare-commit-msg path, if hasNewTranscriptWork returns false due to an error (e.g., GetTranscriptPosition fails because the file is temporarily locked), the session is excluded from the "sessions with new content" list. This means no Entire-Checkpoint trailer is added. The comment calls this "fail-safe" and "conservative," but whether skipping the trailer is truly "safe" or "conservative" depends on perspective -- if the agent do work and the transcript just could not be read, the user loses the checkpoint link. "Fail-closed" (skipping on error) would be a more technically precise term than "fail-safe."
User
Summary: This PR introduces two consolidated functions (resolveFilesTouched and hasNewTranscriptWork) to centralize transcript-related file extraction and "new work" detection, replacing scattered inline logic. I reviewed all doc comments and inline comments across the three changed files. The comments are generally well-written and accurate. I found one critical accuracy issue, two improvement opportunities, and several positive findings.
Assistant
Test analyzer done. No critical gaps — solid coverage with some suggestions for hasNewTranscriptWork unit tests and minor quality notes. Waiting for the remaining 2 agents...
User
Test Coverage Analysis for PR #597: Consolidate Transcript File Extraction
1. Summary
The PR introduces three new abstractions:
resolveFilesTouched -- single entry point for "what files did the agent touch?" (prefers state.FilesTouched, falls back to transcript extraction)
hasNewTranscriptWork -- single entry point for "has the agent done new work since last condensation?" (position-based check, no file extraction)
prepareTranscriptForState -- helper to ensure transcript is up-to-date given a SessionState
The test coverage is solid for resolveFilesTouched (4 subtests covering priority, copy semantics, fallback, and nil cases) and includes a targeted regression test for the IDLE session guard in PostCommit. The existing tests (mid_turn_commit_test.go, phase_postcommit_test.go) exercise the refactored call sites end-to-end. However, there are a few gaps worth examining.
2. Critical Gaps
None. The changes are a refactoring with clear behavioral equivalence, and the most dangerous regression path (IDLE sessions getting transcript fallback in carry-forward) is covered by the new TestPostCommit_IdleSession_NoTranscriptFallbackForCarryForward.
3. Important Improvements
3a. hasNewTranscriptWork has no direct unit tests (Criticality: 6/10)
hasNewTranscriptWork is a new public-facing method with non-trivial logic: it checks TranscriptPath/AgentType preconditions, conditionally calls PrepareTranscript (only for ACTIVE sessions), delegates to GetTranscriptPosition, and compares against CheckpointTranscriptStart. It is currently only tested indirectly through sessionHasNewContentFromLiveTranscript (via TestSessionHasNewContentFromLiveTranscript_NormalizesAbsolutePaths and TestSessionHasNewContentFromLiveTranscript_IncludesSubagentFiles), both of which set Phase=ACTIVE and CheckpointTranscriptStart=0.
Missing scenarios that could hide regressions:
hasNewTranscriptWork with currentPos == CheckpointTranscriptStart -- should return false. The <= comparison is a subtle boundary (was the agent supposed to start from offset N or after N?). The existing tests never exercise the "no growth" path through .
Assistant
Silent failure hunter done. Found 3 HIGH issues (missing logging, error conflation) and 3 MEDIUM issues. Waiting for the code reviewer...
User
Summary
#
Location
Severity
Issue
1
common.go:1434-1436
HIGH
prepareTranscriptForState silently discards GetByAgentType error with no logging
2
manual_commit_hooks.go:1432-1434
HIGH
hasNewTranscriptWork silently returns false on GetTranscriptPosition failure with no logging
3
manual_commit_hooks.go:1427-1430
MEDIUM
hasNewTranscriptWork silently returns false when agent lacks TranscriptAnalyzer -- no logging
4
manual_commit_hooks.go:1336-1338
HIGH
Semantic change: errors now return (false, nil) instead of propagating, bypassing the safety fallback at lines 889-896
5
manual_commit_hooks.go:1449-1455
MEDIUM
Caller contract for PrepareTranscript enforced only by doc comment, not by code
6
manual_commit_condensation.go:533
MEDIUM
resolveFilesTouched skips transcript preparation for non-ACTIVE sessions, relying on assumption that Stop hook flushed successfully
The most actionable items are Issues 1, 2, and 4. Issues 1 and 2 are straightforward fixes (add logging.Debug calls). Issue 4 is a design concern worth discussing: the hasNewTranscriptWork function collapses errors and legitimate "no work" into a single false return, which bypasses the existing error-safety fallback that other code paths use. Whether to fix this depends on the team's risk tolerance for silent checkpoint data loss on transient I/O errors.
<total_tokens>74364</total_tokens><tool_uses>19</tool_uses><duration_ms>146175</duration_ms>
Full transcript available at: /private/tmp/claude-501/-Users-alex-workspace-cli--worktrees-2/tasks/a9d0176b7a0a7fd4a.output
User
Positive Observations
The PostCommit carry-forward path (lines 903-909) correctly gates transcript extraction on IsActive(), with the regression test TestPostCommit_IdleSession_NoTranscriptFallbackForCarryForward validating this. This is good defensive design.
resolveFilesTouched correctly returns a copy of state.FilesTouched (lines 1380-1382), preventing mutation of shared state. The test TestResolveFilesTouched_PrefersStateFallsBackToTranscript/returns copy verifies this.
The test coverage is thorough for the happy paths and the primary regression scenario (IDLE sessions not getting transcript fallback).
User
ISSUE 6: resolveFilesTouched in the condensation path may call prepareTranscriptForState on already-prepared transcripts, but prepareTranscriptForState skips non-ACTIVE sessions -- is the condensation path always ACTIVE?
Location:/Users/alex/workspace/cli/.worktrees/2/cmd/entire/cli/strategy/manual_commit_condensation.go, line 533
Issue Description:extractSessionDataFromLiveTranscript is called during condensation. The function resolveFilesTouched calls prepareTranscriptForState, which checks state.Phase.IsActive() and returns immediately for IDLE/ENDED sessions. However, condensation can happen for IDLE sessions (the IDLE + GitCommit -> IDLE transition triggers ActionCondense).
If an IDLE session has empty FilesTouched and the transcript needs preparation (OpenCode), prepareTranscriptForState will skip preparation because the session is IDLE. Then extractModifiedFilesFromLiveTranscript will try to read the transcript, which may not exist or be stale.
For the IDLE case, the doc comment on prepareTranscriptForState says "IDLE/ENDED sessions are already flushed" (line 1427). This is true for Claude Code (which writes transcripts continuously) but the assumption relies on the Stop hook having called PrepareTranscript -- if the Stop hook failed or was interrupted for OpenCode, the transcript may not have been flushed.
This is a pre-existing concern (the old extractModifiedFilesFromLiveTranscript had the same Phase.IsActive() guard), so the PR does not introduce a regression. But the refactoring makes this assumption more fragile because it is now in a different function (prepareTranscriptForState) separated from the code that relies on it.
User Impact: For OpenCode only, if the Stop hook fails to flush the transcript, IDLE session condensation would use stale transcript data and produce an incomplete files-touched list.
Recommendation: No code change required -- the assumption is documented and reasonable. But consider adding a logging statement in prepareTranscriptForState when it skips a non-ACTIVE session that has an empty FilesTouched, since that is the edge case where skipping preparation matters most.
User
ISSUE 5: extractModifiedFilesFromLiveTranscript no longer has PrepareTranscript -- relies on caller contract with no enforcement
// extractModifiedFilesFromLiveTranscript extracts modified files from the live transcript
// (including subagent transcripts) starting from the given offset, and normalizes them
// to repo-relative paths. Returns the normalized file list.
//
// Callers must ensure the transcript is prepared (e.g., via prepareTranscriptForState
// or hasNewTranscriptWork) before calling this function.
func (s *ManualCommitStrategy) extractModifiedFilesFromLiveTranscript(...)
Issue Description: The old code called PrepareTranscript inside extractModifiedFilesFromLiveTranscript itself, making it self-contained. The new code removes that call and adds a doc comment requiring callers to prepare the transcript first. This is a "caller contract" enforced only by documentation, not by code.
Currently there are three call paths into extractModifiedFilesFromLiveTranscript:
resolveFilesTouched -> calls prepareTranscriptForState first -> OK
sessionHasNewContentFromLiveTranscript -> calls hasNewTranscriptWork first (which calls PrepareTranscript) -> OK
Any future caller -> no enforcement
If a new call site is added that forgets to prepare the transcript, the function will silently read stale data (or a missing file for OpenCode), and the file extraction will silently return wrong results or nil. There is no runtime check, no assertion, and no log message that would indicate the transcript was not prepared.
User Impact: Low for current code, but creates a maintenance trap. A future developer adding a call to extractModifiedFilesFromLiveTranscript may not read the doc comment and produce silently incorrect results.
Recommendation: This is an acceptable design tradeoff for performance (avoiding redundant PrepareTranscript calls). No change needed, but the doc comment should be more emphatic about consequences:
go
// Callers MUST ensure the transcript is prepared (e.g., via prepareTranscriptForState
// or hasNewTranscriptWork) before calling this function. Failing to do so will cause
// stale or missing transcript data to be read, producing incorrect file lists with
// no error indication.
User
ISSUE 4: sessionHasNewContentFromLiveTranscript changed semantics -- hasNewTranscriptWork returning false now conflates "no new work" with "error checking"
if !s.hasNewTranscriptWork(ctx, state) {
return false, nil
}
Code (old):
go
modifiedFiles, ok := s.extractNewModifiedFilesFromLiveTranscript(ctx, state)
if !ok || len(modifiedFiles) == 0 {
return false, nil
}
Issue Description: This is the most significant behavioral change in the PR. The old extractNewModifiedFilesFromLiveTranscript returned a ([]string, bool) tuple where the bool distinguished between "extraction succeeded but found nothing" (nil, true) and "extraction failed" (nil, false). Both cases were treated identically by the caller (return false, nil), so the distinction was not used -- but the information was available for future use.
The new hasNewTranscriptWork collapses these into a single bool return. This means the caller sessionHasNewContentFromLiveTranscript now returns (false, nil) for ALL of these scenarios:
No transcript path (expected for some sessions)
Unknown agent type (data corruption)
PrepareTranscript failed (I/O error) -- execution continues despite this, then GetTranscriptPosition may also fail
Agent does not implement TranscriptAnalyzer (agent bug)
GetTranscriptPosition failed (I/O error)
Transcript position has not advanced (legitimately no new work)
The function signature (bool, error) is misleading because sessionHasNewContentFromLiveTranscriptnever returns an error -- the error return is always nil. Every failure path returns (false, nil). This means the caller at line 888-896:
User
ISSUE 3: hasNewTranscriptWork silently returns false when agent does not implement TranscriptAnalyzer
analyzer, ok := ag.(agent.TranscriptAnalyzer)
if !ok {
return false
}
Issue Description: If an agent does not implement the TranscriptAnalyzer interface, hasNewTranscriptWork returns false (no new work), but sessionHasNewContentFromLiveTranscript still proceeds to call extractModifiedFilesFromLiveTranscript which performs the same type assertion at lines 1467-1470 and also returns nil. So if an agent does not implement TranscriptAnalyzer, the entire check returns (false, nil) and the commit proceeds without a checkpoint trailer.
This is a pre-existing pattern (the old code did the same thing), but the doc comment's claim that this is documented is only partially true. The comment says "Returns false if: ... agent doesn't implement TranscriptAnalyzer" but does not explain the consequence: the user's commit will have no checkpoint metadata for this session.
For currently registered agents this should not happen (they all implement the interface). But if a new agent is added that does not implement TranscriptAnalyzer, this would silently drop checkpoint data with no warning.
Recommendation: No code change strictly needed, but adding a logging.Debug for this case would help future debugging:
go
analyzer, ok := ag.(agent.TranscriptAnalyzer)
if !ok {
logging.Debug(logCtx, "hasNewTranscriptWork: agent does not implement TranscriptAnalyzer",
slog.String("session_id", state.SessionID),
slog.String("agent_type", string(state.AgentType)),
)
return false
}
User
ISSUE 2: hasNewTranscriptWork silently returns false for GetTranscriptPosition failures -- behavioral change from the old code
currentPos, err := analyzer.GetTranscriptPosition(state.TranscriptPath)
if err != nil {
return false // <--- Silent return false, no logging
}
Issue Description: The doc comment (lines 1395-1398) claims this is "intentional fail-safe behavior" where false means "no new work detected, which conservatively skips condensation on errors." However, the comment mischaracterizes the safety properties.
Returning false when GetTranscriptPosition fails does NOT "conservatively skip condensation." It prevents condensation from happening, which means the user's checkpoint data is lost -- the opposite of conservative. If the transcript file is temporarily unreadable (permissions, transient I/O error, NFS hiccup), the checkpoint trailer will not be added to the commit, and the session metadata for that commit will never be persisted to entire/checkpoints/v1. That data is gone forever once the shadow branch is cleaned up.
The old code (extractNewModifiedFilesFromLiveTranscript) had the same return nil, false pattern, so this is not a regression introduced by this PR. But the PR adds a doc comment that justifies this behavior as "fail-safe" when it is actually "fail-silent-and-lose-data."
Moreover, unlike the PrepareTranscript failure at line 1416-1423 which logs the error, the GetTranscriptPosition failure at line 1432-1434 logs nothing. A transient I/O error reading the transcript will produce zero diagnostic output.
Hidden Errors:
File permission errors on the transcript
Transcript file deleted mid-operation
Malformed transcript content that causes GetTranscriptPosition to fail
Disk I/O errors
User Impact: The user commits code, but the Entire-Checkpoint trailer is not added because sessionHasNewContentFromLiveTranscript returned false. The commit goes through without any checkpoint metadata. The user has no way to know that their agent session data was not captured for this commit. On next commit, if the error is transient, the data may be picked up -- but only if the session is still active and the transcript hasn't been truncated.
func prepareTranscriptForState(ctx context.Context, state *SessionState) {
if !state.Phase.IsActive() || state.TranscriptPath == "" || state.AgentType == "" {
return
}
ag, err := agent.GetByAgentType(state.AgentType)
if err != nil {
return // <--- Silent return, no logging
}
prepareTranscriptIfNeeded(ctx, ag, state.TranscriptPath)
}
Issue Description: When GetByAgentType fails -- which happens when the agent type stored in session state does not match any registered agent (e.g., data corruption, agent plugin removed, or a future agent type from a newer CLI version) -- this function silently returns with no logging whatsoever. The caller (resolveFilesTouched) will then proceed to call extractModifiedFilesFromLiveTranscript, which will also call GetByAgentType, fail again silently, and return nil. The result: resolveFilesTouched returns an empty file list with no indication that anything went wrong.
Compare this to hasNewTranscriptWork at line 1406-1408, which has the exact same silent return false for GetByAgentType errors but at least has a documented rationale in its doc comment (lines 1395-1398). prepareTranscriptForState has no such rationale.
Hidden Errors:
Unknown/corrupted agent type in session state
Registry initialization race condition (unlikely but possible)
Agent plugin removed between sessions
User Impact: If an agent type becomes unrecognized (e.g., user downgrades CLI version), transcript preparation silently fails. The subsequent transcript extraction also fails silently. The user's checkpoint ends up with empty FilesTouched, which means carry-forward computation produces no files, and the user loses track of which files the agent modified. There is zero feedback about why this happened.
Recommendation: Add a logging.Debug call when fails, consistent with how logs failures. This function is called from hot paths (hooks), so Debug-level is appropriate:
This PR consolidates transcript file extraction behind two new functions (resolveFilesTouched and hasNewTranscriptWork) and introduces prepareTranscriptForState as a convenience wrapper. While the refactoring is a good consolidation, I found several error handling concerns that range from medium to high severity.
Assistant
All 4 agents complete. Here's the aggregated review:
PR Review Summary
Critical Issues (0)
None. All agents agree the refactoring is behaviorally equivalent to the old code.
Important Issues (2)
Missing logging.Debug in prepareTranscriptForState (common.go:1434-1436) — silently discards GetByAgentType error with no logging. Every other error path in this PR (and the codebase) logs failures.
Missing logging.Debug in hasNewTranscriptWork (manual_commit_hooks.go:1432-1434) — GetTranscriptPosition failure returns false with no logging. The PrepareTranscript failure right above it logs properly.
Both are straightforward: add logging.Debug calls consistent with surrounding code.
Suggestions (5)
Comment precision — prepareTranscriptForState doc says "idempotent" then immediately says "callers should avoid redundant calls for performance" — contradictory. Suggest: "Multiple calls are safe but not free."
Comment precision — sessionHasNewContentFromLiveTranscript inline comment says "hasNewTranscriptWork already called PrepareTranscript" but doesn't mention the IsActive() conditionality. Minor.
hasNewTranscriptWork unit tests — no direct unit tests for boundary cases (position == CheckpointTranscriptStart, missing TranscriptPath, non-ACTIVE phase). Currently tested indirectly via integration tests.
extractModifiedFilesFromLiveTranscript caller contract — PrepareTranscript requirement enforced only by doc comment. Could strengthen wording to emphasize consequences.
Fail-safe vs fail-closed terminology — comment analyzer notes "fail-safe" is borderline; "fail-closed" would be more technically precise (errors cause skipped work, not allowed work).
Strengths
Clean separation of "what files?" vs "has new work?" concerns
Defensive copy semantics in resolveFilesTouched with test
Well-targeted regression test for IDLE session guard
Good doc comments documenting canonical usage ("all call sites that need X should use this")
Code reviewer found zero high-confidence issues
Recommended Action
The two logging gaps (issues 1-2) are worth fixing. The rest are minor comment improvements. Want me to fix issues 1-3?
/Users/alex/workspace/cli/.worktrees/2/cmd/entire/cli/strategy/common.go (new helper: prepareTranscriptForState)
/Users/alex/workspace/cli/.worktrees/2/cmd/entire/cli/strategy/manual_commit_condensation.go (simplified to use resolveFilesTouched)
/Users/alex/workspace/cli/.worktrees/2/cmd/entire/cli/strategy/manual_commit_hooks.go (new methods, refactored call sites, deleted wrappers)
/Users/alex/workspace/cli/.worktrees/2/cmd/entire/cli/strategy/manual_commit_test.go (new tests for resolveFilesTouched)
/Users/alex/workspace/cli/.worktrees/2/cmd/entire/cli/strategy/phase_postcommit_test.go (regression test for IDLE session guard)
Summary
This PR is a well-executed refactoring that consolidates scattered transcript-reading logic behind two focused methods:
resolveFilesTouched -- "What files did the agent touch?" Prefers state.FilesTouched, falls back to transcript extraction. Handles PrepareTranscript internally.
hasNewTranscriptWork -- "Has the agent done new work since last condensation?" Uses GetTranscriptPosition without doing file extraction.
The split cleanly separates two concerns that were previously intertwined in extractNewModifiedFilesFromLiveTranscript (which checked for new work AND extracted files in one call). The new API surface is easier to reason about and avoids redundant transcript preparation.
No High-Confidence Issues Found (>= 80)
I verified the following areas and found them correct:
Behavioral equivalence of the hasNewTranscriptWork refactor. The old extractNewModifiedFilesFromLiveTranscript returned ([]string, bool) where bool signaled extraction success. In sessionHasNewContentFromLiveTranscript, both !ok (error) and len(modifiedFiles) == 0 (no files) resulted in return false, nil. The new code achieves the same outcome: hasNewTranscriptWork returns false for all error paths and for "no new content" (currentPos <= CheckpointTranscriptStart), which maps to the same return false, nil.
The PR removes the PrepareTranscript call from and adds a doc comment requiring callers to prepare first. Both call sites satisfy this:
User
fix 1-3
Assistant
Need to add imports to common.go.
Assistant
All green. Those diagnostics are pre-existing (not in our diff). Let me commit and push.
Assistant
Done. Fixed in a49eebf6:
prepareTranscriptForState — added logging.Debug for GetByAgentType failure
hasNewTranscriptWork — added logging.Debug for GetTranscriptPosition failure
Doc comment — replaced "Safe to call multiple times (idempotent), but callers should avoid redundant calls" with "Multiple calls are safe but not free"
1. Stage all changes
2. Run: /pr-review-toolkit:review-pr all
3. Address all critical and important issues
4. Run specific reviews again to verify
5. Create PR
After PR feedback:
code
1. Make requested changes
2. Run targeted reviews based on feedback
3. Verify issues are resolved
4. Push updates
Notes:
Agents run autonomously and return detailed reports
Each agent focuses on its specialty for deep analysis
Results are actionable with specific file:line references
Agents use appropriate models for their complexity
All agents available in /agents list
// Prefer hook-populated files. If empty, extract from transcript directly —
// hasNewTranscriptWork already called PrepareTranscript, so we bypass
// resolveFilesTouched (which would prepare again) and extract directly.
Current state: The comment explains an optimization: since hasNewTranscriptWork already called PrepareTranscript, the code calls extractModifiedFilesFromLiveTranscript directly instead of going through resolveFilesTouched (which would prepare again). This reasoning is correct but subtly fragile. Looking at the code flow: hasNewTranscriptWork only calls PrepareTranscript when state.Phase.IsActive() (line 1414). sessionHasNewContentFromLiveTranscript is called from sessionHasNewContent when there is no shadow branch (line 1207) or no transcript on the shadow branch (line 1267). At the prepare-commit-msg path call site, the session could theoretically be in any phase (the function is phase-agnostic). If the session is IDLE/ENDED, hasNewTranscriptWork skips PrepareTranscript and the comment's rationale still holds (because extractModifiedFilesFromLiveTranscript also has its PrepareTranscript block removed by this PR, so it would not prepare either way). The optimization is correct but the comment does not acknowledge that the PrepareTranscript call inside hasNewTranscriptWork is conditional on IsActive().
Suggestion: Make the comment more precise:
go
// Prefer hook-populated files. If empty, extract from transcript directly —
// hasNewTranscriptWork already called PrepareTranscript (for active sessions)
// or skipped it (for idle/ended, already flushed), so we bypass
// resolveFilesTouched to avoid redundant preparation.
did
Suggestion: The terminology is borderline. Consider replacing "fail-safe" with "fail-closed" to be more precise, and add a note that this means errors may cause missed checkpoint links in prepare-commit-msg. Alternatively, if the current phrasing is intentional (because not adding a trailer is the "safe" default that avoids false positives), add a brief note explaining why skipping is considered safe -- for example, "safe because the next commit will catch up."
hasNewTranscriptWork
hasNewTranscriptWork with missing TranscriptPath or AgentType -- should return false. These are early-exit guards. If someone accidentally removes one, the method would panic or produce wrong results. Currently, these guards are untested directly.
hasNewTranscriptWork for a non-ACTIVE session -- should skip PrepareTranscript. This matters because the existing TestPostCommit_IdleSession_SkipsSentinelWait regression test operates at the integration level (full PostCommit), not at the hasNewTranscriptWork unit level. A direct test would catch a future regression where the ACTIVE guard is accidentally removed from hasNewTranscriptWork itself.
What it would catch: If someone changes the <= to < in the position comparison, existing tests would not detect it because they always start at offset 0 with a growing transcript. A test with currentPos == CheckpointTranscriptStart == 4 would catch that.
3b. sessionHasNewContentFromLiveTranscript uses state.FilesTouched directly instead of resolveFilesTouched -- no test covers the FilesTouched preference path (Criticality: 5/10)
In the refactored sessionHasNewContentFromLiveTranscript (lines 1340-1346 of manual_commit_hooks.go), the code reads:
This is intentionally different from calling resolveFilesTouched (the comment explains: hasNewTranscriptWork already called PrepareTranscript). However, the existing tests in mid_turn_commit_test.go always have empty FilesTouched, so they only exercise the fallback path. No test verifies that sessionHasNewContentFromLiveTranscript correctly prefers state.FilesTouched when populated.
What it would catch: If someone refactors this code and accidentally replaces the direct state.FilesTouched read with resolveFilesTouched, the redundant PrepareTranscript call could cause a performance regression (double 3s timeout for OpenCode). The test would also verify the intent: when hooks have already populated FilesTouched, transcript extraction is skipped entirely.
3c. prepareTranscriptForState has no direct tests (Criticality: 4/10)
The new prepareTranscriptForState helper in common.go has three early-exit conditions: non-ACTIVE phase, empty TranscriptPath, and empty AgentType. It is tested indirectly through resolveFilesTouched (the fallback path calls it), but only for the Phase not being explicitly set (defaulting to the zero value). A direct test would be simple and would protect against future changes to the guard conditions.
What it would catch: If the ACTIVE-only guard is removed (e.g., someone thinks "it's idempotent, so safe to call for IDLE sessions"), it would cause the 3s sentinel timeout regression that was previously fixed.
4. Test Quality Issues
4a. TestResolveFilesTouched_PrefersStateFallsBackToTranscript subtests are not parallelized
Per the project's CLAUDE.md: "Always use t.Parallel() in tests." The subtests in this new test function do not call t.Parallel(). The parent test uses t.Chdir(dir) which is an exception to parallelization, but the subtests should still be noted as a minor style inconsistency. Since t.Chdir on the parent affects all subtests, parallel subtests here would actually be unsafe, so the current approach is correct -- but a brief comment explaining this would improve clarity.
4b. TestPostCommit_IdleSession_NoTranscriptFallbackForCarryForward asserts on StepCount as a condensation proxy
The test checks state.StepCount to verify condensation did not happen. This is an indirect signal -- StepCount is incremented during condensation. If the condensation path changes to not increment StepCount, this test would pass while the bug exists. A more robust assertion would also check that the checkpoint branch was NOT updated, or that state.LastCheckpointID was not set. That said, StepCount is a reasonable proxy given the current implementation.
5. Positive Observations
TestResolveFilesTouched_PrefersStateFallsBackToTranscript is thorough: it covers the priority path, copy semantics (mutation safety), the transcript fallback path, and the nil/nil case. This is exactly the right set of behavioral tests for a two-tier resolution function.
The copy semantics test (subtest "returns copy of FilesTouched") is particularly valuable. Returning a copy prevents callers from accidentally mutating session state, which could cause subtle bugs in carry-forward computation.
TestPostCommit_IdleSession_NoTranscriptFallbackForCarryForward is a well-structured regression test. It sets up the exact edge case (IDLE session with empty FilesTouched but a transcript that WOULD match committed files) and verifies that condensation does not happen. The comment clearly documents what regression it prevents.
Existing integration-level tests (TestSessionHasNewContentFromLiveTranscript_NormalizesAbsolutePaths, TestSessionHasNewContentFromLiveTranscript_IncludesSubagentFiles, TestPostCommit_IdleSession_SkipsSentinelWait) continue to exercise the refactored call sites end-to-end, providing confidence that the refactoring preserves behavior.
The test naming follows the project's TestComponent_Scenario convention consistently.
The doc comments on both resolveFilesTouched and hasNewTranscriptWork clearly document the "all call sites that need X should use this" consolidation intent, which helps prevent future callers from bypassing these entry points.
<total_tokens>78576</total_tokens><tool_uses>23</tool_uses><duration_ms>128759</duration_ms>
Full transcript available at: /private/tmp/claude-501/-Users-alex-workspace-cli--worktrees-2/tasks/aeb2d5be288339ce9.output
...will NEVER trigger its safety fallback (hasNew = true) for live transcript errors, because errors from hasNewTranscriptWork are never surfaced as Go errors. The fail-safe "assume new content on error" at line 889-896 is completely bypassed for the live transcript path.
User Impact: Same as Issue 2 -- silent data loss on transient errors. The safety net that exists for other error paths (line 889-896) is unreachable for these errors.
Recommendation: Consider having hasNewTranscriptWork return (bool, error) to preserve the ability to distinguish "definitely no new work" from "could not determine." Alternatively, keep the current design but make the doc comment on sessionHasNewContentFromLiveTranscript explicit that errors in the live transcript path are handled as "no new work" rather than triggering the safety fallback. At minimum, ensure all error paths in hasNewTranscriptWork are logged (see Issues 2 and 3).
Recommendation: At minimum, log the error. Ideally, reconsider whether false is truly the safe default here -- for the prepare-commit-msg hook path, returning an error (which gets handled as hasNew = true at line 889-896) would be a safer default because it errs on the side of adding the trailer rather than omitting it:
resolveFilesTouched calls prepareTranscriptForState before extraction.
sessionHasNewContentFromLiveTranscript calls hasNewTranscriptWork first, which calls PrepareTranscript for ACTIVE sessions.
The IDLE session guard in postCommitProcessSession. The carry-forward computation (line 903-909) now gates resolveFilesTouched on state.Phase.IsActive(), preventing IDLE sessions from falling back to transcript extraction. This is correct: IDLE/ENDED sessions should have FilesTouched already populated by SaveStep. The new regression test TestPostCommit_IdleSession_NoTranscriptFallbackForCarryForward validates this.
Copy semantics.resolveFilesTouched defensively copies state.FilesTouched before returning. In sessionHasNewContentFromLiveTranscript, state.FilesTouched is read directly (line 1343) without copying -- this is safe because hasOverlappingFiles is read-only and doesn't mutate the slice.
prepareTranscriptForState in common.go. The helper correctly gates on state.Phase.IsActive() (matching the existing pattern in hasNewTranscriptWork) and silently returns on errors (consistent with the fail-safe approach for hooks).
Test quality. The new TestResolveFilesTouched_PrefersStateFallsBackToTranscript covers all four code paths (prefer state, returns copy, transcript fallback, nil when both empty). Tests use t.Chdir() which correctly means they cannot use t.Parallel(), consistent with the project's documented exception. The regression test for the IDLE guard is well-targeted.
Terminology. The "fail-safe" terminology in the hasNewTranscriptWork doc comment is accurate: returning false (no new work) conservatively skips condensation, which is the safe default. The fixup commit (aaeab8f9) corrected this from a previous "fail-open" label.
The code is clean, well-documented, tests pass, and lint is clear. This is a solid refactoring that reduces the surface area for transcript-reading bugs.
<total_tokens>74695</total_tokens><tool_uses>28</tool_uses><duration_ms>176725</duration_ms>
Full transcript available at: /private/tmp/claude-501/-Users-alex-workspace-cli--worktrees-2/tasks/acc11d2f2bd6f8f79.output