Implement the following plan: ENT-259: Fix attribution in deferred condensation Context…
Jump to turn (6)
- User
Implement the following plan:
When the agent commits mid-turn (ACTIVE → ACTIVE_COMMITTED), PostCommit migration updates state.BaseCommit to the new HEAD. Later when handleTurnEndCondense runs at Stop, calculateSessionAttributions uses state.BaseCommit for the base tree. Since state.BaseCommit now equals HEAD, baseTree == headTree and the diff is zero — attribution shows no changes.
The root cause: BaseCommit serves two purposes (shadow branch naming + attribution reference) but they diverge during deferred condensation. Migration must update it for shadow branch lookup, but attribution needs the original value.
AttributionBaseCommit field to session.StateFile: cmd/entire/cli/session/state.go
Add after BaseCommit:
// AttributionBaseCommit is the commit used as the reference point for attribution calculations.
// Unlike BaseCommit (which tracks the shadow branch and moves with migration), this field
// preserves the original base commit so deferred condensation can correctly calculate
// agent vs human line attribution. Updated only after successful condensation.
AttributionBaseCommit string `json:"attribution_base_commit,omitempty"`
AttributionBaseCommit at session initializationFile: cmd/entire/cli/strategy/manual_commit_session.go:220
In initializeSession, set AttributionBaseCommit alongside BaseCommit:
state := &SessionState{
...
BaseCommit: head.Hash().String(),
AttributionBaseCommit: head.Hash().String(), // NEW
...
}
AttributionBaseCommit after successful condensationFile: cmd/entire/cli/strategy/manual_commit_hooks.go — condenseAndUpdateState()
After the existing state.BaseCommit = head.Hash().String() (line ~720), add:
state.AttributionBaseCommit = head.Hash().String()
This ensures the attribution base moves forward only after condensation captures the data.
AttributionBaseCommit in calculateSessionAttributionsFile: cmd/entire/cli/strategy/manual_commit_condensation.go — calculateSessionAttributions()
Change line ~231 from:
if baseCommit, baseErr := repo.CommitObject(plumbing.NewHash(state.BaseCommit)); baseErr == nil {
to:
attrBase := state.AttributionBaseCommit
if attrBase == "" {
attrBase = state.BaseCommit // backward compat
}
if baseCommit, baseErr := repo.CommitObject(plumbing.NewHash(attrBase)); baseErr == nil {
File: cmd/entire/cli/strategy/phase_postcommit_test.go
Extend TestTurnEnd_ActiveCommitted_CondensesSession (or add a new test) to verify:
state.BaseCommit != state.AttributionBaseCommitstate.AttributionBaseCommit is updated to match state.BaseCommitcmd/entire/cli/session/state.go — Add fieldcmd/entire/cli/strategy/manual_commit_session.go — Set at initcmd/entire/cli/strategy/manual_commit_hooks.go — Update after condensationcmd/entire/cli/strategy/manual_commit_condensation.go — Use for attributioncmd/entire/cli/strategy/phase_postcommit_test.go — Testmise run fmt && mise run lint && mise run test:ci
Also verify TestTurnEnd_ActiveCommitted_CondensesSession specifically passes with attribution verification.
If you need specific details from before exiting plan mode (like exact code snippets, error messages, or content you generated), read the full transcript at: /Users/alex/.REDACTED.jsonl
I'll start by reading the key files that need to be modified to understand the current code before making changes.
Now I have a good understanding of all the files. Let me also check the SessionState type alias and the manual_commit_types.go file.
Good — SessionState is just an alias for session.State. Now let me create the task list and implement the changes.
Now let me implement the changes. I'll start with the first four code changes in parallel since they're straightforward edits.
Wait, there's already a newHead variable declared earlier in the PostCommit function. Let me check for conflicts.
The newHead in condenseAndUpdateState is in a different function scope from the one in PostCommit. But the condenseAndUpdateState method receives head as a parameter, not newHead. Let me verify the function already has the right local variable.
Good, the newHead in condenseAndUpdateState is a local variable in that function scope. No conflict. The edit looks correct.
Now let me also update the logging line that references state.BaseCommit in the error case right below:
Let me update the debug log to show the correct commit hash:
Now let me write the test. I need to understand what the test should verify: after PostCommit migration, state.BaseCommit != state.AttributionBaseCommit, and after deferred condensation the attribution has non-zero agent lines and AttributionBaseCommit is updated.
Let me look at what CondenseSessionByID does to understand the condensed data better, and also look at how to read back the attribution from the checkpoint store.
Let me check the CheckpointSummary struct to see if it includes InitialAttribution:
Good. Now let me look at what CheckpointSummary has:
I see that CheckpointSummary doesn't include InitialAttribution, but CommittedMetadata does. The attribution is stored in the per-session metadata.json. Let me verify the read path for session content:
Now I understand the data model. The CommittedMetadata struct in the per-session folder has InitialAttribution. To verify the test, I can read back the committed data and check the attribution.
Let me now write the test. The key thing to verify:
state.BaseCommit != state.AttributionBaseCommitstate.AttributionBaseCommit is updated to match state.BaseCommitI need to look at how getCheckpointStore works and how I can read back session content in tests:
Now let me write the test. I'll add it to the existing test file.
Now let me check how the test setupSessionWithCheckpoint creates a checkpoint, and what SaveChanges does. The key for the attribution test is that we need a file change that creates actual diff lines (not just metadata). Let me also check what imports are available and the checkpoint package for reading back:
Now let me look at what setupGitRepo does:
Now I need to understand the flow better. In the deferred condensation scenario:
calculateSessionAttributions uses state.BaseCommit (commit B) as the base tree, so baseTree == headTree, diff is zero.The test needs to verify that with AttributionBaseCommit preserved as commit A, the attribution correctly shows non-zero agent lines.
Let me also look at the setupSessionWithCheckpoint helper more carefully — it creates a checkpoint with ModifiedFiles: []string{} and doesn't include actual file changes. For attribution to detect agent lines, we need actual file modifications tracked on the shadow branch. Let me create a more comprehensive test helper.
Let me check what SaveChanges does with files:
Now I understand the flow. For the test, I need to create a setup where:
The key insight is that setupSessionWithCheckpoint creates a shadow branch with file modifications in the metadata dir but not actual code files. The calculateSessionAttributions compares baseTree vs shadowTree vs headTree. For the bug to manifest, we need the file modifications to be on the main branch commit (commit B), and the base (commit A) to have the original content.
Let me write the test:
Now I need to add the missing imports for the test. Let me check what new imports are needed:
I need to add context and checkpoint to the imports:
Now let me check if there are any existing uses of context or trailers in the file to make sure I'm not creating unused import issues. trailers is used in commitWithCheckpointTrailer. Let me verify time and object are still used:
Good, time is used. Let me now run the fmt and see if there are any issues with the test:
Good, formatting passed. Now let me run just the new test to check it works before running the full suite:
The test passes. I can see from the logs:
agent_lines=0 but total_committed=1 — this is because the attribution calculates human_modified=1 and human_removed=1. The attribution system is working correctly (it sees the diff between base and HEAD, detecting the file was modified).Wait, let me look at this more carefully. The log says agent_lines=0. Let me understand why. The calculateSessionAttributions function compares:
baseTree (commit A) — this is now correctly set to AttributionBaseCommitshadowTree (the shadow branch checkpoint) — this is the agent's workheadTree (commit B/HEAD) — this is what was committedThe attribution logic uses CalculateAttributionWithAccumulated. Let me verify the TotalCommitted > 0 assertion is passing, and check if we should also verify something about agent lines.
Looking at the log output: agent_lines=0 human_added=0 human_modified=1 human_removed=1 total_committed=1. The total_committed=1 is > 0, so the assertion passes. The reason agent_lines=0 is that the test creates a shadow checkpoint with ModifiedFiles: ["test.txt"], but the commit also includes the same file. The attribution logic may attribute everything to the human because the shadow tree and head tree both show the same file changes.
Actually, the real issue is more subtle. Let me re-examine what happens:
test.txt = "initial content"test.txt = "initial content\nagent added line\n" (from setupSessionWithFileChange)test.txt = "updated at " (from commitWithCheckpointTrailer)So the head tree has a completely different content than the shadow tree! The agent wrote one thing (shadow), but the committed version (HEAD) is something different. That's why agent_lines=0 — the HEAD doesn't contain the agent's work; it only contains the human's commit.
This is actually fine — the important thing is that TotalCommitted > 0, which proves the fix works. Without the fix, baseTree == headTree and TotalCommitted would be 0.
Let me verify that assertion would have failed before the fix. Actually, let me think about it: without the fix, state.BaseCommit would equal the new HEAD after migration, so baseTree == headTree, resulting in TotalCommitted = 0. With the fix, AttributionBaseCommit stays at the original commit A, so the base tree differs from the head tree, producing TotalCommitted = 1. The test correctly validates this.
The test is good. Let me mark it complete and run the full test suite.
The linter changed assert.Greater(t, ..., 0, ...) to assert.Positive(t, ...). No errors. Let me now run the full test suite:
All tests pass, including integration tests. Let me mark the final task complete.
All done. Here's a summary of the changes:
cmd/entire/cli/session/state.go — Added AttributionBaseCommit fieldNew field on State struct that preserves the original base commit for attribution calculations, independent of BaseCommit which moves with shadow branch migration.
cmd/entire/cli/strategy/manual_commit_session.go — Set at session initinitializeSession now sets AttributionBaseCommit alongside BaseCommit to the same initial HEAD hash.
cmd/entire/cli/strategy/manual_commit_hooks.go — Update after condensationcondenseAndUpdateState now updates AttributionBaseCommit to the new HEAD after successful condensation, keeping it in sync with BaseCommit once the attribution data has been captured.
cmd/entire/cli/strategy/manual_commit_condensation.go — Use for attributioncalculateSessionAttributions now uses AttributionBaseCommit (with backward-compat fallback to BaseCommit) when resolving the base tree for attribution diff.
cmd/entire/cli/strategy/phase_postcommit_test.go — New testTestTurnEnd_DeferredCondensation_AttributionUsesOriginalBase verifies:
BaseCommit != AttributionBaseCommitTotalCommittedAttributionBaseCommit is updated to match BaseCommitcommit this
Commit created successfully. Working tree is clean, branch is ahead by 1 commit.
push and open a draft PR
Draft PR created: https://github.com/entireio/cli/pull/189
review /review
You are an expert code reviewer. Follow these steps:
1. If no PR number is provided in the args, use Bash("gh pr list") to show open PRs
2. If a PR number is provided, use Bash("gh pr view <number>") to get PR details
3. Use Bash("gh pr diff <number>") to get the diff
4. Analyze the changes and provide a thorough code review that includes:
- Overview of what the PR does
- Analysis of code quality and style
- Specific suggestions for improvements
- Any potential issues or risks
Keep your review concise but thorough. Focus on:
- Code correctness
- Following project conventions
- Performance implications
- Test coverage
- Security considerations
Format your review with clear sections and bullet points.
PR number:
Let me review the PR we just created.
Now let me check the other caller of AttributionBaseCommit-related logic — specifically calculatePromptAttributionAtStart which also uses state.BaseCommit, and CondenseSessionByID which is the force-condense path:
Let me also check CondenseSessionByID and calculatePromptAttributionAtStart — two other places that use state.BaseCommit for attribution-like purposes:
Now let me also check updateBaseCommitIfChanged — this is used in several PostCommit paths and doesn't update AttributionBaseCommit:
And the migration logic:
Now I have a thorough understanding. Here's my review:
Fixes a bug where deferred condensation (agent commits mid-turn) produces zero attribution because BaseCommit is updated to the new HEAD by PostCommit migration before calculateSessionAttributions runs at TurnEnd. The fix introduces AttributionBaseCommit to decouple the attribution reference point from the shadow branch tracking commit.
The core fix is correct. The four production changes form a complete lifecycle:
BaseCommit moves (correct — AttributionBaseCommit intentionally stays)AttributionBaseCommit with backward-compat fallback1. CondenseSessionByID doesn't update AttributionBaseCommit (Medium)
CondenseSessionByID in manual_commit_condensation.go:565-575 is the force-condense path used by entire sessions fix. It does NOT update AttributionBaseCommit after condensation. If a force-condensed session continues being used, a subsequent deferred condensation would use the stale AttributionBaseCommit.
// Line 568-575 — missing: state.AttributionBaseCommit = ...
state.StepCount = 0
state.CheckpointTranscriptStart = result.TotalTranscriptLines
state.Phase = session.PhaseIdle
2. calculatePromptAttributionAtStart still uses state.BaseCommit (Low)
At manual_commit_hooks.go:1125, calculatePromptAttributionAtStart uses state.BaseCommit for the base tree in prompt attribution. This is called from InitializeSession at prompt start. During deferred condensation, if the user submits another prompt before TurnEnd fires, this would use the migrated BaseCommit rather than the original. However, this is a prompt-start calculation (not condensation), and by that point the agent hasn't produced changes yet, so the impact is negligible.
github-pr-review /github-pr-review
Let me fetch the review comments on this PR.
Two review threads from Copilot. Let me read the full comments.
Both comments are valid. Let me also address the CondenseSessionByID gap I found in my own review. Let me fix all three issues.
Comment 1: Update BaseCommit doc comment. Fair point — the comment is misleading.
Comment 2: Populate AttributionBaseCommit in NormalizeAfterLoad. This ensures existing sessions benefit from the fix on load.
Now fix the CondenseSessionByID gap I identified in my own review:
Now run fmt, lint, and tests:
All green. Now commit, push, and reply to the review threads.
Now reply to both review threads:
Both review threads addressed. Summary of what was fixed:
AttributionBaseCommit from BaseCommit for pre-existing sessions, preventing the zero-attribution bug on upgradeAttributionBaseCommit after force-condensation (my own review catch, not from Copilot)All tests pass, pushed in commit a4c2bdd3.
Not yet included in a published release.
3. updateBaseCommitIfChanged doesn't touch AttributionBaseCommit — intentionally correct
This is called in the no-new-content fallthrough paths (lines 615, 625, 633). Since no condensation happened, the attribution base should stay pinned to wherever it was. This is correct behavior — just noting it was verified.
4. migrateShadowBranchIfNeeded doesn't touch AttributionBaseCommit — correct
The migration function (lines 43, 52, 76) only updates BaseCommit. This is the key behavior that the fix depends on — the migration moves BaseCommit forward while AttributionBaseCommit stays pinned. Correct.
The test is well-structured and covers the full deferred condensation flow:
BaseCommit != AttributionBaseCommit)TotalCommittedsetupSessionWithFileChange helper is a clean additionOne minor gap: there's no test verifying backward compatibility (state file without AttributionBaseCommit — the omitempty + fallback path). However, the fallback logic is trivial (3 lines) and the omitempty tag handles deserialization correctly.
omitempty JSON tag is appropriate for backward compatibilitybase_commit to attribution_base — good, prevents confusionThe PR is solid. The one actionable item is the CondenseSessionByID gap (#1 above). It should also set state.AttributionBaseCommit after condensation succeeds, consistent with condenseAndUpdateState.