Implement the following plan: Fix: Droid Token Usage Offset Mismatch Context…
- User
Implement the following plan:
Fix: Droid Token Usage Offset Mismatch
Context
calculateTokenUsageinmanual_commit_condensation.gohas a bug for Droid transcripts. ThestartOffsetparameter is a raw JSONL line count (fromcountTranscriptItems), but it's used as an index into the array returned byParseDroidTranscriptFromBytes, which filters out non-message entries (session_start,session_event, etc.). This causes incorrect token counting — either under-counting (off by N non-message entries) or over-counting all tokens when the offset exceeds the filtered array length.The file-based
ParseDroidTranscript(path, startLine)already handles this correctly by applying the offset at the raw line level before filtering. The byte-basedParseDroidTranscriptFromBytesdoes not accept an offset parameter.Approach: Add
startLineparameter toParseDroidTranscriptFromBytesThis mirrors the existing
ParseDroidTranscript(path, startLine)API. All existing callers pass0(no behavioral change), and the bug site passesstartOffset.Option B (changing
countTranscriptItemsto count only messages for Droid) was rejected because it would breaktranscript.SliceFromLinescoping (line 230) andsessionHasNewContentcomparisons (line 1036), which both depend on raw line counts.Steps
1. Modify
ParseDroidTranscriptFromBytessignatureFile:
cmd/entire/cli/agent/factoryaidroid/transcript.goChange:
gofunc ParseDroidTranscriptFromBytes(content []byte) ([]transcript.Line, error) { lines, _, err := parseDroidTranscriptFromReader(bytes.NewReader(content), 0) return lines, err }To:
gofunc ParseDroidTranscriptFromBytes(content []byte, startLine int) ([]transcript.Line, error) { lines, _, err := parseDroidTranscriptFromReader(bytes.NewReader(content), startLine) return lines, err }2. Fix
calculateTokenUsagefor Droid Assistant
★ Insight ─────────────────────────────────────This bug is a classic "abstraction boundary mismatch" —countTranscriptItemscounts raw JSONL lines (including non-message entries likesession_start), butParseDroidTranscriptFromBytesreturns only filtered message entries. When you use a raw line count as an index into a filtered array, you get an offset that's wrong by exactly the number of filtered-out entries.─────────────────────────────────────────────────Let me start by reading the relevant files to understand the current code before making changes.
Assistant
Now let me read the test file and find all call sites to confirm the plan.
Assistant
I'm using the executing-plans skill to implement this plan.
The plan is clear and well-structured — no concerns. Let me create the task list and execute.
Assistant
Now let me read the test file to understand existing test patterns before making changes.
Assistant
Good, I have a clear picture of the existing code and tests. Now let me read the rest of the test file to find the line 1103 call site.
Assistant
Now I have all the context. Let me execute the first batch (tasks 1-3) — these are the mechanical code changes.
Step 1: Modify the function signature
Assistant
★ Insight ─────────────────────────────────────The key issue:parseDroidTranscriptFromReaderappliesstartLineat the raw JSONL level (line 73:if totalLines >= startLine), then filters non-message entries. But the old code incalculateTokenUsagewas callingParseDroidTranscriptFromByteswithout an offset, getting back only messages, then slicing that filtered array with a raw line count — causing an index mismatch proportional to the number ofsession_start/session_evententries in the transcript.─────────────────────────────────────────────────Step 2: Fix calculateTokenUsage
Assistant
Step 3: Update all other callers to pass
, 0Assistant
Now update all test call sites. Since
ParseDroidTranscriptFromBytesappears 6 times in the test file, let me usereplace_all:Assistant
Let me verify there are no remaining callers without the new parameter:
Assistant
Wait — that matched because
[]byte(content), 0has the)closing. Let me check more carefully:Assistant
Good — no callers remain with just a single argument. All call sites have been updated.
Assistant
Batch 1 summary — Steps 1-3 complete:
ParseDroidTranscriptFromBytesnow acceptsstartLine intand passes it through toparseDroidTranscriptFromReadercalculateTokenUsagepassesstartOffsetdirectly to the parser instead of slicing the filtered array- All 10 other call sites updated to pass
0(no behavioral change)
Now for Step 4: regression tests. Let me first check the condensation test file to understand test patterns there.
Assistant
No existing tests for
calculateTokenUsage. Let me check if the function is exported or unexported, and what test files exist in the strategy package.Assistant
Now let me look at the CalculateTokenUsage test in the transcript test file to understand the test data patterns for token usage:
Assistant
Now let me also check the
mustMarshalhelper and themessageWithUsagetype for building test data:Assistant
Good. Now I have all the context to write the tests. Let me add the regression tests.
Test a)
ParseDroidTranscriptFromByteswith startLine and non-message entries:Assistant
Now test b) —
calculateTokenUsagewith Droid transcripts containing non-message lines and a startOffset. SincecalculateTokenUsageis unexported in thestrategypackage, I'll add the test there.Assistant
Now let me check what imports
calculateTokenUsageneeds — specifically theagentpackage:Assistant
Now add the test at the end of the file:
Assistant
★ Insight ─────────────────────────────────────The regression test atstartOffset=3is the critical case — before this fix, the old code would parse all 5 raw lines into 3 messages[m1, m2, m3], then try to slice at index 3, which equalslen(lines). ThestartOffset < len(lines)guard would fail and return all tokens instead of just m3's tokens. With the fix,startOffset=3is passed to the raw JSONL reader, correctly skipping lines 0-2 and only returning messages from line 3 onwards.─────────────────────────────────────────────────Now let me verify the test file compiles — I need to check if
fmtis used (I imported it but may not need it):Assistant
I don't actually use
fmt— let me remove it. And I should check ifstringsandunicode/utf8are still needed (they are, by existing tests).Assistant
Also need to verify that the
droidMessagehelper doesn't usefmteither — it doesn't, it only usesjson.Marshal. Good.Assistant
Step 5: Verification
Assistant
Three lint issues. Let me fix: (1)
unparam— thetypparameter always receives"message"but the helper also builds non-message lines in the tests via raw strings, so I'll just remove thetypparameter; (2)errcheck— checkjson.Marshalerrors.Assistant
The simplest fix: since
typis always"message", hardcode it and accepttfor error checking:Assistant
Now update all call sites of
droidMessageto passtand remove thetyparg:Assistant
Let me verify the test file looks correct now:
Assistant
I notice the spacing is off —
droidMessage(t,"m1"should bedroidMessage(t, "m1". Let me fix that:Assistant
Let me just run fmt to fix it automatically:
Assistant
Lint passes. Now run the full test suite:
Assistant
All tests pass, including the new ones.
Assistant
All 5 tasks complete. Here's what was implemented:
Changes made:
File Change agent/factoryaidroid/transcript.goAdded startLine intparameter toParseDroidTranscriptFromBytesstrategy/manual_commit_condensation.goBug fix: pass startOffsetto parser instead of slicing filtered arraystrategy/manual_commit_condensation.go:553Updated extractUserPromptscaller → pass