|
| 1 | +package strategy |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "os" |
| 7 | + "path/filepath" |
| 8 | + "testing" |
| 9 | + |
| 10 | + "github.com/entireio/cli/cmd/entire/cli/agent" |
| 11 | + "github.com/entireio/cli/cmd/entire/cli/checkpoint" |
| 12 | + "github.com/entireio/cli/cmd/entire/cli/checkpoint/id" |
| 13 | + "github.com/entireio/cli/cmd/entire/cli/paths" |
| 14 | + "github.com/go-git/go-git/v6" |
| 15 | + "github.com/go-git/go-git/v6/plumbing" |
| 16 | + "github.com/stretchr/testify/require" |
| 17 | +) |
| 18 | + |
| 19 | +// TestCondenseSession_CommittedCheckpointCarriesSubagentTokens pins the |
| 20 | +// checkpoint-scoped subagent total onto the committed checkpoint's metadata. |
| 21 | +// |
| 22 | +// Condensation recomputes token usage from the transcript with subagentsDir="", |
| 23 | +// which by contract leaves SubagentTokens nil, and that recomputed value overwrote |
| 24 | +// the checkpoint-scoped total SaveStep had already rescoped into |
| 25 | +// state.CheckpointTokenUsage. Result: committed checkpoints reported |
| 26 | +// "subagent_tokens": null even for sessions that ran many subagents (0 of 30 |
| 27 | +// sampled real checkpoints carried one). |
| 28 | +func TestCondenseSession_CommittedCheckpointCarriesSubagentTokens(t *testing.T) { |
| 29 | + dir := setupGitRepo(t) |
| 30 | + t.Chdir(dir) |
| 31 | + |
| 32 | + repo, err := git.PlainOpen(dir) |
| 33 | + require.NoError(t, err) |
| 34 | + |
| 35 | + ctx := context.Background() |
| 36 | + s := &ManualCommitStrategy{} |
| 37 | + sessionID := "2026-08-10-condense-subagent-tokens" |
| 38 | + |
| 39 | + metadataDir := ".entire/metadata/" + sessionID |
| 40 | + metadataDirAbs := filepath.Join(dir, metadataDir) |
| 41 | + require.NoError(t, os.MkdirAll(metadataDirAbs, 0o755)) |
| 42 | + |
| 43 | + // The assistant line carries real usage, so the transcript recompute fires and |
| 44 | + // produces main-agent tokens with no SubagentTokens — the overwrite this test |
| 45 | + // guards against. |
| 46 | + transcript := `{"type":"human","message":{"content":"delegate to a subagent"}} |
| 47 | +{"type":"assistant","uuid":"a1","message":{"id":"m1","usage":{"input_tokens":300,"output_tokens":150}}} |
| 48 | +` |
| 49 | + require.NoError(t, os.WriteFile(filepath.Join(metadataDirAbs, paths.TranscriptFileName), []byte(transcript), 0o644)) |
| 50 | + require.NoError(t, os.WriteFile(filepath.Join(dir, "test.txt"), []byte("agent-modified"), 0o644)) |
| 51 | + |
| 52 | + require.NoError(t, s.SaveStep(ctx, StepContext{ |
| 53 | + SessionID: sessionID, |
| 54 | + MetadataDir: metadataDir, |
| 55 | + MetadataDirAbs: metadataDirAbs, |
| 56 | + ModifiedFiles: []string{"test.txt"}, |
| 57 | + CommitMessage: "checkpoint 1", |
| 58 | + AuthorName: "Test", |
| 59 | + AuthorEmail: "test@test.com", |
| 60 | + AgentType: agent.AgentTypeClaudeCode, |
| 61 | + TokenUsage: &agent.TokenUsage{ |
| 62 | + InputTokens: 100, OutputTokens: 50, APICallCount: 1, |
| 63 | + SubagentTokens: &agent.TokenUsage{InputTokens: 500, OutputTokens: 250, APICallCount: 5}, |
| 64 | + }, |
| 65 | + })) |
| 66 | + |
| 67 | + state, err := s.loadSessionState(ctx, sessionID) |
| 68 | + require.NoError(t, err) |
| 69 | + require.NotNil(t, state.CheckpointTokenUsage.SubagentTokens, |
| 70 | + "precondition: SaveStep records the checkpoint-scoped subagent total") |
| 71 | + |
| 72 | + checkpointID := id.MustCheckpointID("aabbccdd3344") |
| 73 | + result, err := s.CondenseSession(ctx, repo, checkpointID, state, nil) |
| 74 | + require.NoError(t, err) |
| 75 | + require.False(t, result.Skipped, "condensation must not skip when files are touched") |
| 76 | + |
| 77 | + summary := readCheckpointSummary(t, repo, checkpointID) |
| 78 | + require.NotNil(t, summary.TokenUsage, "committed checkpoint must carry token usage") |
| 79 | + require.NotNil(t, summary.TokenUsage.SubagentTokens, |
| 80 | + "committed checkpoint must carry the checkpoint-scoped subagent total") |
| 81 | + require.Equal(t, 500, summary.TokenUsage.SubagentTokens.InputTokens) |
| 82 | + require.Equal(t, 250, summary.TokenUsage.SubagentTokens.OutputTokens) |
| 83 | + require.Equal(t, 5, summary.TokenUsage.SubagentTokens.APICallCount) |
| 84 | + |
| 85 | + // The session-wide cumulative must survive the fill untouched. The fill copies |
| 86 | + // rather than mutates precisely because state.TokenUsage can alias the |
| 87 | + // checkpoint usage (applyBackfilledSessionTokenUsage adopts it for Copilot CLI); |
| 88 | + // mutating in place would overwrite the cumulative with this window's delta and |
| 89 | + // make resetCheckpointWindow snapshot a too-small baseline for the next window. |
| 90 | + require.NotNil(t, state.TokenUsage.SubagentTokens, |
| 91 | + "session-wide cumulative subagent total must survive condensation") |
| 92 | + require.Equal(t, 500, state.TokenUsage.SubagentTokens.InputTokens) |
| 93 | + require.Equal(t, 250, state.TokenUsage.SubagentTokens.OutputTokens) |
| 94 | +} |
| 95 | + |
| 96 | +// TestCondenseSession_SubagentTokensStayScopedToCheckpointWindow covers the second |
| 97 | +// checkpoint of a session: the committed value must be that window's delta, not the |
| 98 | +// session-wide cumulative, so summing checkpoints does not over-count. |
| 99 | +func TestCondenseSession_SubagentTokensStayScopedToCheckpointWindow(t *testing.T) { |
| 100 | + dir := setupGitRepo(t) |
| 101 | + t.Chdir(dir) |
| 102 | + |
| 103 | + repo, err := git.PlainOpen(dir) |
| 104 | + require.NoError(t, err) |
| 105 | + |
| 106 | + ctx := context.Background() |
| 107 | + s := &ManualCommitStrategy{} |
| 108 | + sessionID := "2026-08-10-condense-subagent-window" |
| 109 | + |
| 110 | + metadataDir := ".entire/metadata/" + sessionID |
| 111 | + metadataDirAbs := filepath.Join(dir, metadataDir) |
| 112 | + require.NoError(t, os.MkdirAll(metadataDirAbs, 0o755)) |
| 113 | + transcript := `{"type":"human","message":{"content":"delegate again"}} |
| 114 | +{"type":"assistant","uuid":"a1","message":{"id":"m1","usage":{"input_tokens":300,"output_tokens":150}}} |
| 115 | +` |
| 116 | + require.NoError(t, os.WriteFile(filepath.Join(metadataDirAbs, paths.TranscriptFileName), []byte(transcript), 0o644)) |
| 117 | + |
| 118 | + saveStep := func(commitMsg, content string, subagent *agent.TokenUsage) { |
| 119 | + require.NoError(t, os.WriteFile(filepath.Join(dir, "test.txt"), []byte(content), 0o644)) |
| 120 | + require.NoError(t, s.SaveStep(ctx, StepContext{ |
| 121 | + SessionID: sessionID, |
| 122 | + MetadataDir: metadataDir, |
| 123 | + MetadataDirAbs: metadataDirAbs, |
| 124 | + ModifiedFiles: []string{"test.txt"}, |
| 125 | + CommitMessage: commitMsg, |
| 126 | + AuthorName: "Test", |
| 127 | + AuthorEmail: "test@test.com", |
| 128 | + AgentType: agent.AgentTypeClaudeCode, |
| 129 | + TokenUsage: &agent.TokenUsage{ |
| 130 | + InputTokens: 100, OutputTokens: 50, APICallCount: 1, |
| 131 | + SubagentTokens: subagent, |
| 132 | + }, |
| 133 | + })) |
| 134 | + } |
| 135 | + |
| 136 | + // Checkpoint 1: subagent cumulative 500/250. Condense through |
| 137 | + // CondenseSessionByID so the real reset path runs and snapshots the baseline — |
| 138 | + // CondenseSession alone does not reset the window (its callers do). |
| 139 | + saveStep("checkpoint 1", "v2", &agent.TokenUsage{InputTokens: 500, OutputTokens: 250, APICallCount: 5}) |
| 140 | + require.NoError(t, s.CondenseSessionByID(ctx, sessionID)) |
| 141 | + |
| 142 | + stateReset, err := s.loadSessionState(ctx, sessionID) |
| 143 | + require.NoError(t, err) |
| 144 | + require.NotNil(t, stateReset.SubagentTokensBaseline, "precondition: reset snapshots the baseline") |
| 145 | + require.Equal(t, 500, stateReset.SubagentTokensBaseline.InputTokens) |
| 146 | + |
| 147 | + // Checkpoint 2: the subagent grew to 620/310 cumulative — a 120/60 delta. |
| 148 | + saveStep("checkpoint 2", "v3", &agent.TokenUsage{InputTokens: 620, OutputTokens: 310, APICallCount: 6}) |
| 149 | + state2, err := s.loadSessionState(ctx, sessionID) |
| 150 | + require.NoError(t, err) |
| 151 | + secondID := id.MustCheckpointID("aabbccdd7788") |
| 152 | + _, err = s.CondenseSession(ctx, repo, secondID, state2, nil) |
| 153 | + require.NoError(t, err) |
| 154 | + |
| 155 | + summary := readCheckpointSummary(t, repo, secondID) |
| 156 | + require.NotNil(t, summary.TokenUsage) |
| 157 | + require.NotNil(t, summary.TokenUsage.SubagentTokens) |
| 158 | + require.Equal(t, 120, summary.TokenUsage.SubagentTokens.InputTokens, |
| 159 | + "second checkpoint must carry its window's delta, not the session cumulative") |
| 160 | + require.Equal(t, 60, summary.TokenUsage.SubagentTokens.OutputTokens) |
| 161 | +} |
| 162 | + |
| 163 | +// readCheckpointSummary reads a committed checkpoint's root CheckpointSummary off |
| 164 | +// the metadata branch. |
| 165 | +func readCheckpointSummary(t *testing.T, repo *git.Repository, checkpointID id.CheckpointID) checkpoint.CheckpointSummary { |
| 166 | + t.Helper() |
| 167 | + |
| 168 | + ref, err := repo.Reference(plumbing.NewBranchReferenceName(paths.MetadataBranchName), true) |
| 169 | + require.NoError(t, err) |
| 170 | + commit, err := repo.CommitObject(ref.Hash()) |
| 171 | + require.NoError(t, err) |
| 172 | + tree, err := commit.Tree() |
| 173 | + require.NoError(t, err) |
| 174 | + checkpointTree, err := tree.Tree(checkpointID.Path()) |
| 175 | + require.NoError(t, err) |
| 176 | + rootMeta, err := checkpointTree.File(paths.MetadataFileName) |
| 177 | + require.NoError(t, err) |
| 178 | + rootBytes, err := rootMeta.Contents() |
| 179 | + require.NoError(t, err) |
| 180 | + |
| 181 | + var summary checkpoint.CheckpointSummary |
| 182 | + require.NoError(t, json.Unmarshal([]byte(rootBytes), &summary)) |
| 183 | + return summary |
| 184 | +} |
0 commit comments