fix(attribution): scope checkpoint subagent tokens to session cumulative · Entire
fix(attribution): scope checkpoint subagent tokens to session cumulative
ddbfb57→main·
suhaanthayyil·4d ago·4 files·+346 added/-28 removed
SaveStep re-subtracted SubagentTokensBaseline from CheckpointTokenUsage.SubagentTokens on every step, mutating an already-rescoped value in place. accumulateTokenUsage only REPLACES SubagentTokens when the incoming step carries a non-nil snapshot, so a later step in the same checkpoint window with a nil SubagentTokens kept the field at its already baseline-subtracted value and the block subtracted the baseline again. That double-subtracts and, via clampSubtract, shrinks or zeroes a real per-checkpoint subagent total despite genuine subagent usage.
Derive the checkpoint delta fresh each call from the session-wide cumulative (state.TokenUsage.SubagentTokens) minus the baseline, which is idempotent whether or not this step carried a snapshot.
Extract the shared StepCount / CheckpointTokenUsage / baseline reset into resetCheckpointWindow and call it at all three condensation reset sites (CondenseSessionByID, CondenseAndMarkFullyCondensed, condenseAndUpdateState) so the baseline capture cannot drift between them.
Add regression coverage: a checkpoint window that drops SubagentTokens mid-window, an edge matrix (nil first step, growth, repeated nil steps), and a test that drives real condensation via CondenseSessionByID so the production baseline snapshot is exercised where it lives rather than hand-simulated.
Changes
4
cmd/entire/cli/strategy
Mmanual_commit_condensation.go+2/-18
Mmanual_commit_git.go+30/-1
Mmanual_commit_hooks.go+1/-9
Msubagent_token_dedup_test.go+313
1206 unmodified lines
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1210
1211
1212
1213
111 unmodified lines
1325
1326
1327
1336
1337
1338
1339
1340
1341
1342
1343
1344
1328
1329
1330
1331
1206 unmodified lines
slog.Int("checkpoints_condensed", result.CheckpointsCount),
)
state.StepCount = 0
state.CheckpointTokenUsage = nil
// Snapshot the cumulative subagent total at this reset so the next
// checkpoint's CheckpointTokenUsage.SubagentTokens can be rescoped to
// "since this condensation" instead of re-reporting everything counted
// so far (see accumulateTokenUsage).
if state.TokenUsage != nil {
state.SubagentTokensBaseline = state.TokenUsage.SubagentTokens
}
resetCheckpointWindow(state)
state.CheckpointTranscriptStart = result.TotalTranscriptLines
state.CheckpointTranscriptSize = int64(len(result.Transcript))
state.Phase = session.PhaseIdle
111 unmodified lines
return nil
}
state.StepCount = 0
state.CheckpointTokenUsage = nil
// Snapshot the cumulative subagent total at this reset so the next
// checkpoint's CheckpointTokenUsage.SubagentTokens can be rescoped to
// "since this condensation" instead of re-reporting everything counted
// so far (see accumulateTokenUsage).
if state.TokenUsage != nil {
state.SubagentTokensBaseline = state.TokenUsage.SubagentTokens
}
resetCheckpointWindow(state)
state.CheckpointTranscriptStart = result.TotalTranscriptLines
state.LastCheckpointID = checkpointID
state.LastCheckpointCommitHash = state.BaseCommit
Mcmd/entire/cli/strategy/manual_commit_condensation.go+2/-18
133 unmodified lines
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
139
151
152
153
154
227 unmodified lines
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
133 unmodified lines
// subtracting the baseline captured at the last reset, otherwise the
// full cumulative subagent total would be reported again at every
// checkpoint instead of just this checkpoint's share.
//
// Derive the checkpoint delta FRESH each call from the session-wide
// cumulative (state.TokenUsage.SubagentTokens) minus the baseline —
// do NOT mutate CheckpointTokenUsage.SubagentTokens in place. A later
// step in the same window can carry step.TokenUsage != nil but
// SubagentTokens == nil (the subagent transcript was cleaned up, so
// CalculateTotalTokenUsage returned APICallCount==0 and left it nil);
// accumulateTokenUsage then leaves CheckpointTokenUsage.SubagentTokens
// at its already-rescoped value, and re-subtracting the baseline from
// that would double-subtract and (via clampSubtract) shrink or zero a
// real subagent total. Recomputing from the session-wide cumulative
// is idempotent regardless of whether this step carried a snapshot.
if state.CheckpointTokenUsage != nil {
state.CheckpointTokenUsage.SubagentTokens = types.SubtractTokenUsage(
state.CheckpointTokenUsage.SubagentTokens, state.SubagentTokensBaseline)
state.TokenUsage.SubagentTokens, state.SubagentTokensBaseline)
}
}
227 unmodified lines
return existing
}
// resetCheckpointWindow resets the per-checkpoint accumulation window after a
// condensation reset. It zeroes the step count, clears the checkpoint-scoped
// token usage, and snapshots the cumulative subagent total into
// SubagentTokensBaseline so the next window's CheckpointTokenUsage.SubagentTokens
// can be rescoped to "since this condensation" rather than re-reporting the full
// cumulative subagent total (see accumulateTokenUsage and the SaveStep rescoping
// in this file, plus SessionState.SubagentTokensBaseline). Shared by all three
// condensation reset sites (CondenseSessionByID, CondenseAndMarkFullyCondensed,
// condenseAndUpdateState) so the baseline capture cannot drift between them.
func resetCheckpointWindow(state *SessionState) {
state.StepCount = 0
state.CheckpointTokenUsage = nil
if state.TokenUsage != nil {
state.SubagentTokensBaseline = state.TokenUsage.SubagentTokens
}
}
// deleteShadowBranch deletes a shadow branch by name.
// Returns nil if the branch doesn't exist (idempotent).
// Uses git CLI instead of go-git's RemoveReference because go-git v5
Mcmd/entire/cli/strategy/manual_commit_git.go+30/-1
1406 unmodified lines
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1410
1411
1412
1413
1406 unmodified lines
newHead := head.Hash().String()
state.BaseCommit = newHead
state.RealignAttributionBase(newHead)
state.StepCount = 0
state.CheckpointTokenUsage = nil
// Snapshot the cumulative subagent total at this reset so the next
// checkpoint's CheckpointTokenUsage.SubagentTokens can be rescoped to
// "since this condensation" instead of re-reporting everything counted
// so far (see accumulateTokenUsage in manual_commit_git.go).
if state.TokenUsage != nil {
state.SubagentTokensBaseline = state.TokenUsage.SubagentTokens
}
resetCheckpointWindow(state)
state.CheckpointTranscriptStart = result.TotalTranscriptLines
state.CheckpointTranscriptSize = int64(len(result.Transcript))
Mcmd/entire/cli/strategy/manual_commit_hooks.go+1/-9
1 unmodified line
2
3
4
5
6
7
8
183 unmodified lines
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
1 unmodified line
import (
"context"
"fmt"
"os"
"path/filepath"
"testing"
183 unmodified lines
})
}
}
// TestSaveStep_SubagentBaselineNotDoubleSubtractedWhenLaterStepDropsSubagent
// pins the double-subtraction bug: within a single checkpoint window, once a
// step has set CheckpointTokenUsage.SubagentTokens (rescoped by subtracting the
// baseline), a LATER step whose TokenUsage is non-nil but carries no
// SubagentTokens (subagent transcript cleaned up, so CalculateTotalTokenUsage
// returns APICallCount==0 and leaves SubagentTokens nil) must not cause the
// baseline to be subtracted a second time. accumulateTokenUsage only REPLACES
// SubagentTokens when the incoming snapshot is non-nil, so a nil-subagent step
// leaves CheckpointTokenUsage.SubagentTokens at its already-rescoped value; a
// per-step re-subtraction would shrink (and via clampSubtract zero) a real
// subagent total. The checkpoint delta must be derived FRESH each call from the
// session-wide cumulative snapshot minus the baseline instead.
func TestSaveStep_SubagentBaselineNotDoubleSubtractedWhenLaterStepDropsSubagent(t *testing.T) {
agentTypes := []types.AgentType{agent.AgentTypeClaudeCode, agent.AgentTypeFactoryAIDroid}
for _, agentType := range agentTypes {
t.Run(string(agentType), func(t *testing.T) {
dir := t.TempDir()
testutil.InitRepo(t, dir)
repo, err := git.PlainOpen(dir)
require.NoError(t, err)
worktree, err := repo.Worktree()
require.NoError(t, err)
require.NoError(t, os.WriteFile(filepath.Join(dir, "test.txt"), []byte("v1"), 0o644))
_, err = worktree.Add("test.txt")
require.NoError(t, err)
_, err = worktree.Commit("Initial commit", &git.CommitOptions{
Author: &object.Signature{Name: "Test", Email: "test@test.com", When: time.Now()},
})
require.NoError(t, err)
t.Chdir(dir)
ctx := context.Background()
s := &ManualCommitStrategy{}
sessionID := "2026-07-13-subagent-nodouble-" + string(agentType)
metadataDir := ".entire/metadata/" + sessionID
metadataDirAbs := filepath.Join(dir, metadataDir)
require.NoError(t, os.MkdirAll(metadataDirAbs, 0o755))
transcript := `{"type":"human","message":{"content":"test"}}` + "\n"
require.NoError(t, os.WriteFile(filepath.Join(metadataDirAbs, paths.TranscriptFileName), []byte(transcript), 0o644))
// Checkpoint 1: a subagent is discovered with cumulative usage 500/250.
require.NoError(t, s.SaveStep(ctx, StepContext{
SessionID: sessionID,
MetadataDir: metadataDir,
MetadataDirAbs: metadataDirAbs,
ModifiedFiles: []string{"test.txt"},
CommitMessage: "checkpoint 1",
AuthorName: "Test",
AuthorEmail: "test@test.com",
AgentType: agentType,
TokenUsage: &agent.TokenUsage{
InputTokens: 100, OutputTokens: 50, APICallCount: 1,
SubagentTokens: &agent.TokenUsage{InputTokens: 500, OutputTokens: 250, APICallCount: 5},
},
}))
// Condensation reset: baseline snapshots the cumulative subagent total.
require.NoError(t, MutateSessionState(ctx, sessionID, func(st *SessionState) error {
st.StepCount = 0
st.CheckpointTokenUsage = nil
if st.TokenUsage != nil {
st.SubagentTokensBaseline = st.TokenUsage.SubagentTokens
}
st.CheckpointTranscriptStart = 10
return nil
}))
// Checkpoint 2, step 1: the subagent has grown to 620/310. The
// checkpoint delta must be 620-500 / 310-250 = 120 / 60.
require.NoError(t, os.WriteFile(filepath.Join(dir, "test.txt"), []byte("v2"), 0o644))
require.NoError(t, s.SaveStep(ctx, StepContext{
SessionID: sessionID,
MetadataDir: metadataDir,
MetadataDirAbs: metadataDirAbs,
ModifiedFiles: []string{"test.txt"},
CommitMessage: "checkpoint 2 step 1",
AuthorName: "Test",
AuthorEmail: "test@test.com",
AgentType: agentType,
TokenUsage: &agent.TokenUsage{
InputTokens: 100, OutputTokens: 50, APICallCount: 1,
SubagentTokens: &agent.TokenUsage{InputTokens: 620, OutputTokens: 310, APICallCount: 6},
},
}))
// Checkpoint 2, step 2: same window, but this step's TokenUsage carries
// NO SubagentTokens (the subagent transcript was cleaned up, so
// CalculateTotalTokenUsage found APICallCount==0 and left SubagentTokens
// nil). accumulateTokenUsage will not replace SubagentTokens, so it stays
// at the checkpoint-1-baseline-subtracted 120/60 — and the baseline must
// NOT be subtracted again.
require.NoError(t, os.WriteFile(filepath.Join(dir, "test.txt"), []byte("v3"), 0o644))
require.NoError(t, s.SaveStep(ctx, StepContext{
SessionID: sessionID,
MetadataDir: metadataDir,
MetadataDirAbs: metadataDirAbs,
ModifiedFiles: []string{"test.txt"},
CommitMessage: "checkpoint 2 step 2",
AuthorName: "Test",
AuthorEmail: "test@test.com",
AgentType: agentType,
TokenUsage: &agent.TokenUsage{
InputTokens: 100, OutputTokens: 50, APICallCount: 1,
// SubagentTokens intentionally nil.
},
}))
state, err := s.loadSessionState(ctx, sessionID)
require.NoError(t, err)
// Session-wide total keeps the latest cumulative snapshot (620/310):
// the nil-subagent step must not clobber or shrink it.
require.NotNil(t, state.TokenUsage.SubagentTokens)
require.Equal(t, 620, state.TokenUsage.SubagentTokens.InputTokens,
"session-wide subagent total must retain the latest cumulative snapshot")
require.Equal(t, 310, state.TokenUsage.SubagentTokens.OutputTokens)
// Checkpoint delta must remain the checkpoint-1-baseline-subtracted
// 120/60, NOT 620-500-500 clamped to 0. This is the regression.
require.NotNil(t, state.CheckpointTokenUsage)
require.NotNil(t, state.CheckpointTokenUsage.SubagentTokens)
require.Equal(t, 120, state.CheckpointTokenUsage.SubagentTokens.InputTokens,
"baseline must be subtracted once, not re-subtracted on a later nil-subagent step")
require.Equal(t, 60, state.CheckpointTokenUsage.SubagentTokens.OutputTokens)
// Main-agent deltas still sum across all three steps in the window.
require.Equal(t, 200, state.CheckpointTokenUsage.InputTokens,
"main-agent deltas sum across checkpoint-2 steps")
})
}
}
// TestSaveStep_CheckpointSubagentAlwaysDerivedFromSessionCumulative walks the
// finding-1 edge matrix in one window after a baseline reset: a nil-subagent
// first step, a step that grows the subagent, then repeated nil-subagent steps.
// After every step the checkpoint subagent total must equal the session-wide
// cumulative minus the baseline (idempotent), never drifting from repeated
// subtraction. The strategy-layer accounting is agent-agnostic, so one agent
// exercises it.
func TestSaveStep_CheckpointSubagentAlwaysDerivedFromSessionCumulative(t *testing.T) {
dir := t.TempDir()
testutil.InitRepo(t, dir)
repo, err := git.PlainOpen(dir)
require.NoError(t, err)
worktree, err := repo.Worktree()
require.NoError(t, err)
require.NoError(t, os.WriteFile(filepath.Join(dir, "test.txt"), []byte("v0"), 0o644))
_, err = worktree.Add("test.txt")
require.NoError(t, err)
_, err = worktree.Commit("Initial commit", &git.CommitOptions{
Author: &object.Signature{Name: "Test", Email: "test@test.com", When: time.Now()},
})
require.NoError(t, err)
t.Chdir(dir)
ctx := context.Background()
s := &ManualCommitStrategy{}
sessionID := "2026-07-13-subagent-edgematrix"
metadataDir := ".entire/metadata/" + sessionID
metadataDirAbs := filepath.Join(dir, metadataDir)
require.NoError(t, os.MkdirAll(metadataDirAbs, 0o755))
require.NoError(t, os.WriteFile(filepath.Join(metadataDirAbs, paths.TranscriptFileName),
[]byte(`{"type":"human","message":{"content":"test"}}`+"\n"), 0o644))
rev := 0
save := func(sub *agent.TokenUsage) {
rev++
require.NoError(t, os.WriteFile(filepath.Join(dir, "test.txt"), []byte(fmt.Sprintf("rev%d", rev)), 0o644))
require.NoError(t, s.SaveStep(ctx, StepContext{
SessionID: sessionID,
MetadataDir: metadataDir,
MetadataDirAbs: metadataDirAbs,
ModifiedFiles: []string{"test.txt"},
CommitMessage: fmt.Sprintf("step %d", rev),
AuthorName: "Test",
AuthorEmail: "test@test.com",
AgentType: agent.AgentTypeClaudeCode,
TokenUsage: &agent.TokenUsage{InputTokens: 10, APICallCount: 1, SubagentTokens: sub},
}))
}
// checkpointSubIn returns the current checkpoint subagent InputTokens (0 when nil).
checkpointSubIn := func() int {
st, loadErr := s.loadSessionState(ctx, sessionID)
require.NoError(t, loadErr)
if st.CheckpointTokenUsage == nil || st.CheckpointTokenUsage.SubagentTokens == nil {
return 0
}
return st.CheckpointTokenUsage.SubagentTokens.InputTokens
}
// Establish a baseline of 400 via a first window + reset.
save(&agent.TokenUsage{InputTokens: 400, APICallCount: 4})
require.NoError(t, MutateSessionState(ctx, sessionID, func(st *SessionState) error {
st.StepCount = 0
st.CheckpointTokenUsage = nil
st.SubagentTokensBaseline = st.TokenUsage.SubagentTokens // 400
st.CheckpointTranscriptStart = 5
return nil
}))
// Edge: nil first step of the window — cumulative stays 400, delta 0.
save(nil)
require.Equal(t, 0, checkpointSubIn(), "nil first step: delta is cumulative(400)-baseline(400)=0")
// Growth step — cumulative 550, delta 150.
save(&agent.TokenUsage{InputTokens: 550, APICallCount: 5})
require.Equal(t, 150, checkpointSubIn(), "growth step: delta is 550-400")
// Repeated nil steps must NOT shrink the delta (idempotent derive-fresh).
save(nil)
require.Equal(t, 150, checkpointSubIn(), "nil step must not re-subtract baseline")
save(nil)
require.Equal(t, 150, checkpointSubIn(), "second nil step must not re-subtract baseline")
}
// TestCondenseSessionByID_CapturesSubagentBaselineViaRealResetPath drives a REAL
// condensation (CondenseSessionByID) rather than hand-simulating the reset, so
// the production baseline-snapshot code in resetCheckpointWindow — shared by the
// three condensation reset sites — is exercised where it actually lives. It then
// runs a follow-up checkpoint to prove the baseline captured by the real path is
// used to rescope the next checkpoint's subagent delta.
func TestCondenseSessionByID_CapturesSubagentBaselineViaRealResetPath(t *testing.T) {
dir := t.TempDir()
testutil.InitRepo(t, dir)
repo, err := git.PlainOpen(dir)
require.NoError(t, err)
t.Chdir(dir)
ctx := context.Background()
s := &ManualCommitStrategy{}
sessionID := "2026-07-13-subagent-realreset"
metadataDir := ".entire/metadata/" + sessionID
metadataDirAbs := filepath.Join(dir, metadataDir)
require.NoError(t, os.MkdirAll(metadataDirAbs, 0o755))
transcript := `{"type":"human","message":{"content":"do the thing"}}
{"type":"assistant","message":{"content":"working on it"}}
`
require.NoError(t, os.WriteFile(filepath.Join(metadataDirAbs, paths.TranscriptFileName), []byte(transcript), 0o644))
// Checkpoint 1: subagent discovered with cumulative usage 500/250.
require.NoError(t, os.WriteFile(filepath.Join(dir, "test.txt"), []byte("v2"), 0o644))
require.NoError(t, s.SaveStep(ctx, StepContext{
SessionID: sessionID,
MetadataDir: metadataDir,
MetadataDirAbs: metadataDirAbs,
ModifiedFiles: []string{"test.txt"},
CommitMessage: "checkpoint 1",
AuthorName: "Test",
AuthorEmail: "test@test.com",
AgentType: agent.AgentTypeClaudeCode,
TokenUsage: &agent.TokenUsage{
InputTokens: 100, OutputTokens: 50, APICallCount: 1,
SubagentTokens: &agent.TokenUsage{InputTokens: 500, OutputTokens: 250, APICallCount: 5},
},
}))
// Drive the REAL condensation reset path (not a hand-simulated one). This
// executes resetCheckpointWindow inside CondenseSessionByID.
require.NoError(t, s.CondenseSessionByID(ctx, sessionID))
state, err := s.loadSessionState(ctx, sessionID)
require.NoError(t, err)
require.Equal(t, 0, state.StepCount, "real condensation must reset StepCount")
require.Nil(t, state.CheckpointTokenUsage, "real condensation must clear CheckpointTokenUsage")
require.NotNil(t, state.SubagentTokensBaseline,
"real condensation must snapshot the subagent baseline")
require.Equal(t, 500, state.SubagentTokensBaseline.InputTokens,
"baseline must capture the cumulative subagent total at condensation")
require.Equal(t, 250, state.SubagentTokensBaseline.OutputTokens)
// Checkpoint 2 after the real reset: the subagent grew to 620/310. Its
// checkpoint delta must be rescoped against the real-path baseline (120/60).
require.NoError(t, os.WriteFile(filepath.Join(dir, "test.txt"), []byte("v3"), 0o644))
require.NoError(t, s.SaveStep(ctx, StepContext{
SessionID: sessionID,
MetadataDir: metadataDir,
MetadataDirAbs: metadataDirAbs,
ModifiedFiles: []string{"test.txt"},
CommitMessage: "checkpoint 2",
AuthorName: "Test",
AuthorEmail: "test@test.com",
AgentType: agent.AgentTypeClaudeCode,
TokenUsage: &agent.TokenUsage{
InputTokens: 100, OutputTokens: 50, APICallCount: 1,
SubagentTokens: &agent.TokenUsage{InputTokens: 620, OutputTokens: 310, APICallCount: 6},
},
}))
state2, err := s.loadSessionState(ctx, sessionID)
require.NoError(t, err)
require.NotNil(t, state2.CheckpointTokenUsage)
require.NotNil(t, state2.CheckpointTokenUsage.SubagentTokens)
require.Equal(t, 120, state2.CheckpointTokenUsage.SubagentTokens.InputTokens,
"checkpoint delta must be rescoped against the real-path baseline")
require.Equal(t, 60, state2.CheckpointTokenUsage.SubagentTokens.OutputTokens)
}