Merge origin/main into trail-resume · Entire

Home

Log in

Merge origin/main into trail-resume

223629e→main·

peyton-alt·3w ago·19 files·+4,197 added/-121 removed

Resolve .gitignore by keeping /skills/, remove stray t1.txt, and preserve restored sessions from resume fallback paths so trail resume can launch agents after restore.

Sessions

1cfc6d5a6270View transcript

?\ Add Trail Resume SubcommandCodex·GPT-5.5·4 steps

Changes

19

68 unmodified lines

69
70
71
72
72
73

68 unmodified lines

.superpowers/
.clawpatch/
entire-external-cp-test/
skills/
/skills/
/git-remote-entire

M.gitignore+1/-1

21 unmodified lines

22
23
24
25
26
27
28
25
26
27
28
29
30
31
30
32
33
34
35
36
37
36
38
39
40
41
5 unmodified lines

47
48
49
50
51
52
53
54
55
56

21 unmodified lines

### Command Layout

The CLI is organized around five noun groups plus a small set of top-level
verbs. The groups are the canonical home for each verb; legacy top-level
shortcuts remain functional but hidden, and emit a deprecation hint pointing
at the canonical group form.
The visible CLI is organized around five noun groups plus a small set of
top-level verbs. The groups are the canonical home for each verb; legacy
top-level shortcuts remain functional but hidden, and emit a deprecation hint
pointing at the canonical group form. Newer experimental command families are
discoverable through `entire labs` and may remain hidden from root help while
their canonical paths are still runnable.

- `session` (alias: `sessions`): `list`, `info`, `stop`, `attach`, `resume`, `current`.
- `session` (alias: `sessions`): `list`, `info`, `tokens`, `stop`, `attach`, `resume`, `current`.
  `resume` with a branch arg switches to it and resumes its session; with no arg
  it opens an interactive picker of stopped sessions (across all worktrees),
  resolving each to its branch and pointing at the owning worktree when the
  branch is checked out elsewhere. Resume keeps an existing local session log
  as-is by default (`--force` overwrites it from the checkpoint).
- `checkpoint` (aliases: `cp`, `checkpoints`): `list`, `explain`, `search`, plus
- `checkpoint` (aliases: `cp`, `checkpoints`): `list`, `explain`, `tokens`, `search`, plus
  the deprecated `rewind` (functional, prints a cobra deprecation message, will
  be removed in a future release)
- `agent`: bare opens the interactive agent selector, plus `list`, `add`, `remove`
5 unmodified lines

current one) and `--all-contexts` (log out of every saved login)
- `doctor`: bare runs the scan-and-fix flow, plus `trace`, `logs`, `bundle`

Experimental command families advertised through `entire labs`:

- `tokens`: `profile` (hidden from root help while token diagnostics mature)

Top-level lifecycle and standalone commands: `enable`, `disable`, `status`,
`login`, `logout`, `clean`, `version`, `dispatch`, `activity`, `help`,
`configure`.

MCLAUDE.md+12/-6

7 unmodified lines

8
9
10
11
11
12
13
14
4 unmodified lines

19
20
21
22
23
24
25
26
27
28
29
30
31
5 unmodified lines

37
38
39
40
41
42
43

7 unmodified lines

)

// newCheckpointGroupCmd builds the `entire checkpoint` parent command and
// registers list/explain/search as children, plus the deprecated rewind.
// registers list/explain/tokens/search as children, plus the deprecated rewind.
func newCheckpointGroupCmd() *cobra.Command {
    cmd := &cobra.Command{
        Use:     "checkpoint",
4 unmodified lines

Commands:
  list     List checkpoints on the current branch
  explain  Explain a checkpoint, commit, or session
  tokens   Show token usage and optimization recommendations
  search   Search checkpoints (semantic + keyword)

Examples:
  entire checkpoint list
  entire checkpoint explain <id|sha>
  entire checkpoint tokens <id>
  entire checkpoint search "fix login"`,
        PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {
            if _, err := paths.WorktreeRoot(cmd.Context()); err != nil {
5 unmodified lines

cmd.AddCommand(newCheckpointListCmd())
    cmd.AddCommand(newExplainCmd())
    cmd.AddCommand(newCheckpointTokensCmd())
    cmd.AddCommand(newRewindCmd())
    cmd.AddCommand(newCheckpointSearchCmd())

Mcmd/entire/cli/checkpoint_group.go+4/-1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682

package cli

import (
    "context"
    "encoding/json"
    "errors"
    "fmt"
    "io"
    "strconv"
    "strings"

"github.com/entireio/cli/cmd/entire/cli/agent"
    "github.com/entireio/cli/cmd/entire/cli/checkpoint"
    "github.com/entireio/cli/cmd/entire/cli/checkpoint/id"
    "github.com/spf13/cobra"
)

type checkpointTokensReport struct {
    CheckpointID    string                        `json:"checkpoint_id"`
    SessionCount    int                           `json:"session_count"`
    SessionID       string                        `json:"session_id,omitempty"`
    Agent           string                        `json:"agent,omitempty"`
    Agents          []string                      `json:"agents,omitempty"`
    Model           string                        `json:"model,omitempty"`
    Models          []string                      `json:"models,omitempty"`
    Branch          string                        `json:"branch,omitempty"`
    Source          string                        `json:"source"`
    Tokens          *sessionTokensUsage           `json:"tokens,omitempty"`
    Context         *sessionTokensContext         `json:"context,omitempty"`
    Contributors    []sessionTokensContributor    `json:"contributors,omitempty"`
    Recommendations []sessionTokensRecommendation `json:"recommendations,omitempty"`
    Comparison      *checkpointTokensComparison   `json:"comparison,omitempty"`
    Limitations     []string                      `json:"limitations,omitempty"`
}

type checkpointTokensComparison struct {
    BaselineCheckpointID string                       `json:"baseline_checkpoint_id"`
    TargetCheckpointID   string                       `json:"target_checkpoint_id"`
    Status               string                       `json:"status"`
    Total                *checkpointTokensMetricDelta `json:"total,omitempty"`
    Input                *checkpointTokensMetricDelta `json:"input,omitempty"`
    CacheRead            *checkpointTokensMetricDelta `json:"cache_read,omitempty"`
    CacheWrite           *checkpointTokensMetricDelta `json:"cache_write,omitempty"`
    Output               *checkpointTokensMetricDelta `json:"output,omitempty"`
    APICalls             *checkpointTokensMetricDelta `json:"api_calls,omitempty"`
    CacheReadCaveat      string                       `json:"cache_read_caveat,omitempty"`
    Qualification        string                       `json:"qualification"`
    Limitations          []string                     `json:"limitations,omitempty"`
}

type checkpointTokensMetricDelta struct {
    Baseline      int      `json:"baseline"`
    Current       int      `json:"current"`
    Change        int      `json:"change"`
    ChangePercent *float64 `json:"change_percent,omitempty"`
    Direction     string   `json:"direction"`
}

const (
    checkpointComparisonStatusUnavailable       = "unavailable"
    checkpointComparisonStatusObservedReduction = "observed_reduction"
    checkpointComparisonStatusObservedIncrease  = "observed_increase"
    checkpointComparisonStatusObservedNoChange  = "observed_no_change"

checkpointDeltaDirectionDown      = "down"
    checkpointDeltaDirectionUp        = "up"
    checkpointDeltaDirectionUnchanged = "unchanged"
)

func newCheckpointTokensCmd() *cobra.Command {
    var jsonFlag bool
    var compareFlag string
    var agentBriefFlag bool

cmd := &cobra.Command{
        Use:   "tokens <checkpoint-id>",
        Short: "Show token usage and optimization recommendations for a checkpoint",
        Long: `Show token usage and optimization recommendations for a checkpoint.

The report reads committed checkpoint metadata using the same checkpoint
resolution path as 'entire checkpoint explain'. Checkpoint IDs may be abbreviated
as long as the prefix is unambiguous; positional targets may also resolve from a
commit ref with an Entire-Checkpoint trailer, and missing metadata may be fetched
from the checkpoint remote.

Use --compare <checkpoint-id> to compare this checkpoint against a previous
checkpoint and qualify observed token reduction or increase.`,
        Args: cobra.ExactArgs(1),
        RunE: func(cmd *cobra.Command, args []string) error {
            if jsonFlag && agentBriefFlag {
                return errors.New("--json and --agent-brief are mutually exclusive")
            }
            return runCheckpointTokens(cmd.Context(), cmd, args[0], jsonFlag, compareFlag, agentBriefFlag)
        },
    }

cmd.Flags().BoolVar(&jsonFlag, "json", false, "Output as JSON")
    cmd.Flags().StringVar(&compareFlag, "compare", "", "Compare against a baseline checkpoint ID")
    cmd.Flags().BoolVar(&agentBriefFlag, "agent-brief", false, "Output compact next-step guidance for agents")
    return cmd
}

func runCheckpointTokens(ctx context.Context, cmd *cobra.Command, checkpointIDPrefix string, jsonOutput bool, comparePrefix string, agentBrief bool) error {
    report, lookup, err := loadCheckpointTokensReport(ctx, cmd, checkpointIDPrefix)
    if lookup != nil {
        defer lookup.Close()
    }
    if err != nil {
        return tokenCommandError(err)
    }

if comparePrefix != "" {
        baselineReport, baselineLookup, err := loadCheckpointTokensReport(ctx, cmd, comparePrefix)
        if baselineLookup != nil {
            defer baselineLookup.Close()
        }
        if err != nil {
            return tokenCommandError(err)
        }
        if baselineReport.CheckpointID == report.CheckpointID {
            cmd.SilenceUsage = true
            return fmt.Errorf("cannot compare checkpoint %s to itself", report.CheckpointID)
        }
        report.Comparison = buildCheckpointTokensComparison(report, baselineReport)
    }

if jsonOutput {
        return writeCheckpointTokensJSON(cmd.OutOrStdout(), report)
    }
    if agentBrief {
        writeCheckpointTokensAgentBrief(cmd.OutOrStdout(), report)
        return nil
    }
    writeCheckpointTokensText(cmd.OutOrStdout(), report)
    return nil
}

func loadCheckpointTokensReport(ctx context.Context, cmd *cobra.Command, checkpointIDPrefix string) (checkpointTokensReport, *explainCheckpointLookup, error) {
    cpID, lookup, err := resolveExplainCheckpointID(ctx, cmd.ErrOrStderr(), explainExportOptions{target: checkpointIDPrefix})
    if err != nil {
        return checkpointTokensReport{}, lookup, err
    }

summary, err := lookup.store.ReadCommitted(ctx, cpID)
    if err != nil {
        return checkpointTokensReport{}, lookup, fmt.Errorf("failed to read checkpoint: %w", err)
    }
    if summary == nil || len(summary.Sessions) == 0 {
        cmd.SilenceUsage = true
        fmt.Fprintln(cmd.ErrOrStderr(), "Checkpoint not found.")
        return checkpointTokensReport{}, lookup, NewSilentError(fmt.Errorf("%w: %s", checkpoint.ErrCheckpointNotFound, checkpointIDPrefix))
    }

metas, metadataWarnings, err := readCheckpointTokenSessionMetadata(ctx, lookup.store, cpID, len(summary.Sessions))
    if err != nil {
        return checkpointTokensReport{}, lookup, err
    }

return buildCheckpointTokensReport(cpID, summary, metas, metadataWarnings), lookup, nil
}

func readCheckpointTokenSessionMetadata(ctx context.Context, store checkpointSessionMetadataReader, cpID id.CheckpointID, sessionCount int) ([]*checkpoint.CommittedMetadata, int, error) {
    if ctxErr := ctx.Err(); ctxErr != nil {
        return nil, 0, ctxErr //nolint:wrapcheck // Propagating context cancellation.
    }
    metas := make([]*checkpoint.CommittedMetadata, 0, sessionCount)
    var warnings int
    for i := range sessionCount {
        if ctxErr := ctx.Err(); ctxErr != nil {
            return nil, warnings, ctxErr //nolint:wrapcheck // Propagating context cancellation.
        }
        meta, err := store.ReadSessionMetadata(ctx, cpID, i)
        if err != nil {
            if ctxErr := ctx.Err(); ctxErr != nil {
                return nil, warnings, ctxErr //nolint:wrapcheck // Propagating context cancellation.
            }
            warnings++
            continue
        }
        metas = append(metas, meta)
    }
    return metas, warnings, nil
}

func buildCheckpointTokensReport(cpID id.CheckpointID, summary *checkpoint.CheckpointSummary, metas []*checkpoint.CommittedMetadata, metadataWarnings int) checkpointTokensReport {
    report := checkpointTokensReport{
        CheckpointID: cpID.String(),
        Source:       "committed_checkpoint",
    }
    if summary != nil {
        report.Branch = summary.Branch
        report.SessionCount = len(summary.Sessions)
    }
    if report.SessionCount == 0 {
        report.SessionCount = len(metas)
    }
    report.Agents = checkpointAgentLabels(metas)
    report.Models = checkpointModelLabels(metas)

if report.SessionCount == 1 && len(metas) == 1 && metas[0] != nil {
        meta := metas[0]
        report.SessionID = meta.SessionID
        if len(report.Agents) > 0 {
            report.Agent = report.Agents[0]
        }
        if len(report.Models) > 0 {
            report.Model = report.Models[0]
        }
        if report.Branch == "" {
            report.Branch = meta.Branch
        }
    } else if len(metas) > 1 && report.Branch == "" {
        report.Branch = firstCheckpointBranch(metas)
    }

usage := checkpointTokenUsage(summary, metas, metadataWarnings > 0)
    if tokens := buildSessionTokensUsage(usage); tokens != nil {
        report.Tokens = tokens
        if tokens.SubagentTotal > 0 {
            report.Contributors = append(report.Contributors, sessionTokensContributor{
                Kind:       "subagents",
                Label:      "Subagents",
                Tokens:     tokens.SubagentTotal,
                Confidence: "reported",
                Signals:    []string{"subagent_tokens"},
            })
        }
    } else {
        report.Limitations = append(report.Limitations, "No token usage recorded for this checkpoint.")
        report.Recommendations = append(report.Recommendations, sessionTokensRecommendation{
            ID:       "no-token-data",
            Severity: "low",
            Message:  "Token usage is unavailable for this checkpoint; the agent may not expose token data yet, or this checkpoint predates token tracking.",
            Signals:  []string{"missing_token_usage"},
        })
    }
    if metadataWarnings > 0 {
        report.Limitations = append(report.Limitations, fmt.Sprintf(
            "%d checkpoint session metadata file%s could not be read; used root token summary or readable session metadata where available.",
            metadataWarnings,
            tokenPluralSuffix(metadataWarnings),
        ))
    }

var turnCount int
    var skillEvents []agent.SkillEvent
    if report.SessionCount == 1 && len(metas) == 1 && metas[0] != nil {
        meta := metas[0]
        if metrics := meta.SessionMetrics; metrics != nil {
            turnCount = metrics.TurnCount
            if contextInfo := buildSessionTokensContext(metrics.ContextTokens, metrics.ContextWindowSize); contextInfo != nil {
                report.Context = contextInfo
                report.Contributors = append(report.Contributors, sessionTokensContributor{
                    Kind:       "context_pressure",
                    Label:      "Context pressure",
                    Percent:    contextInfo.Percent,
                    Confidence: "reported",
                    Signals:    []string{"context_tokens"},
                })
            }
        }
        skillEvents = meta.SkillEvents
    } else {
        for _, meta := range metas {
            if meta == nil {
                continue
            }
            if metrics := meta.SessionMetrics; metrics != nil {
                turnCount += metrics.TurnCount
            }
            skillEvents = append(skillEvents, meta.SkillEvents...)
        }
    }
    if labels := skillEventLabels(skillEvents); len(labels) > 0 {
        report.Contributors = append(report.Contributors, sessionTokensContributor{
            Kind:       "skills",
            Label:      "Skills/slash commands: " + strings.Join(labels, ", "),
            Confidence: "reported",
            Signals:    []string{"skill_events"},
        })
    }

var checkpointCount int
    if summary != nil {
        checkpointCount = summary.CheckpointsCount
    }
    report.Recommendations = append(report.Recommendations, recommendationRules(tokenRecommendationSignals{
        Tokens:          report.Tokens,
        Context:         report.Context,
        TurnCount:       turnCount,
        CheckpointCount: checkpointCount,
    })...)
    return report
}

func checkpointAgentLabels(metas []*checkpoint.CommittedMetadata) []string {
    labels := make([]string, 0, len(metas))
    seen := make(map[string]struct{}, len(metas))
    for _, meta := range metas {
        label := unknownPlaceholder
        if meta != nil && meta.Agent != "" {
            label = string(meta.Agent)
        }
        if _, ok := seen[label]; ok {
            continue
        }
        seen[label] = struct{}{}
        labels = append(labels, label)
    }
    return labels
}

func checkpointModelLabels(metas []*checkpoint.CommittedMetadata) []string {
    labels := make([]string, 0, len(metas))
    seen := make(map[string]struct{}, len(metas))
    for _, meta := range metas {
        if meta == nil || meta.Model == "" {
            continue
        }
        if _, ok := seen[meta.Model]; ok {
            continue
        }
        seen[meta.Model] = struct{}{}
        labels = append(labels, meta.Model)
    }
    return labels
}

func firstCheckpointBranch(metas []*checkpoint.CommittedMetadata) string {
    for _, meta := range metas {
        if meta != nil && meta.Branch != "" {
            return meta.Branch
        }
    }
    return ""
}

func aggregateCheckpointTokenUsage(metas []*checkpoint.CommittedMetadata) *agent.TokenUsage {
    var total *agent.TokenUsage
    for _, meta := range metas {
        if meta == nil {
            continue
        }
        total = addCheckpointTokenUsage(total, meta.TokenUsage)
    }
    return total
}

func checkpointTokenUsage(summary *checkpoint.CheckpointSummary, metas []*checkpoint.CommittedMetadata, metadataReadWarning bool) *agent.TokenUsage {
    sessionUsage := aggregateCheckpointTokenUsage(metas)
    if !metadataReadWarning && sessionUsage != nil {
        return sessionUsage
    }
    if summary != nil && summary.TokenUsage != nil {
        return summary.TokenUsage
    }
    return sessionUsage
}

func addCheckpointTokenUsage(a, b *agent.TokenUsage) *agent.TokenUsage {
    if a == nil && b == nil {
        return nil
    }
    result := &agent.TokenUsage{}
    if a != nil {
        result.InputTokens = a.InputTokens
        result.CacheCreationTokens = a.CacheCreationTokens
        result.CacheReadTokens = a.CacheReadTokens
        result.OutputTokens = a.OutputTokens
        result.APICallCount = a.APICallCount
    }
    if b != nil {
        result.InputTokens = saturatingIntAdd(result.InputTokens, b.InputTokens)
        result.CacheCreationTokens = saturatingIntAdd(result.CacheCreationTokens, b.CacheCreationTokens)
        result.CacheReadTokens = saturatingIntAdd(result.CacheReadTokens, b.CacheReadTokens)
        result.OutputTokens = saturatingIntAdd(result.OutputTokens, b.OutputTokens)
        result.APICallCount = saturatingIntAdd(result.APICallCount, b.APICallCount)
    }
    result.SubagentTokens = addCheckpointTokenUsage(tokenUsageSubagents(a), tokenUsageSubagents(b))
    return result
}

func saturatingIntAdd(a, b int) int {
    maxValue := int(^uint(0) >> 1)
    minValue := -maxValue - 1
    if b > 0 && a > maxValue-b {
        return maxValue
    }
    if b < 0 && a < minValue-b {
        return minValue
    }
    return a + b
}

func tokenUsageSubagents(usage *agent.TokenUsage) *agent.TokenUsage {
    if usage == nil {
        return nil
    }
    return usage.SubagentTokens
}

func tokenPluralSuffix(count int) string {
    if count == 1 {
        return ""
    }
    return "s"
}

func buildCheckpointTokensComparison(target, baseline checkpointTokensReport) *checkpointTokensComparison {
    comparison := &checkpointTokensComparison{
        BaselineCheckpointID: baseline.CheckpointID,
        TargetCheckpointID:   target.CheckpointID,
    }
    if target.Tokens == nil || baseline.Tokens == nil {
        comparison.Status = checkpointComparisonStatusUnavailable
        comparison.Qualification = "Comparison unavailable because token usage is missing for one checkpoint."
        comparison.Limitations = append(comparison.Limitations, comparison.Qualification)
        return comparison
    }

comparison.Total = buildCheckpointMetricDelta(baseline.Tokens.Total, target.Tokens.Total)
    comparison.Input = buildCheckpointMetricDelta(baseline.Tokens.Input, target.Tokens.Input)
    comparison.CacheRead = buildCheckpointMetricDelta(baseline.Tokens.CacheRead, target.Tokens.CacheRead)
    comparison.CacheWrite = buildCheckpointMetricDelta(baseline.Tokens.CacheWrite, target.Tokens.CacheWrite)
    comparison.Output = buildCheckpointMetricDelta(baseline.Tokens.Output, target.Tokens.Output)
    comparison.APICalls = buildCheckpointMetricDelta(baseline.Tokens.APICalls, target.Tokens.APICalls)
    comparison.CacheReadCaveat = checkpointComparisonCacheReadCaveat(comparison.CacheRead)
    comparison.Status = checkpointComparisonStatus(comparison.Total)
    comparison.Qualification = checkpointComparisonQualification(comparison.Status)
    if classes := checkpointCostProxyPressureIncreased(comparison); len(classes) > 0 {
        comparison.Qualification += fmt.Sprintf(" Cost-proxy pressure increased for %s even though total tokens decreased.", formatTokenClassList(classes))
    }
    return comparison
}

func checkpointCostProxyPressureIncreased(comparison *checkpointTokensComparison) []string {
    if comparison == nil || comparison.Total == nil || comparison.Total.Change >= 0 {
        return nil
    }
    var classes []string
    if comparison.CacheWrite != nil && comparison.CacheWrite.Change > 0 {
        classes = append(classes, "cache write")
    }
    if comparison.Output != nil && comparison.Output.Change > 0 {
        classes = append(classes, "output")
    }
    return classes
}

func formatTokenClassList(classes []string) string {
    switch len(classes) {
    case 0:
        return ""
    case 1:
        return classes[0]
    case 2:
        return classes[0] + " and " + classes[1]
    default:
        return strings.Join(classes[:len(classes)-1], ", ") + ", and " + classes[len(classes)-1]
    }
}

func buildCheckpointMetricDelta(baseline, current int) *checkpointTokensMetricDelta {
    change := saturatingIntSub(current, baseline)
    delta := &checkpointTokensMetricDelta{
        Baseline:  baseline,
        Current:   current,
        Change:    change,
        Direction: checkpointDeltaDirection(change),
    }
    if baseline != 0 {
        percent := (float64(delta.Change) / float64(baseline)) * 100
        delta.ChangePercent = &percent
    }
    return delta
}

func saturatingIntSub(a, b int) int {
    if b < 0 {
        if b == minInt() {
            if a >= 0 {
                return maxInt()
            }
            return a - b
        }
        if a > maxInt()-(-b) {
            return maxInt()
        }
    }
    if b > 0 && a < minInt()+b {
        return minInt()
    }
    return a - b
}

func maxInt() int {
    return int(^uint(0) >> 1)
}

func minInt() int {
    return -maxInt() - 1
}

func checkpointDeltaDirection(change int) string {
    switch {
    case change < 0:
        return checkpointDeltaDirectionDown
    case change > 0:
        return checkpointDeltaDirectionUp
    default:
        return checkpointDeltaDirectionUnchanged
    }
}

func checkpointComparisonStatus(total *checkpointTokensMetricDelta) string {
    if total == nil {
        return checkpointComparisonStatusUnavailable
    }
    switch total.Direction {
    case checkpointDeltaDirectionDown:
        return checkpointComparisonStatusObservedReduction
    case checkpointDeltaDirectionUp:
        return checkpointComparisonStatusObservedIncrease
    default:
        return checkpointComparisonStatusObservedNoChange
    }
}

func checkpointComparisonQualification(status string) string {
    switch status {
    case checkpointComparisonStatusObservedReduction:
        return "Observed total token use decreased for this checkpoint comparison. This does not prove quality was preserved; verify the task outcome or tests before treating it as a successful optimization."
    case checkpointComparisonStatusObservedIncrease:
        return "Observed total token use increased for this checkpoint comparison. Check whether the extra context was necessary before treating it as waste."
    case checkpointComparisonStatusObservedNoChange:
        return "Observed total token use was unchanged for this checkpoint comparison. Quality still depends on the task outcome, not token totals alone."
    default:
        return "Comparison unavailable because token usage is missing for one checkpoint."
    }
}

func checkpointComparisonCacheReadCaveat(delta *checkpointTokensMetricDelta) string {
    if delta == nil || (delta.Baseline == 0 && delta.Current == 0) {
        return ""
    }
    return "Total tokens include cache/context replay; use the cache/context replay delta below before treating total direction as work saved or added."
}

func writeCheckpointTokensJSON(w io.Writer, report checkpointTokensReport) error {
    enc := json.NewEncoder(w)
    enc.SetIndent("", "  ")
    if err := enc.Encode(report); err != nil {
        return fmt.Errorf("failed to encode checkpoint token report: %w", err)
    }
    return nil
}

func writeCheckpointTokensText(w io.Writer, report checkpointTokensReport) {
    fmt.Fprintln(w, "Checkpoint tokens")
    fmt.Fprintln(w)
    fmt.Fprintf(w, "Checkpoint: %s\n", report.CheckpointID)
    switch {
    case report.SessionCount > 1:
        fmt.Fprintf(w, "Sessions:   %d\n", report.SessionCount)
        if len(report.Agents) > 0 {
            fmt.Fprintf(w, "Agents:     %s\n", strings.Join(report.Agents, ", "))
        }
        if len(report.Models) > 0 {
            fmt.Fprintf(w, "Models:     %s\n", strings.Join(report.Models, ", "))
        }
    case report.SessionID != "":
        fmt.Fprintf(w, "Session:    %s\n", report.SessionID)
        if report.Agent != "" {
            fmt.Fprintf(w, "Agent:      %s\n", report.Agent)
        }
        if report.Model != "" {
            fmt.Fprintf(w, "Model:      %s\n", report.Model)
        }
    case report.Agent != "":
        fmt.Fprintf(w, "Agent:      %s\n", report.Agent)
    }
    if report.Branch != "" {
        fmt.Fprintf(w, "Branch:     %s\n", report.Branch)
    }

writeTokenUsageSection(w, report.Tokens)
    writeCheckpointTokenComparison(w, report.Comparison)
    if len(report.Recommendations) > 0 {
        writeTokenRecommendations(w, report.Recommendations)
    }
    writeTokenContributors(w, report.Contributors, report.Context)
    writeTokenLimitations(w, report.Limitations)
}

func writeCheckpointTokensAgentBrief(w io.Writer, report checkpointTokensReport) {
    fmt.Fprintln(w, "Checkpoint token brief")
    fmt.Fprintf(w, "Checkpoint: %s\n", report.CheckpointID)
    fmt.Fprintln(w)
    fmt.Fprintln(w, agentBriefUsageLine(report.Tokens))
    fmt.Fprintln(w)
    fmt.Fprintln(w, "Next best action:")
    fmt.Fprintln(w, checkpointAgentBriefNextAction(report))

signals := agentBriefSignals(checkpointAgentBriefSessionReport(report))
    if len(signals) > 0 {
        fmt.Fprintln(w)
        fmt.Fprintln(w, "Signals:")
        for _, signal := range signals {
            fmt.Fprintf(w, "- %s\n", signal)
        }
    }
}

func checkpointAgentBriefNextAction(report checkpointTokensReport) string {
    sessionReport := checkpointAgentBriefSessionReport(report)
    if hasTokenRecommendation(sessionReport, "no-token-data") {
        return "Do not spend extra commands on token optimization for this checkpoint. Continue with the task and capture a newer checkpoint before rechecking tokens."
    }
    if action, ok := agentBriefOptimizationAction(sessionReport); ok {
        return action
    }
    return "Continue normally; no high-signal token optimization is available from this checkpoint."
}

func checkpointAgentBriefSessionReport(report checkpointTokensReport) sessionTokensReport {
    return sessionTokensReport{
        Tokens:          report.Tokens,
        Context:         report.Context,
        Recommendations: report.Recommendations,
        Limitations:     report.Limitations,
    }
}

func writeCheckpointTokenComparison(w io.Writer, comparison *checkpointTokensComparison) {
    if comparison == nil {
        return
    }

fmt.Fprintln(w)
    fmt.Fprintln(w, "Comparison")
    fmt.Fprintf(w, "Baseline: %s\n", comparison.BaselineCheckpointID)
    if comparison.CacheReadCaveat != "" {
        fmt.Fprintf(w, "Caveat: %s\n", comparison.CacheReadCaveat)
    }
    if comparison.Status != checkpointComparisonStatusUnavailable {
        fmt.Fprintf(w, "Total tokens: %s\n", formatCheckpointMetricDelta(comparison.Total, formatTokenCount))
        fmt.Fprintf(w, "Input: %s\n", formatCheckpointMetricDelta(comparison.Input, formatTokenCount))
        fmt.Fprintf(w, "Cache/context replay: %s\n", formatCheckpointMetricDelta(comparison.CacheRead, formatTokenCount))
        fmt.Fprintf(w, "Cache write: %s\n", formatCheckpointMetricDelta(comparison.CacheWrite, formatTokenCount))
        fmt.Fprintf(w, "Output: %s\n", formatCheckpointMetricDelta(comparison.Output, formatTokenCount))
        fmt.Fprintf(w, "API calls: %s\n", formatCheckpointMetricDelta(comparison.APICalls, formatPlainCount))
    }
    fmt.Fprintln(w)
    fmt.Fprintln(w, "Qualification")
    fmt.Fprintln(w, comparison.Qualification)
}

func formatCheckpointMetricDelta(delta *checkpointTokensMetricDelta, formatValue func(int) string) string {
    if delta == nil {
        return "unavailable"
    }
    from := formatValue(delta.Baseline)
    to := formatValue(delta.Current)
    if delta.Direction == checkpointDeltaDirectionUnchanged {
        return fmt.Sprintf("unchanged (%s -> %s)", from, to)
    }
    if delta.ChangePercent == nil {
        return fmt.Sprintf("%s (%s -> %s)", delta.Direction, from, to)
    }
    return fmt.Sprintf("%s %s (%s -> %s)", delta.Direction, formatPercent(absFloat(*delta.ChangePercent)), from, to)
}

func formatPlainCount(value int) string {
    return strconv.Itoa(value)
}

func absFloat(value float64) float64 {
    if value < 0 {
        return -value
    }
    return value
}

Acmd/entire/cli/checkpoint_tokens.go+682

8 unmodified lines

9
10
11
12
13
14
12
13
14
15
16
17
18
19
20
21
19
20
21
22
23
24
25
26
24
25
26
27
28
29
30
31
29
30
31
32
33
34
35
36
34
35
36
37
38
39
40
41
39
40
41
42
43
44
45
46
44
45
46
47
48
49
50
51
49
50
51
52
53
54
55
56
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
37 unmodified lines

107
108
109
110
111
112
113
114

8 unmodified lines

)

type experimentalCommandInfo struct {
    Name       string
    Invocation string
    Summary    string
    CommandPath []string
    Invocation  string
    Summary     string
}

var experimentalCommands = []experimentalCommandInfo{
    {
        Name:       "review",
        Invocation: "entire review",
        Summary:    "Run configured review skills against the current branch",
        CommandPath: []string{"review"},
        Invocation:  "entire review",
        Summary:     "Run configured review skills against the current branch",
    },
    {
        Name:       "investigate",
        Invocation: "entire investigate",
        Summary:    "Run a multi-agent investigation against a topic, issue, or seed doc",
        CommandPath: []string{"investigate"},
        Invocation:  "entire investigate",
        Summary:     "Run a multi-agent investigation against a topic, issue, or seed doc",
    },
    {
        Name:       "org",
        Invocation: "entire org",
        Summary:    "Manage Entire organizations (create, list)",
        CommandPath: []string{"tokens"},
        Invocation:  "entire tokens",
        Summary:     "Analyze experimental token usage diagnostics",
    },
    {
        Name:       "project",
        Invocation: "entire project",
        Summary:    "Manage Entire projects (create, list)",
        CommandPath: []string{"tokens", "profile"},
        Invocation:  "entire tokens profile",
        Summary:     "Aggregate token usage across committed checkpoints",
    },
    {
        Name:       "repo",
        Invocation: "entire repo",
        Summary:    "Manage Entire repositories (create, list, get, delete)",
        CommandPath: []string{"org"},
        Invocation:  "entire org",
        Summary:     "Manage Entire organizations (create, list)",
    },
    {
        Name:       "grant",
        Invocation: "entire grant",
        Summary:    "Manage access grants and org membership (org, project, repo)",
        CommandPath: []string{"project"},
        Invocation:  "entire project",
        Summary:     "Manage Entire projects (create, list)",
    },
    {
        Name:       "blame",
        Invocation: "entire blame",
        Summary:    "Show which lines came from Entire checkpoints",
        CommandPath: []string{"repo"},
        Invocation:  "entire repo",
        Summary:     "Manage Entire repositories (create, list, get, delete)",
    },
    {
        Name:       "why",
        Invocation: "entire why",
        Summary:    "Show why a line exists (commit, checkpoint, prompt, session)",
        CommandPath: []string{"grant"},
        Invocation:  "entire grant",
        Summary:     "Manage access grants and org membership (org, project, repo)",
    },
    {
        CommandPath: []string{"blame"},
        Invocation:  "entire blame",
        Summary:     "Show which lines came from Entire checkpoints",
    },
    {
        CommandPath: []string{"why"},
        Invocation:  "entire why",
        Summary:     "Show why a line exists (commit, checkpoint, prompt, session)",
    },
}

37 unmodified lines

Try:
  entire review --help
  entire investigate --help
  entire tokens --help
  entire tokens profile --help
  entire org --help
  entire project --help
  entire repo --help

Mcmd/entire/cli/labs.go+39/-27

25 unmodified lines

26
27
28
29
30
31
32
33
34
61 unmodified lines

96
97
98
96
97
99
100
101
102
103
104
105
106
107
108
42 unmodified lines

151
152
153
146
147
154
155
156
157
150
151
158
159
160
161
162
18 unmodified lines

181
182
183
176
177
184
185
186
187
188
11 unmodified lines

200
201
202
195
203
204
197
205
206
207
200
208
209
210
211

25 unmodified lines

"Available experimental commands",
        "entire review",
        "entire review --help",
        "entire tokens",
        "entire tokens profile",
        "entire tokens profile --help",
    } {
        if !strings.Contains(got, want) {
            t.Fatalf("entire labs output missing %q:\n%s", want, got)
61 unmodified lines

if !strings.Contains(got, "labs") || !strings.Contains(got, "Explore experimental Entire workflows") {
        t.Fatalf("root help should include labs command, got:\n%s", got)
    }
    if strings.Contains(got, "review") {
        t.Fatalf("root help should not include review while it is listed in labs, got:\n%s", got)
    for _, hiddenExperimentalCommand := range []string{
        "review",
        "tokens                 Analyze token usage across sessions and checkpoints",
    } {
        if strings.Contains(got, hiddenExperimentalCommand) {
            t.Fatalf("root help should not include %q while it is listed in labs, got:\n%s", hiddenExperimentalCommand, got)
        }
    }
}

42 unmodified lines

t.Parallel()

short := []experimentalCommandInfo{
        {Name: "a", Invocation: "entire a", Summary: "first"},
        {Name: "b", Invocation: "entire b", Summary: "second"},
        {Invocation: "entire a", Summary: "first"},
        {Invocation: "entire b", Summary: "second"},
    }
    long := []experimentalCommandInfo{
        {Name: "a", Invocation: "entire a", Summary: "first"},
        {Name: "verylongcommand", Invocation: "entire verylongcommand", Summary: "second"},
        {Invocation: "entire a", Summary: "first"},
        {Invocation: "entire verylongcommand", Summary: "second"},
    }

shortCol := summaryColumns(t, short)[0]
18 unmodified lines

// padding, len("entire ▶▶") == 13 >= 12 would skip padding and misalign the
    // row; rune-based padding correctly adds 3 spaces.
    commands := []experimentalCommandInfo{
        {Name: "long", Invocation: "entire aaaaa", Summary: "first"},
        {Name: "multibyte", Invocation: "entire ▶▶", Summary: "second"},
        {Invocation: "entire aaaaa", Summary: "first"},
        {Invocation: "entire ▶▶", Summary: "second"},
    }

if got := len("entire ▶▶"); got < 12 {
11 unmodified lines

root := NewRootCmd()
    for _, info := range experimentalCommands {
        cmd, _, err := root.Find([]string{info.Name})
        cmd, _, err := root.Find(info.CommandPath)
        if err != nil {
            t.Fatalf("labs command %q should exist at canonical path: %v", info.Name, err)
            t.Fatalf("labs command %q should exist at canonical path: %v", info.Invocation, err)
        }
        if cmd == nil {
            t.Fatalf("labs command %q resolved to nil command", info.Name)
            t.Fatalf("labs command %q resolved to nil command", info.Invocation)
        }
    }
}

Mcmd/entire/cli/labs_test.go+19/-11

225 unmodified lines

226
227
228
229
229
230
231
232
75 unmodified lines

308
309
310
311
311
312
313
314
15 unmodified lines

330
331
332
333
333
334
335
336
405 unmodified lines

742
743
744
745
745
746
747
748
749
750
751
751
752
753
754
3 unmodified lines

758
759
760
761
761
762
763
764
21 unmodified lines

786
787
788
789
789
790
791
792
8 unmodified lines

801
802
803
804
804
805
806
807
15 unmodified lines

823
824
825
826
826
827
828
829
15 unmodified lines

845
846
847
848
848
849
850
851
18 unmodified lines

870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
873
874
875
42 unmodified lines

918
919
920
934
921
922
923
924
925
926
927
928
34 unmodified lines

963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
977
983
984
985
986
1 unmodified line

988
989
990
985
986
987
991
992
993
994
995
992
996
997
998
999
1000
997
1001
1002
1003
1004
3 unmodified lines

1008
1009
1010
1007
1008
1009
1011
1012
1013
1014
1015
1016
1017
1016
1018
1019
1020
1021
2 unmodified lines

1024
1025
1026
1025
1026
1027
1027
1028
1029
1030
1031
1032
1033
1033
1034
1035
1036
11 unmodified lines

1048
1049
1050
1051
1051
1052
1053
1054
3 unmodified lines

1058
1059
1060
1061
1062
1061
1064
1062
1063
1064
1065

225 unmodified lines

slog.String("checkpoint_id", checkpointID.String()),
            slog.String("error", err.Error()),
        )
        return nil, checkRemoteMetadata(ctx, w, errW, checkpointID, stores.Refs())
        return checkRemoteMetadata(ctx, w, errW, checkpointID, stores.Refs())
    }

return restoreResumeSessions(ctx, w, errW, metadata, force)
75 unmodified lines

)
            fmt.Fprintf(w, "Found %d checkpoints for commit %s but metadata is not available\n",
                len(result.checkpointIDs), result.commitHash[:7])
            return nil, checkRemoteMetadata(ctx, w, errW, result.checkpointIDs[0], stores.Refs())
            return checkRemoteMetadata(ctx, w, errW, result.checkpointIDs[0], stores.Refs())
        }
        skipped := len(result.checkpointIDs) - 1
        fmt.Fprintf(w, "Found %d checkpoints for commit %s, resuming from the latest (%d older checkpoints skipped)\n",
15 unmodified lines

slog.String("checkpoint_id", checkpointID.String()),
                slog.String("error", storeErr.Error()),
            )
            return nil, checkRemoteMetadata(ctx, w, errW, checkpointID, stores.Refs())
            return checkRemoteMetadata(ctx, w, errW, checkpointID, stores.Refs())
        }
    }

405 unmodified lines

w, errW io.Writer,
    checkpointID id.CheckpointID,
    refs checkpoint.CommittedRefs,
) error {
) ([]strategy.RestoredSession, error) {
    logCtx := logging.WithComponent(ctx, "resume.checkRemoteMetadata")

if !refs.ReadBootstrappableFromOrigin() {
        fmt.Fprintf(errW, "Checkpoint '%s' found in commit but metadata is not available in %s.\n", checkpointID, refs.Read)
        fmt.Fprintf(errW, "This ref is local-only. Try: entire explain %s\n", checkpointID)
        return nil
        return nil, nil
    }

// Open a fresh repo to avoid stale packfile index issues
3 unmodified lines

slog.String("error", repoErr.Error()),
        )
        fmt.Fprintf(errW, "Checkpoint '%s' found in commit but session metadata not available\n", checkpointID)
        return nil
        return nil, nil
    }
    defer repo.Close()

21 unmodified lines

slog.String("error", err.Error()),
                        )
                    } else {
                        return resumeSession(ctx, w, errW, metadata, false)
                        return restoreResumeSessions(ctx, w, errW, metadata, false)
                    }
                }
            } else {
8 unmodified lines

promoteRemoteTrackingPrimary(ctx, repo, refs)
    metadata, metadataErr := readCheckpointInfoFromRef(ctx, repo, refs, checkpointID)
    if metadataErr == nil {
        return resumeSession(ctx, w, errW, metadata, false)
        return restoreResumeSessions(ctx, w, errW, metadata, false)
    }
    logging.Debug(logCtx, "remote-tracking metadata read failed",
        slog.String("checkpoint_id", checkpointID.String()),
15 unmodified lines

slog.String("error", err.Error()),
                )
            } else {
                return resumeSession(ctx, w, errW, metadata, false)
                return restoreResumeSessions(ctx, w, errW, metadata, false)
            }
        }
    } else {
15 unmodified lines

fmt.Fprintf(errW, "This can happen if the metadata branch was not pushed. Try:\n")
        fmt.Fprintf(errW, "  git fetch origin entire/checkpoints/v1:entire/checkpoints/v1\n")
    }
    return nil
    return nil, nil
}

// promoteRemoteTrackingPrimary advances the local primary ref to match origin's
18 unmodified lines

}
}

// resumeSession restores and displays the resume command for a specific session.
// For multi-session checkpoints, restores ALL sessions and shows commands for each.
// If force is false, prompts for confirmation when local logs have newer timestamps.
// The caller must provide the already-resolved checkpoint metadata to avoid redundant lookups
// and to support both local and remote metadata trees.
func resumeSession(ctx context.Context, w, errW io.Writer, metadata *strategy.CheckpointInfo, force bool) error {
    sessions, err := restoreResumeSessions(ctx, w, errW, metadata, force)
    if err != nil || len(sessions) == 0 {
        return err
    }
    return displayRestoredSessions(w, sessions)
}

func restoreResumeSessions(ctx context.Context, w, errW io.Writer, metadata *strategy.CheckpointInfo, force bool) ([]strategy.RestoredSession, error) {
    checkpointID := metadata.CheckpointID
    sessionID := metadata.SessionID
42 unmodified lines

sessions, restoreErr := strat.RestoreLogsOnly(ctx, w, errW, point, force)
    if restoreErr != nil || len(sessions) == 0 {
        // Fall back to single-session restore (e.g., old checkpoints without agent metadata)
        return nil, resumeSingleSession(ctx, w, errW, ag, sessionID, checkpointID, repoRoot, force)
        session, ok, err := restoreSingleSession(ctx, w, ag, sessionID, checkpointID, repoRoot, force)
        if err != nil || !ok {
            return nil, err
        }
        return []strategy.RestoredSession{session}, nil
    }

logging.Debug(logCtx, "resume session completed",
34 unmodified lines

// kept and only the resume command is printed; --force overwrites it from the checkpoint.
// A missing local log is always restored from the checkpoint.
func resumeSingleSession(ctx context.Context, w, _ io.Writer, ag agent.Agent, sessionID string, checkpointID id.CheckpointID, repoRoot string, force bool) error {
    session, ok, err := restoreSingleSession(ctx, w, ag, sessionID, checkpointID, repoRoot, force)
    if err != nil || !ok {
        return err
    }
    fmt.Fprintf(w, "\nTo continue this session:\n")
    fmt.Fprintf(w, "  %s\n", ag.FormatResumeCommand(session.SessionID))
    return nil
}

func restoreSingleSession(ctx context.Context, w io.Writer, ag agent.Agent, sessionID string, checkpointID id.CheckpointID, repoRoot string, force bool) (strategy.RestoredSession, bool, error) {
    restored := strategy.RestoredSession{
        SessionID: sessionID,
        Agent:     ag.Type(),
    }

sessionLogPath, err := resolveTranscriptPath(ctx, sessionID, ag)
    if err != nil {
        return fmt.Errorf("failed to resolve transcript path: %w", err)
        return strategy.RestoredSession{}, false, fmt.Errorf("failed to resolve transcript path: %w", err)
    }

if checkpointID.IsEmpty() {
1 unmodified line

slog.String("checkpoint_id", checkpointID.String()),
        )
        fmt.Fprintf(w, "Session '%s' found in commit trailer but session log not available\n", sessionID)
        fmt.Fprintf(w, "\nTo continue this session:\n")
        fmt.Fprintf(w, "  %s\n", ag.FormatResumeCommand(sessionID))
        return nil
        return restored, true, nil
    }

repo, repoErr := openRepository(ctx)
    if repoErr != nil {
        return fmt.Errorf("failed to open repository: %w", repoErr)
        return strategy.RestoredSession{}, false, fmt.Errorf("failed to open repository: %w", repoErr)
    }
    defer repo.Close()
    stores, err := checkpoint.Open(ctx, repo, checkpoint.OpenOptions{BlobFetcher: FetchBlobsByHash})
    if err != nil {
        return fmt.Errorf("open checkpoint store: %w", err)
        return strategy.RestoredSession{}, false, fmt.Errorf("open checkpoint store: %w", err)
    }
    logContent, _, err := checkpoint.ReadRawSessionLogForCheckpoint(ctx, stores.Primary, checkpointID)
    if err != nil {
3 unmodified lines

slog.String("session_id", sessionID),
            )
            fmt.Fprintf(w, "Session '%s' found in commit trailer but session log not available\n", sessionID)
            fmt.Fprintf(w, "\nTo continue this session:\n")
            fmt.Fprintf(w, "  %s\n", ag.FormatResumeCommand(sessionID))
            return nil
            return restored, true, nil
        }
        logging.Error(ctx, "resume session failed",
            slog.String("checkpoint_id", checkpointID.String()),
            slog.String("session_id", sessionID),
            slog.String("error", err.Error()),
        )
        return fmt.Errorf("failed to get session log: %w", err)
        return strategy.RestoredSession{}, false, fmt.Errorf("failed to get session log: %w", err)
    }

// By default, never overwrite a session log that already exists locally: the
2 unmodified lines

if !force {
        if _, statErr := os.Stat(sessionLogPath); statErr == nil {
            fmt.Fprintf(w, "Keeping existing local session log for '%s' (use --force to overwrite from checkpoint).\n", sessionID)
            fmt.Fprintf(w, "\nTo continue this session:\n")
            fmt.Fprintf(w, "  %s\n", ag.FormatResumeCommand(sessionID))
            return nil
            return restored, true, nil
        }
    }

// Ensure parent directory exists
    if err := os.MkdirAll(filepath.Dir(sessionLogPath), 0o750); err != nil {
        return fmt.Errorf("failed to create session directory: %w", err)
        return strategy.RestoredSession{}, false, fmt.Errorf("failed to create session directory: %w", err)
    }

agentSession := &agent.AgentSession{
11 unmodified lines

slog.String("session_id", sessionID),
            slog.String("error", err.Error()),
        )
        return fmt.Errorf("failed to write session: %w", err)
        return strategy.RestoredSession{}, false, fmt.Errorf("failed to write session: %w", err)
    }

logging.Debug(ctx, "resume session completed",
3 unmodified lines

fmt.Fprintf(w, "✓ Session restored to: %s\n", sessionLogPath)
    fmt.Fprintf(w, "  Session: %s\n", sessionID)
    fmt.Fprintf(w, "\nTo continue this session:\n")
    fmt.Fprintf(w, "  %s\n", ag.FormatResumeCommand(sessionID))

return nil
    return restored, true, nil
}

func promptFetchFromRemote(branchName string) (bool, error) {

Mcmd/entire/cli/resume.go+40/-42

901 unmodified lines

902
903
904
905
905
906
907
908
28 unmodified lines

937
938
939
940
941
942
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
946
956
957
958
959
960
961
952
962
963
964
965
35 unmodified lines

1001
1002
1003
994
1004
1005
1006
1007
15 unmodified lines

1023
1024
1025
1016
1026
1027
1028
1029
40 unmodified lines

1070
1071
1072
1063
1073
1074
1075
1076

901 unmodified lines

}
}

func TestResumeSingleSession_UsesV1Transcript(t *testing.T) {
func TestRestoreSingleSession_UsesV1TranscriptAndReturnsRestoredSession(t *testing.T) {
    tmpDir := t.TempDir()
    t.Chdir(tmpDir)

28 unmodified lines

}

ag := &recordingResumeAgent{sessionDir: filepath.Join(tmpDir, "sessions")}
    var stdout, stderr bytes.Buffer
    if err := resumeSingleSession(ctx, &stdout, &stderr, ag, sessionID, cpID, tmpDir, true); err != nil {
        t.Fatalf("resumeSingleSession() error = %v", err)
    var stdout bytes.Buffer
    restored, ok, err := restoreSingleSession(ctx, &stdout, ag, sessionID, cpID, tmpDir, true)
    if err != nil {
        t.Fatalf("restoreSingleSession() error = %v", err)
    }
    if !ok {
        t.Fatal("restoreSingleSession() ok = false, want true")
    }
    if restored.SessionID != sessionID {
        t.Fatalf("restored SessionID = %q, want %q", restored.SessionID, sessionID)
    }
    if restored.Agent != ag.Type() {
        t.Fatalf("restored Agent = %q, want %q", restored.Agent, ag.Type())
    }

if ag.writtenSession == nil {
        t.Fatal("resumeSingleSession() did not restore a session")
        t.Fatal("restoreSingleSession() did not restore a session")
    }
    if string(ag.writtenSession.NativeData) != string(raw) {
        t.Fatalf("restored transcript = %q, want %q", string(ag.writtenSession.NativeData), string(raw))
    }
    if strings.Contains(stdout.String(), "session log not available") {
        t.Fatalf("resumeSingleSession() reported missing log: %q", stdout.String())
        t.Fatalf("restoreSingleSession() reported missing log: %q", stdout.String())
    }
}

35 unmodified lines

// Call checkRemoteMetadata - should find metadata on the remote tree and
    // attempt to resume, but fail because the test checkpoint has no agent field.
    err = checkRemoteMetadata(context.Background(), os.Stdout, os.Stderr, checkpointID, checkpoint.DefaultV1Refs())
    _, err = checkRemoteMetadata(context.Background(), os.Stdout, os.Stderr, checkpointID, checkpoint.DefaultV1Refs())
    if err == nil {
        t.Error("checkRemoteMetadata() should return error when agent is missing from metadata")
    } else if !strings.Contains(err.Error(), "failed to resolve agent") {
15 unmodified lines

// Don't create any remote ref - simulating no remote entire/checkpoints/v1

// Call checkRemoteMetadata - should handle gracefully (no remote branch)
    err := checkRemoteMetadata(
    _, err := checkRemoteMetadata(
        context.Background(),
        os.Stdout,
        os.Stderr,
40 unmodified lines

}

// Call checkRemoteMetadata with a DIFFERENT checkpoint ID (not on remote)
    err = checkRemoteMetadata(
    _, err = checkRemoteMetadata(
        context.Background(),
        os.Stdout,
        os.Stderr,

Mcmd/entire/cli/resume_test.go+19/-9

27 unmodified lines

28
29
30
31
31
32
33
34
276 unmodified lines

311
312
313
314
314
315
316
317

27 unmodified lines

reviewContextCommitSeparator = "\x1e"
)

type reviewContextSessionMetadataReader interface {
type checkpointSessionMetadataReader interface {
    ReadSessionMetadata(ctx context.Context, checkpointID checkpointid.CheckpointID, sessionIndex int) (*checkpoint.CommittedMetadata, error)
}

276 unmodified lines

cpID checkpointid.CheckpointID,
    sessionIndex int,
) (*checkpoint.CommittedMetadata, error) {
    if r, ok := reader.(reviewContextSessionMetadataReader); ok {
    if r, ok := reader.(checkpointSessionMetadataReader); ok {
        return r.ReadSessionMetadata(ctx, cpID, sessionIndex) //nolint:wrapcheck // Best-effort prompt context.
    }
    content, err := reader.ReadSessionContent(ctx, cpID, sessionIndex)

Mcmd/entire/cli/review_context.go+2/-2

83 unmodified lines

84
85
86
87
88
89
90

83 unmodified lines

// Noun groups (canonical homes for subcommands).
    cmd.AddCommand(newSessionsCmd())        // 'session' (with 'sessions' as Cobra alias)
    cmd.AddCommand(newCheckpointGroupCmd()) // 'checkpoint' / 'cp' / 'checkpoints'
    cmd.AddCommand(newTokensGroupCmd())     // 'tokens'
    cmd.AddCommand(newAgentGroupCmd())      // 'agent'
    cmd.AddCommand(newAuthCmd())            // 'auth'
    cmd.AddCommand(newDoctorCmd())          // 'doctor' (group: trace/logs/bundle)

Mcmd/entire/cli/root.go+1

package cli

import ( "context" "encoding/json" "errors" "fmt" "io" "math/bits" "strings"

"github.com/entireio/cli/cmd/entire/cli/agent" "github.com/entireio/cli/cmd/entire/cli/strategy" "github.com/spf13/cobra" )

type sessionTokensReport struct { SessionID string json:"session_id" Agent string json:"agent" Model string json:"model,omitempty" Status string json:"status" Source string json:"source" Tokens *sessionTokensUsage json:"tokens,omitempty" Context *sessionTokensContext json:"context,omitempty" Contributors []sessionTokensContributor json:"contributors,omitempty" Recommendations []sessionTokensRecommendation json:"recommendations,omitempty" Limitations []string json:"limitations,omitempty" }

type sessionTokensUsage struct { Total int json:"total" Input int json:"input" CacheRead int json:"cache_read" CacheWrite int json:"cache_write" Output int json:"output" APICalls int json:"api_calls" SubagentTotal int json:"subagent_total,omitempty" }

type sessionTokensContext struct { Tokens int json:"tokens" WindowSize int json:"window_size" Percent int json:"percent" }

type sessionTokensContributor struct { Kind string json:"kind" Label string json:"label" Tokens int json:"tokens,omitempty" Percent int json:"percent,omitempty" Confidence string json:"confidence" Signals []string json:"signals,omitempty" }

type sessionTokensRecommendation struct { ID string json:"id" Severity string json:"severity" Message string json:"message" Signals []string json:"signals,omitempty" }

type tokenRecommendationSignals struct { Tokens *sessionTokensUsage Context *sessionTokensContext TurnCount int CheckpointCount int }

// Recommendation thresholds are coarse diagnostics for clear token hotspots, not a cost model or quality verdict. const ( recommendationHighCacheReadPercent = 80 recommendationHighAPICalls = 20 recommendationSubagentShareDenominator = 10 recommendationHighContextPercent = 80 recommendationLongSessionTurns = 10 recommendationLongSessionCheckpoints = 5 )

const agentBriefCostProxyBatchAction = "Use at most 3 batched reads before answering. Continue only if a named file or test can change the verdict; otherwise answer now. Avoid broad grep, broad diffs, broad tests, and repeated token diagnostics; keep the answer tight."

func newTokensCmd() *cobra.Command { var jsonFlag bool var currentFlag bool var agentBriefFlag bool

cmd := &cobra.Command{ Use: "tokens [session-id]", Short: "Show token usage and optimization recommendations for a session", Long: `Show token usage and optimization recommendations for a session.

When no session ID is provided, Entire reports on the most recently active session, preferring the current worktree and falling back to the newest session if no state matches this worktree. The report uses token and context data Entire already captured for the session.

Use --agent-brief when an agent needs compact guidance for the next step, for example: "Use Entire token tracking to check how this session is doing and optimize next steps."`, Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { if jsonFlag && agentBriefFlag { return errors.New("--json and --agent-brief are mutually exclusive") } if currentFlag && len(args) > 0 { return errors.New("--current and session ID argument are mutually exclusive") }

sessionID := "" if len(args) > 0 { sessionID = args[0] } return runSessionTokens(cmd.Context(), cmd, sessionID, currentFlag, jsonFlag, agentBriefFlag) }, }

cmd.Flags().BoolVar(&jsonFlag, "json", false, "Output as JSON") cmd.Flags().BoolVar(&currentFlag, "current", false, "Prefer the current worktree's most recent session") cmd.Flags().BoolVar(&agentBriefFlag, "agent-brief", false, "Output compact next-step guidance for agents") return cmd }

func runSessionTokens(ctx context.Context, cmd *cobra.Command, sessionID string, current, jsonOutput, agentBrief bool) error { if sessionID == "" { if current { sessionID = strategy.FindMostRecentSessionInCurrentWorktree(ctx) } else { sessionID = strategy.FindMostRecentSession(ctx) } if sessionID == "" { fmt.Fprintln(cmd.OutOrStdout(), "No active session found in this worktree.") return nil } }

state, err := strategy.LoadSessionState(ctx, sessionID) if err != nil { return tokenCommandError(fmt.Errorf("failed to load session: %w", err)) } if state == nil { cmd.SilenceUsage = true fmt.Fprintln(cmd.ErrOrStderr(), "Session not found.") return NewSilentError(fmt.Errorf("session not found: %s", sessionID)) }

report := buildSessionTokensReport(state, sessionPhaseLabel(state)) if jsonOutput { return writeSessionTokensJSON(cmd.OutOrStdout(), report) } if agentBrief { writeSessionTokensAgentBrief(cmd.OutOrStdout(), report) return nil } writeSessionTokensText(cmd.OutOrStdout(), report) return nil }

func tokenCommandError(err error) error { if err == nil { return nil } var silent *SilentError if errors.As(err, &silent) { return err } if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { return NewSilentError(err) } return err }

func buildSessionTokensReport(state *strategy.SessionState, status string) sessionTokensReport { agentLabel := string(state.AgentType) if agentLabel == "" { agentLabel = unknownPlaceholder }

report := sessionTokensReport{ SessionID: state.SessionID, Agent: agentLabel, Model: state.ModelName, Status: status, Source: "session_state", }

if tokens := buildSessionTokensUsage(state.TokenUsage); tokens != nil { report.Tokens = tokens if tokens.SubagentTotal > 0 { report.Contributors = append(report.Contributors, sessionTokensContributor{ Kind: "subagents", Label: "Subagents", Tokens: tokens.SubagentTotal, Confidence: "reported", Signals: []string{"subagent_tokens"}, }) } } else { report.Limitations = append(report.Limitations, "No token usage recorded for this session.") report.Recommendations = append(report.Recommendations, sessionTokensRecommendation{ ID: "no-token-data", Severity: "low", Message: "Token usage is unavailable for this session; the agent may not expose token data yet, or no checkpoint has captured it.", Signals: []string{"missing_token_usage"}, }) }

if contextInfo := buildSessionTokensContext(state.ContextTokens, state.ContextWindowSize); contextInfo != nil { report.Context = contextInfo report.Contributors = append(report.Contributors, sessionTokensContributor{ Kind: "context_pressure", Label: "Context pressure", Percent: contextInfo.Percent, Confidence: "reported", Signals: []string{"context_tokens"}, }) }

if labels := skillEventLabels(state.SkillEvents); len(labels) > 0 { report.Contributors = append(report.Contributors, sessionTokensContributor{ Kind: "skills", Label: "Skills/slash commands: " + strings.Join(labels, ", "), Confidence: "reported", Signals: []string{"skill_events"}, }) }

report.Recommendations = append(report.Recommendations, recommendationRules(tokenRecommendationSignals{ Tokens: report.Tokens, Context: report.Context, TurnCount: state.SessionTurnCount, CheckpointCount: state.StepCount, })...) return report }

func buildSessionTokensUsage(usage *agent.TokenUsage) *sessionTokensUsage { if usage == nil { return nil } total := totalTokens(usage) if total == 0 && usage.APICallCount == 0 { return nil } return &sessionTokensUsage{ Total: total, Input: usage.InputTokens, CacheRead: usage.CacheReadTokens, CacheWrite: usage.CacheCreationTokens, Output: usage.OutputTokens, APICalls: usage.APICallCount, SubagentTotal: totalTokens(usage.SubagentTokens), } }

func topLevelSessionTokenTotal(tokens *sessionTokensUsage) int { if tokens == nil { return 0 } total := saturatingIntAdd(tokens.Input, tokens.CacheWrite) total = saturatingIntAdd(total, tokens.CacheRead) return saturatingIntAdd(total, tokens.Output) }

func buildSessionTokensContext(tokens, windowSize int) *sessionTokensContext { if tokens <= 0 || windowSize <= 0 { return nil } return &sessionTokensContext{ Tokens: tokens, WindowSize: windowSize, Percent: roundedPercent(tokens, windowSize), } }

func roundedPercent(value, total int) int { if total <= 0 { return 0 } if value <= 0 { return 0 }

const maxPercent = 100

hi, lo := bits.Mul64(uint64(value), maxPercent) lo, carry := bits.Add64(lo, uint64(total)/2, 0) hi += carry divisor := uint64(total) if hi >= divisor { return maxPercent } quotient, _ := bits.Div64(hi, lo, divisor) if quotient > maxPercent { return maxPercent } return int(quotient) }

func recommendationRules(signals tokenRecommendationSignals) []sessionTokensRecommendation { var recs []sessionTokensRecommendation

cacheReadHotspot := false if signals.Tokens != nil && signals.Tokens.CacheRead > 0 { cacheReadPercent := tokenPercent(signals.Tokens.CacheRead, topLevelSessionTokenTotal(signals.Tokens)) if cacheReadPercent >= recommendationHighCacheReadPercent { cacheReadHotspot = true recs = append(recs, sessionTokensRecommendation{ ID: "context-replay-hotspot", Severity: "high", Message: fmt.Sprintf( "Cache/context replay is %s of token volume; reduce unnecessary follow-up calls in this large-context session.", formatPercent(cacheReadPercent), ), Signals: []string{"cache_read_tokens"}, }) } } if signals.Tokens != nil && signals.Tokens.APICalls >= recommendationHighAPICalls { message := fmt.Sprintf("API call count is high for one session: %d calls. Batch the next diagnosis and reduce iterative calls.", signals.Tokens.APICalls) if cacheReadHotspot { message = fmt.Sprintf("Large context was replayed across %d API calls; batch the next diagnosis and reduce iterative tool calls.", signals.Tokens.APICalls) } recs = append(recs, sessionTokensRecommendation{ ID: "api-call-amplification", Severity: "medium", Message: message, Signals: []string{"api_call_count"}, }) } if signals.Tokens != nil && tokenShareAtLeastOneTenth(signals.Tokens.SubagentTotal, signals.Tokens.Total) { recs = append(recs, sessionTokensRecommendation{ ID: "subagent-heavy", Severity: "medium", Message: "Scope subagent tasks tightly; give each subagent a narrow objective and expected output.", Signals: []string{"subagent_tokens"}, }) } if signals.Tokens != nil && signals.Tokens.Total > 0 && tokenClassPressure(signals.Tokens.CacheWrite, signals.Tokens.Total, 5000, 10, 50_000) { recs = append(recs, sessionTokensRecommendation{ ID: "cache-write-pressure", Severity: "medium", Message: "Cache write is elevated; avoid broad new context and narrow the next read before continuing.", Signals: []string{"cache_write_tokens"}, }) } if signals.Tokens != nil && signals.Tokens.Total > 0 && tokenClassPressure(signals.Tokens.Output, signals.Tokens.Total, 3000, 2, 10_000) { recs = append(recs, sessionTokensRecommendation{ ID: "output-pressure", Severity: "medium", Message: "Output tokens are elevated; keep the next answer tight and avoid restating evidence.", Signals: []string{"output_tokens"}, }) } if signals.Context != nil && signals.Context.Percent >= recommendationHighContextPercent { recs = append(recs, sessionTokensRecommendation{ ID: "high-context-pressure", Severity: "medium", Message: fmt.Sprintf("Context pressure is %d%% of the window; preserve only relevant context before continuing.", signals.Context.Percent), Signals: []string{"context_tokens"}, }) } if cacheReadHotspot && signals.Tokens != nil && signals.Tokens.APICalls >= recommendationHighAPICalls { recs = append(recs, sessionTokensRecommendation{ ID: "summarize-before-boundary", Severity: "low", Message: "Compact or restart after summarizing this investigation; do not discard useful findings just because cache read is high.", Signals: []string{"cache_read_tokens", "api_call_count"}, }) } if signals.TurnCount >= recommendationLongSessionTurns || signals.CheckpointCount >= recommendationLongSessionCheckpoints { recs = append(recs, sessionTokensRecommendation{ ID: "long-session", Severity: "low", Message: "Compact or restart after summarizing the useful findings if older context is no longer needed.", Signals: []string{"turn_count", "checkpoint_count"}, }) }

return recs }

func tokenShareAtLeastOneTenth(part, total int) bool { if part <= 0 || total <= 0 { return false } return part >= (total-1)/recommendationSubagentShareDenominator+1 }

func tokenClassPressure(value, total, minTokens int, minPercent float64, highTokens int) bool { if value <= 0 || total <= 0 { return false } if value >= highTokens { return true } return value >= minTokens && tokenPercent(value, total) >= minPercent }

func tokenPercent(value, total int) float64 { if total <= 0 { return 0 } return float64(value) * 100 / float64(total) }

func formatPercent(percent float64) string { formatted := fmt.Sprintf("%.1f", percent) formatted = strings.TrimSuffix(formatted, ".0") return formatted + "%" }

func skillEventLabels(events []agent.SkillEvent) []string { seen := make(map[string]struct{}, len(events)) labels := make([]string, 0, len(events)) for _, event := range events { label := event.Collapse.Label if label == "" && event.Native != nil { label = event.Native["command"] } if label == "" { label = event.Skill.Name } if label == "" { continue } if _, ok := seen[label]; ok { continue } seen[label] = struct{}{} labels = append(labels, label) } return labels }

func writeSessionTokensJSON(w io.Writer, report sessionTokensReport) error { enc := json.NewEncoder(w) enc.SetIndent("", " ") if err := enc.Encode(report); err != nil { return fmt.Errorf("failed to encode session token report: %w", err) } return nil }

func writeSessionTokensText(w io.Writer, report sessionTokensReport) { fmt.Fprintln(w, "Session tokens") fmt.Fprintln(w) fmt.Fprintf(w, "Session: %s\n", report.SessionID) fmt.Fprintf(w, "Agent: %s\n", report.Agent) if report.Model != "" { fmt.Fprintf(w, "Model: %s\n", report.Model) } fmt.Fprintf(w, "Status: %s\n", report.Status)

writeTokenUsageSection(w, report.Tokens) if len(report.Recommendations) > 0 { writeTokenRecommendations(w, report.Recommendations) }

writeTokenContributors(w, report.Contributors, report.Context) writeTokenLimitations(w, report.Limitations) }

func writeSessionTokensAgentBrief(w io.Writer, report sessionTokensReport) { fmt.Fprintln(w, "Session token brief") fmt.Fprintf(w, "Session: %s\n", report.SessionID) fmt.Fprintln(w) fmt.Fprintln(w, agentBriefUsageLine(report.Tokens)) fmt.Fprintln(w) fmt.Fprintln(w, "Next best action:") fmt.Fprintln(w, agentBriefNextAction(report))

signals := agentBriefSignals(report) if len(signals) > 0 { fmt.Fprintln(w) fmt.Fprintln(w, "Signals:") for _, signal := range signals { fmt.Fprintf(w, "- %s\n", signal) } } }

func agentBriefUsageLine(tokens *sessionTokensUsage) string { if tokens == nil { return "Token usage: unavailable." } if tokens.CacheRead > 0 { return fmt.Sprintf( "Token usage: %s total; %s cache/context replay; %s.", formatTokenCount(tokens.Total), formatPercent(tokenPercent(tokens.CacheRead, topLevelSessionTokenTotal(tokens))), formatAPICalls(tokens.APICalls), ) } return fmt.Sprintf("Token usage: %s total; %s.", formatTokenCount(tokens.Total), formatAPICalls(tokens.APICalls)) }

func formatAPICalls(count int) string { if count == 1 { return "1 API call" } return fmt.Sprintf("%d API calls", count) }

func agentBriefNextAction(report sessionTokensReport) string { if hasTokenRecommendation(report, "no-token-data") { return "Token usage is not available yet. Use this as a context check, not a spend diagnosis; continue after the next checkpoint captures usage." } if action, ok := agentBriefOptimizationAction(report); ok { return action } return "Continue normally; no high-signal token optimization is available from this session yet." }

func agentBriefOptimizationAction(report sessionTokensReport) (string, bool) { switch { case (hasTokenRecommendation(report, "cache-write-pressure") || hasTokenRecommendation(report, "output-pressure")) && (hasTokenRecommendation(report, "context-replay-hotspot") || hasTokenRecommendation(report, "api-call-amplification")): return agentBriefCostProxyBatchAction, true case hasTokenRecommendation(report, "cache-write-pressure") && hasTokenRecommendation(report, "output-pressure"): return agentBriefCostProxyBatchAction, true case hasTokenRecommendation(report, "cache-write-pressure"): return "Use at most 3 batched reads and avoid broad new context until you have one narrowed hypothesis.", true case hasTokenRecommendation(report, "output-pressure"): return "Keep the next answer tight; cite only necessary evidence and avoid restating prior context.", true case hasTokenRecommendation(report, "context-replay-hotspot") && hasTokenRecommendation(report, "api-call-amplification"): return agentBriefCostProxyBatchAction, true case hasTokenRecommendation(report, "api-call-amplification"): return agentBriefCostProxyBatchAction, true case hasTokenRecommendation(report, "context-replay-hotspot"): return "Use at most 2 focused reads only if a named file or test can change the answer; otherwise answer now. Avoid broad grep, broad diffs, and broad tests.", true case hasTokenRecommendation(report, "subagent-heavy"): return "Do not launch broad subagents. Use one narrowly scoped check with a concrete expected output.", true case hasTokenRecommendation(report, "high-context-pressure"): return "Preserve useful findings, then answer with at most 2 focused reads if more evidence is required.", true case hasTokenRecommendation(report, "long-session"): return "Summarize useful findings and stop unless one focused read can change the answer.", true default: return "", false } }

func agentBriefSignals(report sessionTokensReport) []string { var signals []string if hasTokenRecommendation(report, "context-replay-hotspot") { signals = append(signals, "Cache/context replay dominates token volume.") } if hasTokenRecommendation(report, "api-call-amplification") { signals = append(signals, "API call count is high for one session.") } if hasTokenRecommendation(report, "cache-write-pressure") { signals = append(signals, "Cache write/new context pressure is elevated.") } if hasTokenRecommendation(report, "output-pressure") { signals = append(signals, "Output pressure is elevated.") } if hasTokenRecommendation(report, "subagent-heavy") { signals = append(signals, "Subagent usage is a meaningful part of total tokens.") } if hasTokenRecommendation(report, "high-context-pressure") { signals = append(signals, "Context pressure is high.") } if hasTokenRecommendation(report, "long-session") { signals = append(signals, "Session has crossed a long-session or checkpoint boundary.") } if hasTokenRecommendation(report, "no-token-data") { signals = append([]string{"Token usage is unavailable for this session."}, signals...) } if len(signals) == 0 && report.Tokens != nil { signals = append(signals, "No high-signal token risk detected from captured usage.") } return signals }

func hasTokenRecommendation(report sessionTokensReport, id string) bool { for _, rec := range report.Recommendations { if rec.ID == id { return true } } return false }

func writeTokenRecommendations(w io.Writer, recs []sessionTokensRecommendation) { fmt.Fprintln(w) fmt.Fprintln(w, "Recommendations") for _, rec := range recs { fmt.Fprintf(w, "- %s\n", rec.Message) } }

func writeTokenUsageSection(w io.Writer, tokens *sessionTokensUsage) { writeTokenUsageSectionWithTitle(w, "Token usage", tokens) }

func writeTokenUsageSectionWithTitle(w io.Writer, title string, tokens *sessionTokensUsage) { fmt.Fprintln(w) fmt.Fprintln(w, title) if tokens != nil { fmt.Fprintf(w, "Total: %s tokens\n", formatTokenCount(tokens.Total)) parts := []string{ "Input: " + formatTokenCount(tokens.Input), "Cache read: " + formatTokenCount(tokens.CacheRead), "Cache write: " + formatTokenCount(tokens.CacheWrite), "Output: " + formatTokenCount(tokens.Output), fmt.Sprintf("API calls: %d", tokens.APICalls), } fmt.Fprintf(w, " %s\n", strings.Join(parts, " | ")) } else { fmt.Fprintln(w, "Token data: unavailable") } }

func writeTokenContributors(w io.Writer, contributors []sessionTokensContributor, contextInfo *sessionTokensContext) { if len(contributors) > 0 { fmt.Fprintln(w) fmt.Fprintln(w, "Likely contributors") for _, contributor := range contributors { switch contributor.Kind { case "subagents": fmt.Fprintf(w, "- %s: %s tokens\n", contributor.Label, formatTokenCount(contributor.Tokens)) case "context_pressure": if contextInfo != nil { fmt.Fprintf(w, "- %s: %d%% of %s tokens\n", contributor.Label, contextInfo.Percent, formatTokenCount(contextInfo.WindowSize)) } default: fmt.Fprintf(w, "- %s\n", contributor.Label) } } } }

func writeTokenLimitations(w io.Writer, limitations []string) { if len(limitations) > 0 { fmt.Fprintln(w) fmt.Fprintln(w, "Limitations") for _, limitation := range limitations { fmt.Fprintf(w, "- %s\n", limitation) } } }


Acmd/entire/cli/session\_tokens.go+641

163 unmodified lines

164 165 166 167 168 169 170 3 unmodified lines

174 175 176 177 178 179 180 8 unmodified lines

189 190 191 192 193 194 195

163 unmodified lines

Commands: list List all sessions across all worktrees info Show detailed information for a specific session tokens Show token usage and optimization recommendations stop Stop one or more active sessions current Show the active session for the current worktree attach Attach an existing agent session 3 unmodified lines

entire session list List all sessions entire session info Show session details entire session info --json Output as JSON entire session tokens Show token usage entire session stop Interactive stop entire session current Active session for cwd entire session attach Attach an external session 8 unmodified lines

cmd.AddCommand(newListCmd()) cmd.AddCommand(newInfoCmd()) cmd.AddCommand(newTokensCmd()) cmd.AddCommand(newStopCmd()) cmd.AddCommand(newSessionCurrentCmd()) cmd.AddCommand(newAttachCmd())


Mcmd/entire/cli/sessions.go+3

4 unmodified lines

5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 22 23 24 25 27 28 29 30 31 32 33 34 35 283 unmodified lines

319 320 321 315 322 323 324 325 274 unmodified lines

600 601 602 596 603 604 605 606 250 unmodified lines

857 858 859 853 860 861 862 863 54 unmodified lines

918 919 920 914 921 922 923 924 49 unmodified lines

974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914

4 unmodified lines

"context" "encoding/json" "errors" "fmt" "os" "path/filepath" "slices" "strings" "testing" "time"

"github.com/entireio/cli/cmd/entire/cli/agent" "github.com/entireio/cli/cmd/entire/cli/checkpoint" "github.com/entireio/cli/cmd/entire/cli/checkpoint/id" "github.com/entireio/cli/cmd/entire/cli/paths" "github.com/entireio/cli/cmd/entire/cli/session" "github.com/entireio/cli/cmd/entire/cli/strategy" "github.com/entireio/cli/cmd/entire/cli/testutil" "github.com/entireio/cli/redact" )

const ( testAgentClaude = "Claude Code" testAgentGemini = "Gemini CLI" testCheckpointID = "a3b2c4d5e6f7" testPromptFixLogin = "fix the login bug" testAgentClaude = "Claude Code" testAgentGemini = "Gemini CLI" testCheckpointID = "a3b2c4d5e6f7" testModelClaudeOpus = "claude-opus-4-6[1m]" testOtherWorktreePath = "/other/worktree" testPromptFixLogin = "fix the login bug" )

// setupStopTestRepo initializes a temporary git repo, changes to it, and clears 283 unmodified lines

inScope.WorktreePath = worktreePath

outOfScope := makeSessionState("test-all-scope-out", session.PhaseIdle) outOfScope.WorktreePath = "/other/worktree" outOfScope.WorktreePath = testOtherWorktreePath

for _, s := range []*strategy.SessionState{inScope, outOfScope} { if err := strategy.SaveSessionState(ctx, s); err != nil { 274 unmodified lines

// Session in a different worktree — should be stoppable via no-args path. remote := makeSessionState("test-cross-wt-stop", session.PhaseIdle) remote.WorktreePath = "/other/worktree" remote.WorktreePath = testOtherWorktreePath remote.WorktreeID = "other-wt" remote.StepCount = 0

250 unmodified lines

state := makeSessionState("test-info-text", session.PhaseActive) state.AgentType = testAgentClaude state.ModelName = "claude-opus-4-6[1m]" state.ModelName = testModelClaudeOpus state.WorktreeID = "my-feature" state.LastInteractionTime = &lastActive state.SessionTurnCount = 3 54 unmodified lines

state := makeSessionState("test-info-json", session.PhaseIdle) state.AgentType = testAgentClaude state.ModelName = "claude-opus-4-6[1m]" state.ModelName = testModelClaudeOpus state.WorktreeID = "my-feature" state.StepCount = 2 state.LastCheckpointID = testCheckpointID 49 unmodified lines

} }

// --- session tokens tests ---

func TestTokensCmd_TextOutputWithRecommendations(t *testing.T) { setupStopTestRepo(t)

ctx := context.Background() state := makeSessionState("test-tokens-text", session.PhaseActive) state.AgentType = testAgentClaude state.ModelName = testModelClaudeOpus state.SessionTurnCount = 12 state.ContextTokens = 8500 state.ContextWindowSize = 10000 state.TokenUsage = &agent.TokenUsage{ InputTokens: 1000, CacheReadTokens: 10000, CacheCreationTokens: 500, OutputTokens: 100, APICallCount: 6, SubagentTokens: &agent.TokenUsage{ InputTokens: 1000, OutputTokens: 1000, APICallCount: 2, }, }

if err := strategy.SaveSessionState(ctx, state); err != nil { t.Fatalf("SaveSessionState() error = %v", err) }

cmd := newTokensCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"test-tokens-text"})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

out := stdout.String() checks := []string{ "Session tokens", "Session: test-tokens-text", "Agent: Claude Code", "Model: claude-opus-4-6[1m]", "Status: active", "Total: 13.6k tokens", "Input: 1k", "Cache read: 10k", "Cache write: 500", "Output: 100", "API calls: 6", "Subagents: 2k tokens", "Context pressure: 85% of 10k tokens", "Recommendations", "Scope subagent tasks tightly", "Context pressure is 85% of the window", "Compact or restart after summarizing the useful findings", } for _, check := range checks { if !strings.Contains(out, check) { t.Errorf("expected %q in output, got:\n%s", check, out) } }

recommendationsIndex := strings.Index(out, "Recommendations") tokenUsageIndex := strings.Index(out, "Token usage") if recommendationsIndex == -1 || tokenUsageIndex == -1 { t.Fatalf("expected recommendations and token usage sections, got:\n%s", out) } if tokenUsageIndex > recommendationsIndex { t.Fatalf("expected token usage before recommendations, got:\n%s", out) } }

func TestRecommendationRulesSubagentHeavyAvoidsOverflow(t *testing.T) { t.Parallel()

maxInt := int(^uint(0) >> 1) recs := recommendationRules(tokenRecommendationSignals{ Tokens: &sessionTokensUsage{ Total: maxInt, SubagentTotal: maxInt, }, })

for _, rec := range recs { if rec.ID == "subagent-heavy" { return } } t.Fatalf("expected subagent-heavy recommendation, got %+v", recs) }

func TestRecommendationRulesCacheReplayUsesTopLevelTokenTotal(t *testing.T) { t.Parallel()

recs := recommendationRules(tokenRecommendationSignals{ Tokens: &sessionTokensUsage{ Total: 10000, Input: 100, CacheRead: 800, CacheWrite: 50, Output: 50, APICalls: 20, SubagentTotal: 9000, }, })

var ids []string for _, rec := range recs { ids = append(ids, rec.ID) }

expected := []string{"context-replay-hotspot", "summarize-before-boundary"} for _, id := range expected { if !slices.Contains(ids, id) { t.Fatalf("expected %s recommendation in %+v", id, recs) } } }

func TestRecommendationThresholdsDocumentCurrentHeuristics(t *testing.T) { t.Parallel()

checks := map[string]int{ "cache read hotspot percent": recommendationHighCacheReadPercent, "high API calls": recommendationHighAPICalls, "subagent share denominator": recommendationSubagentShareDenominator, "high context percent": recommendationHighContextPercent, "long session turns": recommendationLongSessionTurns, "long checkpoint count": recommendationLongSessionCheckpoints, } want := map[string]int{ "cache read hotspot percent": 80, "high API calls": 20, "subagent share denominator": 10, "high context percent": 80, "long session turns": 10, "long checkpoint count": 5, } for name, got := range checks { if got != want[name] { t.Fatalf("%s = %d, want %d", name, got, want[name]) } } }

func TestTokensCmd_JSONOutputReportsLimitations(t *testing.T) { setupStopTestRepo(t)

ctx := context.Background() state := makeSessionState("test-tokens-json", session.PhaseIdle) state.AgentType = testAgentGemini state.ContextTokens = 9000 state.ContextWindowSize = 10000

if err := strategy.SaveSessionState(ctx, state); err != nil { t.Fatalf("SaveSessionState() error = %v", err) }

cmd := newTokensCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"test-tokens-json", "--json"})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

var result map[string]interface{} if err := json.Unmarshal(stdout.Bytes(), &result); err != nil { t.Fatalf("expected valid JSON, got parse error: %v\noutput: %s", err, stdout.String()) }

if result["session_id"] != "test-tokens-json" { t.Errorf("expected session_id 'test-tokens-json', got: %v", result["session_id"]) } if result["agent"] != testAgentGemini { t.Errorf("expected agent %q, got: %v", testAgentGemini, result["agent"]) } if _, ok := result["tokens"]; ok { t.Errorf("expected tokens to be omitted when no token data exists, got: %v", result["tokens"]) }

recs, ok := result["recommendations"].([]interface{}) if !ok || len(recs) == 0 { t.Fatalf("expected recommendations array, got: %T %v", result["recommendations"], result["recommendations"]) } var sawNoTokenData bool var sawContextPressure bool for _, raw := range recs { rec, ok := raw.(map[string]interface{}) if !ok { t.Fatalf("expected recommendation object, got: %T", raw) } switch rec["id"] { case "no-token-data": sawNoTokenData = true case "high-context-pressure": sawContextPressure = true } } if !sawNoTokenData { t.Error("expected no-token-data recommendation") } if !sawContextPressure { t.Error("expected high-context-pressure recommendation") }

limitations, ok := result["limitations"].([]interface{}) if !ok || len(limitations) == 0 { t.Fatalf("expected limitations array, got: %T %v", result["limitations"], result["limitations"]) } }

func TestTokensCmd_JSONOutputReportsAPICallOnlyUsage(t *testing.T) { setupStopTestRepo(t)

ctx := context.Background() state := makeSessionState("test-tokens-api-only", session.PhaseActive) state.AgentType = testAgentClaude state.TokenUsage = &agent.TokenUsage{ APICallCount: 25, }

if err := strategy.SaveSessionState(ctx, state); err != nil { t.Fatalf("SaveSessionState() error = %v", err) }

cmd := newTokensCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"test-tokens-api-only", "--json"})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

var result sessionTokensReport if err := json.Unmarshal(stdout.Bytes(), &result); err != nil { t.Fatalf("expected valid JSON, got parse error: %v\noutput: %s", err, stdout.String()) } if result.Tokens == nil { t.Fatalf("expected API-call-only token usage to be reported") } if result.Tokens.Total != 0 || result.Tokens.APICalls != 25 { t.Fatalf("unexpected token usage: %+v", result.Tokens) } if reportHasSessionRecommendation(result, "no-token-data") { t.Fatalf("expected API-call-only usage to avoid no-token-data recommendation, got %+v", result.Recommendations) } if !reportHasSessionRecommendation(result, "api-call-amplification") { t.Fatalf("expected api-call-amplification recommendation, got %+v", result.Recommendations) } }

func reportHasSessionRecommendation(report sessionTokensReport, id string) bool { for _, rec := range report.Recommendations { if rec.ID == id { return true } } return false }

func TestRecommendationRules_CacheWritePressure(t *testing.T) { t.Parallel()

recs := recommendationRules(tokenRecommendationSignals{ Tokens: &sessionTokensUsage{ Total: 50_000, CacheWrite: 6_000, }, })

if !recommendationsIncludeID(recs, "cache-write-pressure") { t.Fatalf("expected cache-write-pressure recommendation, got %+v", recs) } }

func TestRecommendationRules_OutputPressure(t *testing.T) { t.Parallel()

recs := recommendationRules(tokenRecommendationSignals{ Tokens: &sessionTokensUsage{ Total: 100_000, Output: 3_500, }, })

if !recommendationsIncludeID(recs, "output-pressure") { t.Fatalf("expected output-pressure recommendation, got %+v", recs) } }

func TestRecommendationRules_OutputPressureWithLargeCacheReplay(t *testing.T) { t.Parallel()

recs := recommendationRules(tokenRecommendationSignals{ Tokens: &sessionTokensUsage{ Total: 10_000_000, CacheRead: 9_800_000, Output: 100_000, }, })

if !recommendationsIncludeID(recs, "output-pressure") { t.Fatalf("expected output-pressure recommendation for high absolute output, got %+v", recs) } }

func recommendationsIncludeID(recs []sessionTokensRecommendation, id string) bool { for _, rec := range recs { if rec.ID == id { return true } } return false }

func TestTokensCmd_AgentBriefPrioritizesNextAction(t *testing.T) { setupStopTestRepo(t)

ctx := context.Background() state := makeSessionState("test-tokens-brief", session.PhaseActive) state.AgentType = testAgentClaude state.TokenUsage = &agent.TokenUsage{ InputTokens: 94, CacheCreationTokens: 122171, CacheReadTokens: 6052424, OutputTokens: 38956, APICallCount: 70, }

if err := strategy.SaveSessionState(ctx, state); err != nil { t.Fatalf("SaveSessionState() error = %v", err) }

cmd := newTokensCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"test-tokens-brief", "--agent-brief"})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

out := stdout.String() checks := []string{ "Session token brief", "Session: test-tokens-brief", "Token usage: 6213.6k total; 97.4% cache/context replay; 70 API calls.", "Next best action:", "Use at most 3 batched reads before answering.", "Continue only if a named file or test can change the verdict; otherwise answer now.", "Avoid broad grep, broad diffs, broad tests, and repeated token diagnostics; keep the answer tight.", "Signals:", "- Cache/context replay dominates token volume.", "- API call count is high for one session.", "- Cache write/new context pressure is elevated.", "- Output pressure is elevated.", } for _, check := range checks { if !strings.Contains(out, check) { t.Errorf("expected %q in output, got:\n%s", check, out) } } if strings.Contains(out, "Recommendations") { t.Fatalf("expected agent brief to omit regular recommendations section, got:\n%s", out) } if strings.Contains(out, "Likely contributors") { t.Fatalf("expected agent brief to omit contributor detail, got:\n%s", out) } }

func TestAgentBriefUsageLineUsesTopLevelCacheReplayTotal(t *testing.T) { t.Parallel()

line := agentBriefUsageLine(&sessionTokensUsage{ Total: 10000, Input: 100, CacheRead: 800, CacheWrite: 50, Output: 50, APICalls: 20, SubagentTotal: 9000, })

want := "Token usage: 10k total; 80% cache/context replay; 20 API calls." if line != want { t.Fatalf("agentBriefUsageLine() = %q, want %q", line, want) } }

func TestTokensCmd_AgentBriefHighCacheReplayWithoutHighAPICalls(t *testing.T) { setupStopTestRepo(t)

ctx := context.Background() state := makeSessionState("test-tokens-brief-cache-only", session.PhaseActive) state.AgentType = testAgentClaude state.TokenUsage = &agent.TokenUsage{ InputTokens: 27_892, CacheReadTokens: 608_896, OutputTokens: 865, APICallCount: 3, }

if err := strategy.SaveSessionState(ctx, state); err != nil { t.Fatalf("SaveSessionState() error = %v", err) }

cmd := newTokensCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"test-tokens-brief-cache-only", "--agent-brief"})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

out := stdout.String() checks := []string{ "Token usage: 637.7k total; 95.5% cache/context replay; 3 API calls.", "Use at most 2 focused reads only if a named file or test can change the answer; otherwise answer now.", "Avoid broad grep, broad diffs, and broad tests.", "- Cache/context replay dominates token volume.", } for _, check := range checks { if !strings.Contains(out, check) { t.Errorf("expected %q in output, got:\n%s", check, out) } } if strings.Contains(out, "Continue normally") { t.Fatalf("expected high cache replay to avoid continue-normally action, got:\n%s", out) } }

func TestTokensCmd_AgentBriefHighAPICallsWithoutCacheReplay(t *testing.T) { setupStopTestRepo(t)

ctx := context.Background() state := makeSessionState("test-tokens-brief-api-only", session.PhaseActive) state.AgentType = testAgentClaude state.TokenUsage = &agent.TokenUsage{ InputTokens: 10_000, OutputTokens: 1_000, APICallCount: 25, }

if err := strategy.SaveSessionState(ctx, state); err != nil { t.Fatalf("SaveSessionState() error = %v", err) }

cmd := newTokensCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"test-tokens-brief-api-only", "--agent-brief"})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

out := stdout.String() checks := []string{ "Token usage: 11k total; 25 API calls.", "Use at most 3 batched reads before answering.", "Avoid broad grep, broad diffs, broad tests, and repeated token diagnostics; keep the answer tight.", "- API call count is high for one session.", } for _, check := range checks { if !strings.Contains(out, check) { t.Errorf("expected %q in output, got:\n%s", check, out) } } if strings.Contains(out, "Continue normally") { t.Fatalf("expected high API calls to avoid continue-normally action, got:\n%s", out) } }

func TestTokensCmd_AgentBriefNoTokenData(t *testing.T) { setupStopTestRepo(t)

ctx := context.Background() state := makeSessionState("test-tokens-brief-missing", session.PhaseActive) state.AgentType = testAgentGemini state.ContextTokens = 9000 state.ContextWindowSize = 10000

if err := strategy.SaveSessionState(ctx, state); err != nil { t.Fatalf("SaveSessionState() error = %v", err) }

cmd := newTokensCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"test-tokens-brief-missing", "--agent-brief"})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

out := stdout.String() checks := []string{ "Session token brief", "Session: test-tokens-brief-missing", "Token usage: unavailable.", "Next best action:", "Token usage is not available yet.", "Signals:", "- Token usage is unavailable for this session.", "- Context pressure is high.", } for _, check := range checks { if !strings.Contains(out, check) { t.Errorf("expected %q in output, got:\n%s", check, out) } } }

func TestSessionTokensAgentBriefClassAwareCostProxy(t *testing.T) { t.Parallel()

tokens := &sessionTokensUsage{ Total: 50_000, CacheWrite: 6_000, Output: 3_500, APICalls: 4, } report := sessionTokensReport{ SessionID: "test-cost-proxy-brief", Tokens: tokens, Recommendations: recommendationRules(tokenRecommendationSignals{Tokens: tokens}), }

var stdout bytes.Buffer writeSessionTokensAgentBrief(&stdout, report)

out := stdout.String() checks := []string{ "Session token brief", "Session: test-cost-proxy-brief", "Use at most 3 batched reads", "Avoid broad grep, broad diffs, broad tests", "otherwise answer now", "keep the answer tight", "- Cache write/new context pressure is elevated.", "- Output pressure is elevated.", } for _, check := range checks { if !strings.Contains(out, check) { t.Errorf("expected %q in output, got:\n%s", check, out) } } }

func TestCheckpointTokensAgentBriefClassAwareCostProxy(t *testing.T) { t.Parallel()

tokens := &sessionTokensUsage{ Total: 50_000, CacheWrite: 6_000, Output: 3_500, APICalls: 4, } report := checkpointTokensReport{ CheckpointID: "c05e500cafe0", Tokens: tokens, Recommendations: recommendationRules(tokenRecommendationSignals{Tokens: tokens}), }

var stdout bytes.Buffer writeCheckpointTokensAgentBrief(&stdout, report)

out := stdout.String() checks := []string{ "Checkpoint token brief", "Checkpoint: c05e500cafe0", "Use at most 3 batched reads", "Avoid broad grep, broad diffs, broad tests", "otherwise answer now", "keep the answer tight", "- Cache write/new context pressure is elevated.", "- Output pressure is elevated.", } for _, check := range checks { if !strings.Contains(out, check) { t.Errorf("expected %q in output, got:\n%s", check, out) } } }

func TestCheckpointTokensAgentBriefCombinesOutputAndReplayPressure(t *testing.T) { t.Parallel()

tokens := &sessionTokensUsage{ Total: 10_000_000, CacheRead: 9_800_000, Output: 100_000, APICalls: 25, } report := checkpointTokensReport{ CheckpointID: "c05e501cafe0", Tokens: tokens, Recommendations: recommendationRules(tokenRecommendationSignals{Tokens: tokens}), }

var stdout bytes.Buffer writeCheckpointTokensAgentBrief(&stdout, report)

out := stdout.String() checks := []string{ "Use at most 3 batched reads", "Avoid broad grep, broad diffs, broad tests", "keep the answer tight", "- Cache/context replay dominates token volume.", "- API call count is high for one session.", "- Output pressure is elevated.", } for _, check := range checks { if !strings.Contains(out, check) { t.Errorf("expected %q in output, got:\n%s", check, out) } } }

func TestSessionsCmd_TokensSubcommand(t *testing.T) { setupStopTestRepo(t)

ctx := context.Background() state := makeSessionState("test-tokens-subcommand", session.PhaseActive) state.TokenUsage = &agent.TokenUsage{InputTokens: 42}

if err := strategy.SaveSessionState(ctx, state); err != nil { t.Fatalf("SaveSessionState() error = %v", err) }

cmd := newSessionsCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"tokens", "test-tokens-subcommand", "--json"})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

var result sessionTokensReport if err := json.Unmarshal(stdout.Bytes(), &result); err != nil { t.Fatalf("expected valid JSON, got parse error: %v\noutput: %s", err, stdout.String()) } if result.SessionID != "test-tokens-subcommand" { t.Errorf("expected session_id 'test-tokens-subcommand', got: %q", result.SessionID) } if result.Tokens == nil || result.Tokens.Total != 42 { t.Fatalf("expected token total 42, got: %+v", result.Tokens) } }

func TestSessionsCmd_TokensSubcommandAgentBrief(t *testing.T) { setupStopTestRepo(t)

ctx := context.Background() state := makeSessionState("test-tokens-subcommand-brief", session.PhaseActive) state.TokenUsage = &agent.TokenUsage{ InputTokens: 1200, OutputTokens: 300, APICallCount: 2, }

if err := strategy.SaveSessionState(ctx, state); err != nil { t.Fatalf("SaveSessionState() error = %v", err) }

cmd := newSessionsCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"tokens", "test-tokens-subcommand-brief", "--agent-brief"})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

out := stdout.String() if !strings.Contains(out, "Session token brief") { t.Fatalf("expected agent brief output, got:\n%s", out) } if !strings.Contains(out, "Token usage: 1.5k total") { t.Fatalf("expected token summary in brief, got:\n%s", out) } }

func TestSessionsCmd_HelpIncludesTokensSubcommand(t *testing.T) { cmd := newSessionsCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"--help"})

if err := cmd.ExecuteContext(context.Background()); err != nil { t.Fatalf("expected no error, got: %v", err) }

out := stdout.String() if !strings.Contains(out, "tokens Show token usage and optimization recommendations") { t.Fatalf("expected tokens command in manual command list, got:\n%s", out) } if !strings.Contains(out, "entire session tokens Show token usage") { t.Fatalf("expected tokens example in help, got:\n%s", out) } }

func TestTokensCmd_JSONAndAgentBriefAreMutuallyExclusive(t *testing.T) { setupStopTestRepo(t)

cmd := newTokensCmd() cmd.SetArgs([]string{"test-session", "--json", "--agent-brief"})

err := cmd.ExecuteContext(context.Background()) if err == nil { t.Fatal("expected error for --json with --agent-brief") } if !strings.Contains(err.Error(), "mutually exclusive") { t.Fatalf("expected mutually exclusive error, got: %v", err) } }

func TestCheckpointTokensCmd_JSONAndAgentBriefAreMutuallyExclusive(t *testing.T) { t.Parallel()

cmd := newCheckpointGroupCmd() cmd.SetArgs([]string{"tokens", "abc123", "--json", "--agent-brief"})

func TestTokensCmd_PrioritizesContextReplayHotspot(t *testing.T) { setupStopTestRepo(t)

ctx := context.Background() state := makeSessionState("test-tokens-hotspot", session.PhaseActive) state.AgentType = testAgentClaude state.SessionTurnCount = 4 state.TokenUsage = &agent.TokenUsage{ InputTokens: 94, CacheCreationTokens: 122171, CacheReadTokens: 6052424, OutputTokens: 38956, APICallCount: 70, }

if err := strategy.SaveSessionState(ctx, state); err != nil { t.Fatalf("SaveSessionState() error = %v", err) }

cmd := newTokensCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"test-tokens-hotspot"})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

out := stdout.String() checks := []string{ "Recommendations", "Cache/context replay is 97.4% of token volume", "Large context was replayed across 70 API calls", "Compact or restart after summarizing this investigation", "Token usage", "Total: 6213.6k tokens", "Cache read: 6052.4k", } for _, check := range checks { if !strings.Contains(out, check) { t.Errorf("expected %q in output, got:\n%s", check, out) } }

recommendationsIndex := strings.Index(out, "Recommendations") tokenUsageIndex := strings.Index(out, "Token usage") if recommendationsIndex == -1 || tokenUsageIndex == -1 { t.Fatalf("expected recommendations and token usage sections, got:\n%s", out) } if tokenUsageIndex > recommendationsIndex { t.Fatalf("expected token usage before recommendations, got:\n%s", out) } if strings.Contains(out, "Start a fresh session after major task boundaries") { t.Fatalf("expected no generic fresh-session recommendation, got:\n%s", out) } }

func TestTokensCmd_DefaultsToCurrentSession(t *testing.T) { setupStopTestRepo(t)

ctx := context.Background() repoRoot, err := paths.WorktreeRoot(ctx) if err != nil { t.Fatalf("WorktreeRoot() error = %v", err) } now := time.Now()

current := makeSessionState("test-tokens-current", session.PhaseActive) current.WorktreePath = repoRoot current.LastInteractionTime = &now current.TokenUsage = &agent.TokenUsage{InputTokens: 1200}

otherTime := now.Add(5 * time.Minute) other := makeSessionState("test-tokens-other", session.PhaseActive) other.WorktreePath = testOtherWorktreePath other.LastInteractionTime = &otherTime other.TokenUsage = &agent.TokenUsage{InputTokens: 9999}

for _, s := range []*strategy.SessionState{current, other} { if err := strategy.SaveSessionState(ctx, s); err != nil { t.Fatalf("SaveSessionState() error = %v", err) } }

cmd := newTokensCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

out := stdout.String() if !strings.Contains(out, "Session: test-tokens-current") { t.Fatalf("expected current worktree session, got:\n%s", out) } if strings.Contains(out, "test-tokens-other") { t.Fatalf("expected other worktree session to be ignored, got:\n%s", out) } }

func TestTokensCmd_CurrentDoesNotFallbackToOtherWorktree(t *testing.T) { setupStopTestRepo(t)

ctx := context.Background() now := time.Now() other := makeSessionState("test-tokens-other-only", session.PhaseActive) other.WorktreePath = testOtherWorktreePath other.LastInteractionTime = &now other.TokenUsage = &agent.TokenUsage{InputTokens: 9999}

if err := strategy.SaveSessionState(ctx, other); err != nil { t.Fatalf("SaveSessionState() error = %v", err) }

defaultCmd := newTokensCmd() var defaultStdout bytes.Buffer defaultCmd.SetOut(&defaultStdout) defaultCmd.SetArgs([]string{}) if err := defaultCmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected default command to fall back, got: %v", err) } if !strings.Contains(defaultStdout.String(), "Session: test-tokens-other-only") { t.Fatalf("expected default command to fall back to other worktree session, got:\n%s", defaultStdout.String()) }

currentCmd := newTokensCmd() var currentStdout bytes.Buffer currentCmd.SetOut(&currentStdout) currentCmd.SetArgs([]string{"--current"}) if err := currentCmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected --current command to avoid fallback without error, got: %v", err) } out := currentStdout.String() if !strings.Contains(out, "No active session found in this worktree.") { t.Fatalf("expected --current command to report no current worktree session, got:\n%s", out) } if strings.Contains(out, "test-tokens-other-only") { t.Fatalf("expected --current command not to fall back to other worktree, got:\n%s", out) } }

func TestTokensCmd_CurrentAndSessionIDAreMutuallyExclusive(t *testing.T) { setupStopTestRepo(t)

cmd := newTokensCmd() cmd.SetArgs([]string{"test-session", "--current"})

err := cmd.ExecuteContext(context.Background()) if err == nil { t.Fatal("expected error for --current with session ID") } if !strings.Contains(err.Error(), "mutually exclusive") { t.Fatalf("expected mutually exclusive error, got: %v", err) } }

func TestTokenCommandError_SuppressesCancellation(t *testing.T) { err := tokenCommandError(fmt.Errorf("wrapped: %w", context.Canceled)) if !errors.Is(err, context.Canceled) { t.Fatalf("expected context.Canceled in error chain, got: %v", err) } var silentErr *SilentError if !errors.As(err, &silentErr) { t.Fatalf("expected SilentError, got: %T %v", err, err) } }

func TestRoundedPercentAvoidsIntermediateOverflow(t *testing.T) { t.Parallel()

maxInt := int(^uint(0) >> 1)

if got := roundedPercent(maxInt/2, maxInt); got != 50 { t.Fatalf("roundedPercent() = %d, want 50", got) } }

func TestRoundedPercentClampsAt100(t *testing.T) { t.Parallel()

if got := roundedPercent(200, 100); got != 100 { t.Fatalf("roundedPercent() = %d, want 100", got) } }

// --- checkpoint tokens tests ---

func TestCheckpointTokensCmd_TextOutputWithRealCheckpointShape(t *testing.T) { repo, _ := runExplainAutoTestRepo(t) ctx := context.Background() cpID := id.MustCheckpointID("beefbeefcafe") if err := checkpoint.NewGitStore(repo, checkpoint.DefaultV1Refs()).WriteCommitted(ctx, checkpoint.WriteCommittedOptions{ CheckpointID: cpID, SessionID: "checkpoint-token-session", Strategy: strategy.StrategyNameManualCommit, Branch: "e2e-triage-fix", Agent: testAgentClaude, Transcript: redact.AlreadyRedacted([]byte({"type":"user","message":{"content":[{"type":"text","text":"why is slack failing"}]}} + "\n")), AuthorName: "Test", AuthorEmail: "test@example.com", TokenUsage: &agent.TokenUsage{ InputTokens: 94, CacheCreationTokens: 122171, CacheReadTokens: 6052424, OutputTokens: 38956, APICallCount: 70, }, }); err != nil { t.Fatalf("WriteCommitted() error = %v", err) }

cmd := newCheckpointGroupCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"tokens", "beefbeef"})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

out := stdout.String() checks := []string{ "Checkpoint tokens", "Checkpoint: beefbeefcafe", "Session: checkpoint-token-session", "Agent: Claude Code", "Branch: e2e-triage-fix", "Recommendations", "Cache/context replay is 97.4% of token volume", "Large context was replayed across 70 API calls", "Token usage", "Total: 6213.6k tokens", "Cache read: 6052.4k", } for _, check := range checks { if !strings.Contains(out, check) { t.Errorf("expected %q in output, got:\n%s", check, out) } }

func TestCheckpointTokensCmd_AgentBriefGivesOperationalBudget(t *testing.T) { repo, _ := runExplainAutoTestRepo(t) ctx := context.Background() cpID := id.MustCheckpointID("b1efbeefcafe") if err := checkpoint.NewGitStore(repo, checkpoint.DefaultV1Refs()).WriteCommitted(ctx, checkpoint.WriteCommittedOptions{ CheckpointID: cpID, SessionID: "checkpoint-token-brief", Strategy: strategy.StrategyNameManualCommit, Branch: "e2e-triage-fix", Agent: testAgentClaude, Transcript: redact.AlreadyRedacted([]byte({"type":"user","message":{"content":[{"type":"text","text":"why is slack failing"}]}} + "\n")), AuthorName: "Test", AuthorEmail: "test@example.com", TokenUsage: &agent.TokenUsage{ InputTokens: 94, CacheCreationTokens: 122171, CacheReadTokens: 6052424, OutputTokens: 38956, APICallCount: 70, }, }); err != nil { t.Fatalf("WriteCommitted() error = %v", err) }

cmd := newCheckpointGroupCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"tokens", "b1efbeef", "--agent-brief"})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

out := stdout.String() checks := []string{ "Checkpoint token brief", "Checkpoint: b1efbeefcafe", "Token usage: 6213.6k total; 97.4% cache/context replay; 70 API calls.", "Next best action:", "Use at most 3 batched reads before answering.", "Continue only if a named file or test can change the verdict; otherwise answer now.", "Avoid broad grep, broad diffs, broad tests, and repeated token diagnostics; keep the answer tight.", "Signals:", "- Cache/context replay dominates token volume.", "- API call count is high for one session.", "- Cache write/new context pressure is elevated.", "- Output pressure is elevated.", } for _, check := range checks { if !strings.Contains(out, check) { t.Errorf("expected %q in output, got:\n%s", check, out) } } for _, verboseSection := range []string{"Recommendations", "Likely contributors", "Limitations"} { if strings.Contains(out, verboseSection) { t.Fatalf("expected agent brief to omit %s section, got:\n%s", verboseSection, out) } } }

func TestCheckpointTokensCmd_AgentBriefMissingTokenData(t *testing.T) { repo, _ := runExplainAutoTestRepo(t) ctx := context.Background() store := checkpoint.NewGitStore(repo, checkpoint.DefaultV1Refs()) cpID := id.MustCheckpointID("deadcafebeef") writeCommittedTokenCheckpoint(ctx, t, store, cpID, "checkpoint-token-missing-brief", nil)

cmd := newCheckpointGroupCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"tokens", "deadcafe", "--agent-brief"})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

out := stdout.String() checks := []string{ "Checkpoint token brief", "Checkpoint: deadcafebeef", "Token usage: unavailable.", "Do not spend extra commands on token optimization for this checkpoint.", "- Token usage is unavailable for this session.", } for _, check := range checks { if !strings.Contains(out, check) { t.Errorf("expected %q in output, got:\n%s", check, out) } } }

func TestCheckpointTokensCmd_TextOutputWithMultipleSessionsUsesAggregateScope(t *testing.T) { repo, _ := runExplainAutoTestRepo(t) ctx := context.Background() store := checkpoint.NewGitStore(repo, checkpoint.DefaultV1Refs()) cpID := id.MustCheckpointID("feedfeedcafe")

if err := store.WriteCommitted(ctx, checkpoint.WriteCommittedOptions{ CheckpointID: cpID, SessionID: "checkpoint-token-session-one", Strategy: strategy.StrategyNameManualCommit, Branch: "multi-session-branch", Agent: testAgentClaude, Transcript: redact.AlreadyRedacted([]byte({"type":"user","message":{"content":[{"type":"text","text":"first session"}]}} + "\n")), AuthorName: "Test", AuthorEmail: "test@example.com", TokenUsage: &agent.TokenUsage{ InputTokens: 1000, APICallCount: 1, SubagentTokens: &agent.TokenUsage{ InputTokens: 2000, OutputTokens: 500, APICallCount: 2, }, }, }); err != nil { t.Fatalf("WriteCommitted() first session error = %v", err) } if err := store.WriteCommitted(ctx, checkpoint.WriteCommittedOptions{ CheckpointID: cpID, SessionID: "checkpoint-token-session-two", Strategy: strategy.StrategyNameManualCommit, Branch: "multi-session-branch", Agent: testAgentGemini, Transcript: redact.AlreadyRedacted([]byte({"type":"user","message":{"content":[{"type":"text","text":"second session"}]}} + "\n")), AuthorName: "Test", AuthorEmail: "test@example.com", TokenUsage: &agent.TokenUsage{ InputTokens: 500, OutputTokens: 500, APICallCount: 2, }, }); err != nil { t.Fatalf("WriteCommitted() second session error = %v", err) }

cmd := newCheckpointGroupCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"tokens", "feedfeed"})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

out := stdout.String() checks := []string{ "Checkpoint tokens", "Checkpoint: feedfeedcafe", "Sessions: 2", "Agents: Claude Code, Gemini CLI", "Branch: multi-session-branch", "Total: 4.5k tokens", "Input: 1.5k", "Output: 500", "API calls: 3", "Subagents: 2.5k tokens", } for _, check := range checks { if !strings.Contains(out, check) { t.Errorf("expected %q in output, got:\n%s", check, out) } } if strings.Contains(out, "Session: checkpoint-token-session-two") { t.Fatalf("expected aggregate checkpoint output, not latest-session attribution, got:\n%s", out) } }

func TestCheckpointTokensCmd_JSONOutput(t *testing.T) { repo, _ := runExplainAutoTestRepo(t) ctx := context.Background() cpID := id.MustCheckpointID("cafe00001234") if err := checkpoint.NewGitStore(repo, checkpoint.DefaultV1Refs()).WriteCommitted(ctx, checkpoint.WriteCommittedOptions{ CheckpointID: cpID, SessionID: "checkpoint-token-json", Strategy: strategy.StrategyNameManualCommit, Agent: testAgentGemini, Transcript: redact.AlreadyRedacted([]byte({"type":"user","message":{"content":[{"type":"text","text":"token json"}]}} + "\n")), AuthorName: "Test", AuthorEmail: "test@example.com", TokenUsage: &agent.TokenUsage{ InputTokens: 120, OutputTokens: 30, APICallCount: 1, }, }); err != nil { t.Fatalf("WriteCommitted() error = %v", err) }

cmd := newCheckpointGroupCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"tokens", "cafe0000", "--json"})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

var result checkpointTokensReport if err := json.Unmarshal(stdout.Bytes(), &result); err != nil { t.Fatalf("expected valid JSON, got parse error: %v\noutput: %s", err, stdout.String()) } if result.CheckpointID != "cafe00001234" { t.Errorf("expected checkpoint_id 'cafe00001234', got: %q", result.CheckpointID) } if result.SessionID != "checkpoint-token-json" { t.Errorf("expected session_id 'checkpoint-token-json', got: %q", result.SessionID) } if result.Tokens == nil || result.Tokens.Total != 150 { t.Fatalf("expected token total 150, got: %+v", result.Tokens) } }

func TestCheckpointTokensReport_UsesRootSummaryWhenSessionMetadataIncomplete(t *testing.T) { t.Parallel()

cpID := id.MustCheckpointID("abc123abc123") report := buildCheckpointTokensReport( cpID, &checkpoint.CheckpointSummary{ CheckpointID: cpID, Sessions: []checkpoint.SessionFilePaths{ {Metadata: "0/metadata.json"}, {Metadata: "1/metadata.json"}, }, TokenUsage: &agent.TokenUsage{ InputTokens: 1000, OutputTokens: 500, APICallCount: 7, }, }, []*checkpoint.CommittedMetadata{ { SessionID: "readable-session", Agent: "Claude Code", Model: "claude-opus-4-6", TokenUsage: &agent.TokenUsage{ InputTokens: 100, }, SessionMetrics: &checkpoint.SessionMetrics{ ContextTokens: 9000, ContextWindowSize: 10000, }, }, }, 1, )

if report.Tokens == nil { t.Fatalf("expected token data, got nil") } if report.Tokens.Total != 1500 || report.Tokens.APICalls != 7 { t.Fatalf("expected root summary tokens, got %+v", report.Tokens) } if report.SessionID != "" || report.Agent != "" || report.Model != "" { t.Fatalf("expected multi-session checkpoint to omit singular session fields, got session_id=%q agent=%q model=%q", report.SessionID, report.Agent, report.Model) } if report.Context != nil { t.Fatalf("expected multi-session checkpoint to omit singular context, got %+v", report.Context) } for _, contributor := range report.Contributors { if contributor.Kind == "context_pressure" { t.Fatalf("expected multi-session checkpoint to omit singular context contributor, got %+v", report.Contributors) } } if len(report.Limitations) == 0 || !strings.Contains(report.Limitations[0], "1 checkpoint session metadata file could not be read") { t.Fatalf("expected incomplete metadata limitation, got %+v", report.Limitations) } }

func TestAddCheckpointTokenUsageSaturatesOverflow(t *testing.T) { t.Parallel()

maxInt := int(^uint(0) >> 1) usage := addCheckpointTokenUsage( &agent.TokenUsage{ InputTokens: maxInt, CacheCreationTokens: maxInt, CacheReadTokens: maxInt, OutputTokens: maxInt, APICallCount: maxInt, SubagentTokens: &agent.TokenUsage{ InputTokens: maxInt, }, }, &agent.TokenUsage{ InputTokens: 1, CacheCreationTokens: 1, CacheReadTokens: 1, OutputTokens: 1, APICallCount: 1, SubagentTokens: &agent.TokenUsage{ InputTokens: 1, }, }, )

if usage.InputTokens != maxInt || usage.CacheCreationTokens != maxInt || usage.CacheReadTokens != maxInt || usage.OutputTokens != maxInt || usage.APICallCount != maxInt { t.Fatalf("expected saturated top-level usage, got %+v", usage) } if usage.SubagentTokens == nil || usage.SubagentTokens.InputTokens != maxInt { t.Fatalf("expected saturated subagent usage, got %+v", usage.SubagentTokens) } }

func TestCheckpointTokensReport_UsesRootSummaryWhenNoSessionMetadataReadable(t *testing.T) { t.Parallel()

cpID := id.MustCheckpointID("abc123def456") report := buildCheckpointTokensReport( cpID, &checkpoint.CheckpointSummary{ CheckpointID: cpID, Sessions: []checkpoint.SessionFilePaths{ {Metadata: "0/metadata.json"}, {Metadata: "1/metadata.json"}, }, TokenUsage: &agent.TokenUsage{ InputTokens: 1000, OutputTokens: 500, APICallCount: 7, }, }, nil, 2, )

if report.Tokens == nil { t.Fatalf("expected token data, got nil") } if report.Tokens.Total != 1500 || report.Tokens.APICalls != 7 { t.Fatalf("expected root summary tokens, got %+v", report.Tokens) } }

type cancelingCheckpointMetadataReader struct { cancel context.CancelFunc calls int }

func (r *cancelingCheckpointMetadataReader) ReadSessionMetadata( _ context.Context, _ id.CheckpointID, _ int, ) (*checkpoint.CommittedMetadata, error) { r.calls++ if r.calls == 1 { r.cancel() return &checkpoint.CommittedMetadata{SessionID: "read-before-cancel"}, nil } return &checkpoint.CommittedMetadata{SessionID: "read-after-cancel"}, nil }

func TestReadCheckpointTokenSessionMetadataStopsBetweenReadsWhenContextCanceled(t *testing.T) { t.Parallel()

ctx, cancel := context.WithCancel(context.Background()) reader := &cancelingCheckpointMetadataReader{cancel: cancel}

metas, warnings, err := readCheckpointTokenSessionMetadata(ctx, reader, id.MustCheckpointID("abc123abc123"), 2) if !errors.Is(err, context.Canceled) { t.Fatalf("expected context.Canceled, got metas=%+v warnings=%d err=%v", metas, warnings, err) } if reader.calls != 1 { t.Fatalf("expected one metadata read before cancellation, got %d", reader.calls) } if metas != nil || warnings != 0 { t.Fatalf("expected canceled read to return no partial results, got metas=%+v warnings=%d", metas, warnings) } }

func TestReadCheckpointTokenSessionMetadataChecksCanceledContextBeforeAllocation(t *testing.T) { t.Parallel()

ctx, cancel := context.WithCancel(context.Background()) cancel()

metas, warnings, err := readCheckpointTokenSessionMetadata(ctx, nil, id.MustCheckpointID("abc123abc123"), 0) if !errors.Is(err, context.Canceled) { t.Fatalf("expected context.Canceled, got metas=%+v warnings=%d err=%v", metas, warnings, err) } if metas != nil || warnings != 0 { t.Fatalf("expected canceled read to return no results, got metas=%+v warnings=%d", metas, warnings) } }

func TestCheckpointTokensCmd_TextOutputWithComparison(t *testing.T) { repo, _ := runExplainAutoTestRepo(t) ctx := context.Background() store := checkpoint.NewGitStore(repo, checkpoint.DefaultV1Refs()) baselineID := id.MustCheckpointID("aaa111bbb222") currentID := id.MustCheckpointID("bbb222ccc333")

if err := store.WriteCommitted(ctx, checkpoint.WriteCommittedOptions{ CheckpointID: baselineID, SessionID: "checkpoint-token-baseline", Strategy: strategy.StrategyNameManualCommit, Branch: "tokens-compare", Agent: testAgentClaude, Transcript: redact.AlreadyRedacted([]byte({"type":"user","message":{"content":[{"type":"text","text":"baseline"}]}} + "\n")), AuthorName: "Test", AuthorEmail: "test@example.com", TokenUsage: &agent.TokenUsage{ InputTokens: 200_000, CacheCreationTokens: 50_000, CacheReadTokens: 750_000, OutputTokens: 10_000, APICallCount: 10, }, }); err != nil { t.Fatalf("WriteCommitted() baseline error = %v", err) } if err := store.WriteCommitted(ctx, checkpoint.WriteCommittedOptions{ CheckpointID: currentID, SessionID: "checkpoint-token-current", Strategy: strategy.StrategyNameManualCommit, Branch: "tokens-compare", Agent: testAgentClaude, Transcript: redact.AlreadyRedacted([]byte({"type":"user","message":{"content":[{"type":"text","text":"current"}]}} + "\n")), AuthorName: "Test", AuthorEmail: "test@example.com", TokenUsage: &agent.TokenUsage{ InputTokens: 150_000, CacheCreationTokens: 25_000, CacheReadTokens: 300_000, OutputTokens: 25_000, APICallCount: 4, }, }); err != nil { t.Fatalf("WriteCommitted() current error = %v", err) }

cmd := newCheckpointGroupCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"tokens", "bbb222", "--compare", "aaa111"})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

out := stdout.String() checks := []string{ "Checkpoint tokens", "Checkpoint: bbb222ccc333", "Token usage", "Total: 500k tokens", "Comparison", "Baseline: aaa111bbb222", "Caveat: Total tokens include cache/context replay; use the cache/context replay delta below before treating total direction as work saved or added.", "Total tokens: down 50.5% (1010k -> 500k)", "Input: down 25% (200k -> 150k)", "Cache/context replay: down 60% (750k -> 300k)", "Cache write: down 50% (50k -> 25k)", "Output: up 150% (10k -> 25k)", "API calls: down 60% (10 -> 4)", "Qualification", "Observed total token use decreased for this checkpoint comparison.", "This does not prove quality was preserved", "Cost-proxy pressure increased for output", } for _, check := range checks { if !strings.Contains(out, check) { t.Errorf("expected %q in output, got:\n%s", check, out) } } }

func TestCheckpointTokensCmd_RejectsSelfComparison(t *testing.T) { repo, _ := runExplainAutoTestRepo(t) ctx := context.Background() store := checkpoint.NewGitStore(repo, checkpoint.DefaultV1Refs()) cpID := id.MustCheckpointID("abc222abc222")

writeCommittedTokenCheckpoint(ctx, t, store, cpID, "checkpoint-token-self-compare", &agent.TokenUsage{ InputTokens: 100, OutputTokens: 50, APICallCount: 1, })

cmd := newCheckpointGroupCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"tokens", "abc222", "--compare", "abc222abc222"})

err := cmd.ExecuteContext(ctx) if err == nil { t.Fatal("expected self-comparison error, got nil") } if !strings.Contains(err.Error(), "cannot compare checkpoint abc222abc222 to itself") { t.Fatalf("expected self-comparison error, got: %v", err) } if stdout.Len() != 0 { t.Fatalf("expected no report output for self-comparison, got:\n%s", stdout.String()) } }

func TestCheckpointTokensCmd_JSONOutputWithComparison(t *testing.T) { repo, _ := runExplainAutoTestRepo(t) ctx := context.Background() store := checkpoint.NewGitStore(repo, checkpoint.DefaultV1Refs()) baselineID := id.MustCheckpointID("abc111abc111") currentID := id.MustCheckpointID("abc222abc222")

if err := store.WriteCommitted(ctx, checkpoint.WriteCommittedOptions{ CheckpointID: baselineID, SessionID: "checkpoint-token-json-baseline", Strategy: strategy.StrategyNameManualCommit, Agent: testAgentGemini, Transcript: redact.AlreadyRedacted([]byte({"type":"user","message":{"content":[{"type":"text","text":"baseline json"}]}} + "\n")), AuthorName: "Test", AuthorEmail: "test@example.com", TokenUsage: &agent.TokenUsage{ InputTokens: 100, CacheCreationTokens: 50, CacheReadTokens: 300, OutputTokens: 100, APICallCount: 5, }, }); err != nil { t.Fatalf("WriteCommitted() baseline error = %v", err) } if err := store.WriteCommitted(ctx, checkpoint.WriteCommittedOptions{ CheckpointID: currentID, SessionID: "checkpoint-token-json-current", Strategy: strategy.StrategyNameManualCommit, Agent: testAgentGemini, Transcript: redact.AlreadyRedacted([]byte({"type":"user","message":{"content":[{"type":"text","text":"current json"}]}} + "\n")), AuthorName: "Test", AuthorEmail: "test@example.com", TokenUsage: &agent.TokenUsage{ InputTokens: 120, CacheCreationTokens: 80, CacheReadTokens: 480, OutputTokens: 200, APICallCount: 8, }, }); err != nil { t.Fatalf("WriteCommitted() current error = %v", err) }

cmd := newCheckpointGroupCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"tokens", "abc222", "--compare", "abc111", "--json"})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

var result checkpointTokensReport if err := json.Unmarshal(stdout.Bytes(), &result); err != nil { t.Fatalf("expected valid JSON, got parse error: %v\noutput: %s", err, stdout.String()) } if result.Comparison == nil { t.Fatalf("expected comparison, got nil") } if result.Comparison.Status != "observed_increase" { t.Fatalf("expected observed_increase status, got %q", result.Comparison.Status) } if result.Comparison.BaselineCheckpointID != "abc111abc111" { t.Errorf("baseline checkpoint id = %q, want abc111abc111", result.Comparison.BaselineCheckpointID) } if result.Comparison.TargetCheckpointID != "abc222abc222" { t.Errorf("target checkpoint id = %q, want abc222abc222", result.Comparison.TargetCheckpointID) } if result.Comparison.Total == nil { t.Fatalf("expected total delta, got nil") } if result.Comparison.Total.Baseline != 550 || result.Comparison.Total.Current != 880 { t.Fatalf("unexpected total delta: %+v", result.Comparison.Total) } if result.Comparison.Total.Change != 330 { t.Fatalf("expected total change 330, got %+v", result.Comparison.Total) } if result.Comparison.Total.Direction != checkpointDeltaDirectionUp { t.Fatalf("expected total direction up, got %+v", result.Comparison.Total) } if result.Comparison.Total.ChangePercent == nil || *result.Comparison.Total.ChangePercent != 60 { t.Fatalf("expected total change percent 60, got %+v", result.Comparison.Total) } if result.Comparison.CacheReadCaveat == "" { t.Fatalf("expected cache read caveat, got %+v", result.Comparison) } if result.Comparison.Input == nil || result.Comparison.Input.Change != 20 { t.Fatalf("expected input change 20, got %+v", result.Comparison.Input) } if result.Comparison.CacheWrite == nil || result.Comparison.CacheWrite.Change != 30 { t.Fatalf("expected cache write change 30, got %+v", result.Comparison.CacheWrite) } if result.Comparison.Output == nil || result.Comparison.Output.Change != 100 { t.Fatalf("expected output change 100, got %+v", result.Comparison.Output) } }

func TestCheckpointTokensCmd_JSONComparisonQualifiesCostProxyPressure(t *testing.T) { repo, _ := runExplainAutoTestRepo(t) ctx := context.Background() store := checkpoint.NewGitStore(repo, checkpoint.DefaultV1Refs()) baselineID := id.MustCheckpointID("c0a111c0a111") currentID := id.MustCheckpointID("c0a222c0a222")

writeCommittedTokenCheckpoint(ctx, t, store, baselineID, "checkpoint-token-cost-proxy-baseline", &agent.TokenUsage{ InputTokens: 100_000, CacheReadTokens: 100_000, APICallCount: 6, }) writeCommittedTokenCheckpoint(ctx, t, store, currentID, "checkpoint-token-cost-proxy-current", &agent.TokenUsage{ InputTokens: 50_000, CacheCreationTokens: 30_000, OutputTokens: 30_000, APICallCount: 4, })

cmd := newCheckpointGroupCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"tokens", "c0a222", "--compare", "c0a111", "--json"})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

var result checkpointTokensReport if err := json.Unmarshal(stdout.Bytes(), &result); err != nil { t.Fatalf("expected valid JSON, got parse error: %v\noutput: %s", err, stdout.String()) } if result.Comparison == nil { t.Fatalf("expected comparison, got nil") } if result.Comparison.Status != checkpointComparisonStatusObservedReduction { t.Fatalf("expected observed reduction, got %q", result.Comparison.Status) } checks := []string{ "Cost-proxy pressure increased", "cache write", "output", } for _, check := range checks { if !strings.Contains(result.Comparison.Qualification, check) { t.Fatalf("expected %q in qualification, got %q", check, result.Comparison.Qualification) } } }

func TestCheckpointTokensCmd_ComparisonNoChange(t *testing.T) { repo, _ := runExplainAutoTestRepo(t) ctx := context.Background() store := checkpoint.NewGitStore(repo, checkpoint.DefaultV1Refs()) baselineID := id.MustCheckpointID("111aaa222bbb") currentID := id.MustCheckpointID("222bbb333ccc")

writeCommittedTokenCheckpoint(ctx, t, store, baselineID, "checkpoint-token-no-change-baseline", &agent.TokenUsage{ InputTokens: 100, OutputTokens: 100, APICallCount: 2, }) writeCommittedTokenCheckpoint(ctx, t, store, currentID, "checkpoint-token-no-change-current", &agent.TokenUsage{ InputTokens: 100, OutputTokens: 100, APICallCount: 2, })

cmd := newCheckpointGroupCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"tokens", "222bbb", "--compare", "111aaa"})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

out := stdout.String() checks := []string{ "Total tokens: unchanged (200 -> 200)", "Cache/context replay: unchanged (0 -> 0)", "API calls: unchanged (2 -> 2)", "Observed total token use was unchanged for this checkpoint comparison.", "Quality still depends on the task outcome", } for _, check := range checks { if !strings.Contains(out, check) { t.Errorf("expected %q in output, got:\n%s", check, out) } } }

func TestBuildCheckpointMetricDeltaClampsChangeOverflow(t *testing.T) { t.Parallel()

maxInt := int(^uint(0) >> 1) minInt := -maxInt - 1

up := buildCheckpointMetricDelta(minInt, maxInt) if up.Change != maxInt { t.Fatalf("upward overflow change = %d, want %d", up.Change, maxInt) } if up.Direction != checkpointDeltaDirectionUp { t.Fatalf("upward overflow direction = %q, want up", up.Direction) }

down := buildCheckpointMetricDelta(maxInt, minInt) if down.Change != minInt { t.Fatalf("downward overflow change = %d, want %d", down.Change, minInt) } if down.Direction != checkpointDeltaDirectionDown { t.Fatalf("downward overflow direction = %q, want down", down.Direction) } }

func TestSaturatingIntSubHandlesMinIntSubtrahend(t *testing.T) { t.Parallel()

maxInt := int(^uint(0) >> 1) minInt := -maxInt - 1

tests := []struct { name string a int want int }{ { name: "clamps non-negative minuend", a: 0, want: maxInt, }, { name: "keeps max exact result", a: -1, want: maxInt, }, { name: "keeps representable result", a: -2, want: maxInt - 1, }, { name: "keeps zero exact result", a: minInt, want: 0, }, }

for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel()

if got := saturatingIntSub(tt.a, minInt); got != tt.want { t.Fatalf("saturatingIntSub(%d, minInt) = %d, want %d", tt.a, got, tt.want) } }) } }

func TestCheckpointTokensCmd_ComparisonUnavailableWhenBaselineTokenDataMissing(t *testing.T) { repo, _ := runExplainAutoTestRepo(t) ctx := context.Background() store := checkpoint.NewGitStore(repo, checkpoint.DefaultV1Refs()) baselineID := id.MustCheckpointID("333ccc444ddd") currentID := id.MustCheckpointID("444ddd555eee")

writeCommittedTokenCheckpoint(ctx, t, store, baselineID, "checkpoint-token-missing-baseline", nil) writeCommittedTokenCheckpoint(ctx, t, store, currentID, "checkpoint-token-current-with-data", &agent.TokenUsage{ InputTokens: 100, OutputTokens: 50, APICallCount: 1, })

cmd := newCheckpointGroupCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"tokens", "444ddd", "--compare", "333ccc"})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

out := stdout.String() checks := []string{ "Comparison", "Baseline: 333ccc444ddd", "Qualification", "Comparison unavailable because token usage is missing for one checkpoint.", } for _, check := range checks { if !strings.Contains(out, check) { t.Errorf("expected %q in output, got:\n%s", check, out) } } if strings.Contains(out, "Total tokens:") { t.Fatalf("expected unavailable comparison to omit metric deltas, got:\n%s", out) } }

func TestCheckpointTokensCmd_JSONComparisonUnavailableWhenCurrentTokenDataMissing(t *testing.T) { repo, _ := runExplainAutoTestRepo(t) ctx := context.Background() store := checkpoint.NewGitStore(repo, checkpoint.DefaultV1Refs()) baselineID := id.MustCheckpointID("555eee666fff") currentID := id.MustCheckpointID("666fff777aaa")

writeCommittedTokenCheckpoint(ctx, t, store, baselineID, "checkpoint-token-baseline-with-data", &agent.TokenUsage{ InputTokens: 100, OutputTokens: 50, APICallCount: 1, }) writeCommittedTokenCheckpoint(ctx, t, store, currentID, "checkpoint-token-missing-current", nil)

cmd := newCheckpointGroupCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"tokens", "666fff", "--compare", "555eee", "--json"})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

var result checkpointTokensReport if err := json.Unmarshal(stdout.Bytes(), &result); err != nil { t.Fatalf("expected valid JSON, got parse error: %v\noutput: %s", err, stdout.String()) } if result.Comparison == nil { t.Fatalf("expected comparison, got nil") } if result.Comparison.Status != "unavailable" { t.Fatalf("expected unavailable status, got %q", result.Comparison.Status) } if result.Comparison.Total != nil { t.Fatalf("expected no total delta when current token data is missing, got %+v", result.Comparison.Total) } if len(result.Comparison.Limitations) == 0 { t.Fatalf("expected comparison limitation, got %+v", result.Comparison) } }

func TestCheckpointTokensCmd_ComparisonUsesMultiSessionAggregates(t *testing.T) { repo, _ := runExplainAutoTestRepo(t) ctx := context.Background() store := checkpoint.NewGitStore(repo, checkpoint.DefaultV1Refs()) baselineID := id.MustCheckpointID("777aaa888bbb") currentID := id.MustCheckpointID("888bbb999ccc")

writeCommittedTokenCheckpoint(ctx, t, store, baselineID, "checkpoint-token-baseline-one", &agent.TokenUsage{ InputTokens: 1_000, APICallCount: 1, }) writeCommittedTokenCheckpoint(ctx, t, store, baselineID, "checkpoint-token-baseline-two", &agent.TokenUsage{ OutputTokens: 1_000, APICallCount: 1, }) writeCommittedTokenCheckpoint(ctx, t, store, currentID, "checkpoint-token-current-one", &agent.TokenUsage{ InputTokens: 500, APICallCount: 1, }) writeCommittedTokenCheckpoint(ctx, t, store, currentID, "checkpoint-token-current-two", &agent.TokenUsage{ OutputTokens: 500, APICallCount: 1, })

cmd := newCheckpointGroupCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"tokens", "888bbb", "--compare", "777aaa"})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

out := stdout.String() checks := []string{ "Sessions: 2", "Total: 1k tokens", "Baseline: 777aaa888bbb", "Total tokens: down 50% (2k -> 1k)", "API calls: unchanged (2 -> 2)", } for _, check := range checks { if !strings.Contains(out, check) { t.Errorf("expected %q in output, got:\n%s", check, out) } } }

func TestCheckpointTokensCmd_ComparisonOmitsPercentWhenBaselineMetricIsZero(t *testing.T) { repo, _ := runExplainAutoTestRepo(t) ctx := context.Background() store := checkpoint.NewGitStore(repo, checkpoint.DefaultV1Refs()) baselineID := id.MustCheckpointID("999ccc000aaa") currentID := id.MustCheckpointID("000aaa111bbb")

writeCommittedTokenCheckpoint(ctx, t, store, baselineID, "checkpoint-token-zero-api-baseline", &agent.TokenUsage{ InputTokens: 100, }) writeCommittedTokenCheckpoint(ctx, t, store, currentID, "checkpoint-token-zero-api-current", &agent.TokenUsage{ InputTokens: 100, APICallCount: 3, })

cmd := newCheckpointGroupCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"tokens", "000aaa", "--compare", "999ccc"})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

out := stdout.String() checks := []string{ "Total tokens: unchanged (100 -> 100)", "API calls: up (0 -> 3)", } for _, check := range checks { if !strings.Contains(out, check) { t.Errorf("expected %q in output, got:\n%s", check, out) } } if strings.Contains(out, "API calls: up ") && strings.Contains(out, "API calls: up %") { t.Fatalf("expected zero-baseline API delta to omit percent, got:\n%s", out) } }

func writeCommittedTokenCheckpoint(ctx context.Context, t *testing.T, store *checkpoint.GitStore, cpID id.CheckpointID, sessionID string, usage *agent.TokenUsage) { t.Helper()

if err := store.WriteCommitted(ctx, checkpoint.WriteCommittedOptions{ CheckpointID: cpID, SessionID: sessionID, Strategy: strategy.StrategyNameManualCommit, Branch: "tokens-compare", Agent: testAgentClaude, Transcript: redact.AlreadyRedacted([]byte({"type":"user","message":{"content":[{"type":"text","text":"compare"}]}} + "\n")), AuthorName: "Test", AuthorEmail: "test@example.com", TokenUsage: usage, }); err != nil { t.Fatalf("WriteCommitted(%s) error = %v", cpID, err) } }

func TestInfoCmd_EndedSession(t *testing.T) { setupStopTestRepo(t)


Mcmd/entire/cli/sessions\_test.go+1950/-8

108 unmodified lines

109 110 111 112 113 112 113 114 115 116 117 118

108 unmodified lines

if tu == nil { return 0 } total := tu.InputTokens + tu.CacheCreationTokens + tu.CacheReadTokens + tu.OutputTokens total += totalTokens(tu.SubagentTokens) total := saturatingIntAdd(tu.InputTokens, tu.CacheCreationTokens) total = saturatingIntAdd(total, tu.CacheReadTokens) total = saturatingIntAdd(total, tu.OutputTokens) total = saturatingIntAdd(total, totalTokens(tu.SubagentTokens)) return total }


Mcmd/entire/cli/status\_style.go+4/-2

890 unmodified lines

891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911

890 unmodified lines

} }

func TestTotalTokens_SaturatesOverflow(t *testing.T) { t.Parallel()

maxInt := int(^uint(0) >> 1) tu := &agent.TokenUsage{ InputTokens: maxInt, SubagentTokens: &agent.TokenUsage{ OutputTokens: 1, }, } if got := totalTokens(tu); got != maxInt { t.Errorf("totalTokens() = %d, want %d", got, maxInt) } }

func TestActiveTimeDisplay(t *testing.T) { t.Parallel()


Mcmd/entire/cli/status\_test.go+15

137 unmodified lines

138 139 140 141 142 143 144 145 146 147 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 149 150 151 152 170 171 172 173 174 175 176 177

137 unmodified lines

}

// Scope to current worktree to prevent cross-worktree pollution. worktreePath, wpErr := paths.WorktreeRoot(ctx) if wpErr == nil && worktreePath != "" { var filtered []*SessionState for _, s := range states { if s.WorktreePath == worktreePath { filtered = append(filtered, s) } if filtered := sessionStatesForCurrentWorktree(ctx, states); len(filtered) > 0 { states = filtered // If no sessions match the worktree, fall back to all sessions. }

return mostRecentSessionID(states) }

// FindMostRecentSessionInCurrentWorktree returns the most recently interacted // session from the current worktree only. Unlike FindMostRecentSession, it does // not fall back to sessions from other worktrees. func FindMostRecentSessionInCurrentWorktree(ctx context.Context) string { states, err := ListSessionStates(ctx) if err != nil || len(states) == 0 { return "" } return mostRecentSessionID(sessionStatesForCurrentWorktree(ctx, states)) }

func sessionStatesForCurrentWorktree(ctx context.Context, states []*SessionState) []*SessionState { worktreePath, err := paths.WorktreeRoot(ctx) if err != nil || worktreePath == "" { return nil } filtered := make([]*SessionState, 0, len(states)) for _, s := range states { if s.WorktreePath == worktreePath { filtered = append(filtered, s) } if len(filtered) > 0 { states = filtered } // If no sessions match the worktree, fall back to all sessions } return filtered }

func mostRecentSessionID(states []*SessionState) string { var best *SessionState for _, s := range states { if s.LastInteractionTime == nil {


Mcmd/entire/cli/strategy/session\_state.go+31/-11

package cli

import (
    "context"
    "encoding/json"
    "errors"
    "fmt"
    "io"

type tokensProfileReport struct {
    Source                   string                        `json:"source"`
    UsageScope               string                        `json:"usage_scope"`
    CheckpointsAvailable     int                           `json:"checkpoints_available"`
    CheckpointsAnalyzed      int                           `json:"checkpoints_analyzed"`
    CheckpointsWithTokenData int                           `json:"checkpoints_with_token_data"`
    MissingTokenData         int                           `json:"missing_token_data"`
    MetadataReadWarnings     int                           `json:"metadata_read_warnings,omitempty"`
    Tokens                   *sessionTokensUsage           `json:"tokens,omitempty"`
    Signals                  []tokensProfileSignal         `json:"signals,omitempty"`
    Recommendations          []sessionTokensRecommendation `json:"recommendations,omitempty"`
    Limitations              []string                      `json:"limitations,omitempty"`
}

type tokensProfileSignal struct {
    ID            string   `json:"id"`
    Label         string   `json:"label"`
    Count         int      `json:"count"`
    Percent       int      `json:"percent"`
    CheckpointIDs []string `json:"checkpoint_ids,omitempty"`
}

type tokensProfileSignalDefinition struct {
    id    string
    label string
}

var tokensProfileSignalDefinitions = []tokensProfileSignalDefinition{
    {id: "context-replay-hotspot", label: "Cache/context replay hotspot"},
    {id: "api-call-amplification", label: "API call amplification"},
    {id: "subagent-heavy", label: "Subagent-heavy sessions"},
    {id: "missing-token-data", label: "Missing token data"},
}

const tokensProfileUsageScopeCheckpointObserved = "checkpoint_observed"

func newTokensGroupCmd() *cobra.Command {
    cmd := &cobra.Command{
        Use:    "tokens",
        Short:  "Analyze token usage across sessions and checkpoints",
        Hidden: true,
        Long: `Analyze token usage across sessions and checkpoints.

Commands:
  profile  Aggregate token usage across committed checkpoints

Examples:
  entire tokens profile
  entire tokens profile --json`,
        RunE: func(cmd *cobra.Command, _ []string) error {
            return cmd.Help()
        },
    }

cmd.AddCommand(newTokensProfileCmd())
    return cmd
}

func newTokensProfileCmd() *cobra.Command {
    var jsonFlag bool
    var limitFlag int
    var allFlag bool

cmd := &cobra.Command{
        Use:   "profile",
        Short: "Aggregate token usage and recommendations across checkpoint history",
        Long: `Aggregate token usage and recommendations across committed checkpoint history.

The profile reads committed checkpoint metadata only. It does not inspect
transcripts or source files, so it is deterministic and avoids adding token
cost while diagnosing token usage. By default it scans the latest 50 committed
checkpoints; use --limit or --all to change the scope.`,
        Args: cobra.NoArgs,
        RunE: func(cmd *cobra.Command, _ []string) error {
            limit := limitFlag
            if allFlag {
                limit = 0
            } else if limit <= 0 {
                return errors.New("--limit must be positive unless --all is used")
            }
            return runTokensProfile(cmd.Context(), cmd, jsonFlag, limit)
        },
    }

cmd.Flags().BoolVar(&jsonFlag, "json", false, "Output as JSON")
    cmd.Flags().IntVar(&limitFlag, "limit", 50, "Maximum committed checkpoints to analyze")
    cmd.Flags().BoolVar(&allFlag, "all", false, "Analyze all committed checkpoints")
    cmd.MarkFlagsMutuallyExclusive("limit", "all")
    return cmd
}

func runTokensProfile(ctx context.Context, cmd *cobra.Command, jsonOutput bool, limit int) error {
    repo, err := openRepository(ctx)
    if err != nil {
        cmd.SilenceUsage = true
        fmt.Fprintln(cmd.ErrOrStderr(), "Not a git repository.")
        return NewSilentError(err)
    }
    defer repo.Close()

store := checkpoint.NewGitStore(repo, checkpoint.ResolveCommittedRefs(ctx))
    store.SetBlobFetcher(FetchBlobsByHash)
    infos, err := store.ListCommitted(ctx)
    if err != nil {
        return fmt.Errorf("failed to list checkpoints: %w", err)
    }

report, err := buildTokensProfileReport(ctx, store, infos, limit)
    if err != nil {
        return err
    }

if jsonOutput {
        return writeTokensProfileJSON(cmd.OutOrStdout(), report)
    }
    writeTokensProfileText(cmd.OutOrStdout(), report)
    return nil
}

func buildTokensProfileReport(ctx context.Context, store *checkpoint.GitStore, infos []checkpoint.CommittedInfo, limit int) (tokensProfileReport, error) {
    checkpointsAvailable := len(infos)
    infos = limitTokensProfileCheckpoints(infos, limit)
    report := tokensProfileReport{
        Source:               "committed_checkpoints",
        UsageScope:           tokensProfileUsageScopeCheckpointObserved,
        CheckpointsAvailable: checkpointsAvailable,
        CheckpointsAnalyzed:  len(infos),
    }
    signals := make(map[string]*tokensProfileSignal, len(tokensProfileSignalDefinitions))
    var aggregate *agent.TokenUsage

for _, info := range infos {
        if err := ctx.Err(); err != nil {
            return tokensProfileReport{}, err //nolint:wrapcheck // Propagating context cancellation.
        }

summary, err := store.ReadCommitted(ctx, info.CheckpointID)
        if err != nil {
            return tokensProfileReport{}, fmt.Errorf("failed to read checkpoint %s: %w", info.CheckpointID, err)
        }
        if summary == nil {
            report.MissingTokenData++
            addTokensProfileSignal(signals, "missing-token-data", info.CheckpointID, report.CheckpointsAnalyzed)
            continue
        }

usage, metadataReadWarning, err := tokensProfileCheckpointUsage(ctx, store, info.CheckpointID, summary)
        if err != nil {
            return tokensProfileReport{}, err
        }
        if metadataReadWarning {
            report.MetadataReadWarnings++
        }
        tokens := buildSessionTokensUsage(usage)
        if tokens == nil {
            report.MissingTokenData++
            addTokensProfileSignal(signals, "missing-token-data", info.CheckpointID, report.CheckpointsAnalyzed)
            continue
        }

report.CheckpointsWithTokenData++
        aggregate = addCheckpointTokenUsage(aggregate, usage)
        addTokensProfileTokenSignals(signals, info.CheckpointID, tokens, report.CheckpointsAnalyzed)
    }

report.Tokens = buildSessionTokensUsage(aggregate)
    report.Signals = orderedTokensProfileSignals(signals)
    report.Recommendations = tokensProfileRecommendations(report)
    report.Limitations = tokensProfileLimitations(report)
    return report, nil
}

func limitTokensProfileCheckpoints(infos []checkpoint.CommittedInfo, limit int) []checkpoint.CommittedInfo {
    if limit <= 0 || len(infos) <= limit {
        return infos
    }
    return infos[:limit]
}

func tokensProfileCheckpointUsage(ctx context.Context, store *checkpoint.GitStore, checkpointID id.CheckpointID, summary *checkpoint.CheckpointSummary) (*agent.TokenUsage, bool, error) {
    if summary == nil {
        return nil, false, nil
    }

metas := make([]*checkpoint.CommittedMetadata, 0, len(summary.Sessions))
    metadataReadWarning := false
    for i := range len(summary.Sessions) {
        meta, err := store.ReadSessionMetadata(ctx, checkpointID, i)
        if err != nil {
            if ctxErr := ctx.Err(); ctxErr != nil {
                return nil, false, ctxErr //nolint:wrapcheck // Propagating context cancellation.
            }
            metadataReadWarning = true
            continue
        }
        metas = append(metas, meta)
    }
    return checkpointTokenUsage(summary, metas, metadataReadWarning), metadataReadWarning, nil
}

func addTokensProfileTokenSignals(signals map[string]*tokensProfileSignal, checkpointID id.CheckpointID, tokens *sessionTokensUsage, denominator int) {
    if tokens == nil {
        return
    }
    topLevelTotal := topLevelSessionTokenTotal(tokens)
    if topLevelTotal > 0 && tokenPercent(tokens.CacheRead, topLevelTotal) >= recommendationHighCacheReadPercent {
        addTokensProfileSignal(signals, "context-replay-hotspot", checkpointID, denominator)
    }
    if tokens.APICalls >= 20 {
        addTokensProfileSignal(signals, "api-call-amplification", checkpointID, denominator)
    }
    if tokenShareAtLeastOneTenth(tokens.SubagentTotal, tokens.Total) {
        addTokensProfileSignal(signals, "subagent-heavy", checkpointID, denominator)
    }
}

func addTokensProfileSignal(signals map[string]*tokensProfileSignal, signalID string, checkpointID id.CheckpointID, denominator int) {
    signal := signals[signalID]
    if signal == nil {
        definition := tokensProfileSignalDefinitionFor(signalID)
        signal = &tokensProfileSignal{
            ID:    definition.id,
            Label: definition.label,
        }
        signals[signalID] = signal
    }
    signal.Count++
    if denominator > 0 {
        signal.Percent = roundedPercent(signal.Count, denominator)
    }
    if checkpointID != "" {
        signal.CheckpointIDs = append(signal.CheckpointIDs, checkpointID.String())
    }
}

func tokensProfileSignalDefinitionFor(signalID string) tokensProfileSignalDefinition {
    for _, definition := range tokensProfileSignalDefinitions {
        if definition.id == signalID {
            return definition
        }
    }
    return tokensProfileSignalDefinition{id: signalID, label: signalID}
}

func orderedTokensProfileSignals(signals map[string]*tokensProfileSignal) []tokensProfileSignal {
    ordered := make([]tokensProfileSignal, 0, len(signals))
    for _, definition := range tokensProfileSignalDefinitions {
        if signal := signals[definition.id]; signal != nil {
            ordered = append(ordered, *signal)
        }
    }
    return ordered
}

func tokensProfileRecommendations(report tokensProfileReport) []sessionTokensRecommendation {
    var recs []sessionTokensRecommendation

if report.CheckpointsAnalyzed == 0 {
        return []sessionTokensRecommendation{{
            ID:       "no-checkpoints",
            Severity: "low",
            Message:  "Create checkpoints first; token profiling needs committed checkpoint metadata to identify patterns.",
            Signals:  []string{"empty_checkpoint_history"},
        }}
    }

if tokensProfileSignalCount(report.Signals, "context-replay-hotspot") > 0 ||
        tokensProfileSignalCount(report.Signals, "api-call-amplification") > 0 {
        recs = append(recs, sessionTokensRecommendation{
            ID:       "search-before-reinvestigation",
            Severity: "high",
            Message:  "Use `entire search` for prior decisions/checkpoints before broad re-investigation.",
            Signals:  []string{"cache_read_tokens", "api_call_count"},
        })
    }
    if tokensProfileSignalCount(report.Signals, "api-call-amplification") > 0 {
        recs = append(recs, sessionTokensRecommendation{
            ID:       "batch-diagnostics",
            Severity: "medium",
            Message:  "Batch diagnostic reads around one narrowed hypothesis when API call amplification repeats.",
            Signals:  []string{"api_call_count"},
        })
    }
    if tokensProfileSignalCount(report.Signals, "context-replay-hotspot") > 0 {
        recs = append(recs, sessionTokensRecommendation{
            ID:       "preserve-then-compact",
            Severity: "medium",
            Message:  "Summarize useful findings before continuing large-context work; compact or restart only after preserving relevant context.",
            Signals:  []string{"cache_read_tokens"},
        })
    }
    if tokensProfileSignalCount(report.Signals, "subagent-heavy") > 0 {
        recs = append(recs, sessionTokensRecommendation{
            ID:       "scope-subagents",
            Severity: "medium",
            Message:  "Scope subagent tasks tightly with a narrow objective and expected output.",
            Signals:  []string{"subagent_tokens"},
        })
    }
    if report.MissingTokenData > 0 {
        recs = append(recs, sessionTokensRecommendation{
            ID:       "improve-token-coverage",
            Severity: "low",
            Message:  "Increase token coverage by using agents and checkpoints that report token usage.",
            Signals:  []string{"missing_token_usage"},
        })
    }

if len(recs) == 0 {
        recs = append(recs, sessionTokensRecommendation{
            ID:       "no-repeated-hotspots",
            Severity: "low",
            Message:  "No repeated token hotspots were visible in committed checkpoint metadata.",
            Signals:  []string{"checkpoint_token_metadata"},
        })
    }
    return recs
}

func tokensProfileSignalCount(signals []tokensProfileSignal, signalID string) int {
    for _, signal := range signals {
        if signal.ID == signalID {
            return signal.Count
        }
    }
    return 0
}

func tokensProfileLimitations(report tokensProfileReport) []string {
    var limitations []string
    if report.CheckpointsAvailable > report.CheckpointsAnalyzed {
        limitations = append(limitations, fmt.Sprintf("Limited to latest %d of %d committed checkpoints; use --limit or --all to change scope.", report.CheckpointsAnalyzed, report.CheckpointsAvailable))
    }
    if report.CheckpointsAnalyzed == 0 {
        limitations = append(limitations, "No committed checkpoints found.")
    }
    if report.MissingTokenData > 0 {
        limitations = append(limitations, fmt.Sprintf("%d checkpoint%s did not include token usage.", report.MissingTokenData, tokenPluralSuffix(report.MissingTokenData)))
    }
    if report.MetadataReadWarnings > 0 {
        limitations = append(limitations, fmt.Sprintf("%d checkpoint%s had incomplete session metadata; profile used root token summaries or readable sessions where available.", report.MetadataReadWarnings, tokenPluralSuffix(report.MetadataReadWarnings)))
    }
    if report.Tokens != nil {
        limitations = append(limitations, "Token totals are summed from analyzed checkpoints and may include overlapping checkpoint history; treat them as checkpoint-observed volume, not guaranteed unique session spend.")
    }
    if report.CheckpointsAnalyzed > 0 {
        limitations = append(limitations, "Tool-level search/read spend is not captured yet; this profile infers patterns from token totals, cache/context replay, API call counts, and subagent totals.")
    }
    return limitations
}

func writeTokensProfileJSON(w io.Writer, report tokensProfileReport) error {
    enc := json.NewEncoder(w)
    enc.SetIndent("", "  ")
    if err := enc.Encode(report); err != nil {
        return fmt.Errorf("failed to encode token profile report: %w", err)
    }
    return nil
}

func writeTokensProfileText(w io.Writer, report tokensProfileReport) {
    fmt.Fprintln(w, "Token profile")
    fmt.Fprintln(w)
    fmt.Fprintf(w, "Source:               %s\n", report.Source)
    fmt.Fprintf(w, "Checkpoints available: %d\n", report.CheckpointsAvailable)
    fmt.Fprintf(w, "Checkpoints analyzed: %d\n", report.CheckpointsAnalyzed)
    fmt.Fprintf(w, "With token data:      %d\n", report.CheckpointsWithTokenData)
    fmt.Fprintf(w, "Missing token data:   %d\n", report.MissingTokenData)
    if report.MetadataReadWarnings > 0 {
        fmt.Fprintf(w, "Metadata warnings:    %d\n", report.MetadataReadWarnings)
    }

writeTokenUsageSectionWithTitle(w, "Checkpoint-observed token usage", report.Tokens)
    writeTokensProfileSignals(w, report.Signals)
    if len(report.Recommendations) > 0 {
        writeTokenRecommendations(w, report.Recommendations)
    }
    writeTokenLimitations(w, report.Limitations)
}

func writeTokensProfileSignals(w io.Writer, signals []tokensProfileSignal) {
    if len(signals) == 0 {
        return
    }

fmt.Fprintln(w)
    fmt.Fprintln(w, "Repeated signals")
    for _, signal := range signals {
        fmt.Fprintf(w, "- %s: %d checkpoint%s", signal.Label, signal.Count, tokenPluralSuffix(signal.Count))
        if signal.Percent > 0 {
            fmt.Fprintf(w, " (%d%%)", signal.Percent)
        }
        fmt.Fprintln(w)
    }
}

Acmd/entire/cli/tokens_profile.go+410

package cli

import ( "bytes" "context" "encoding/json" "strings" "testing"

"github.com/entireio/cli/cmd/entire/cli/agent" "github.com/entireio/cli/cmd/entire/cli/checkpoint" "github.com/entireio/cli/cmd/entire/cli/checkpoint/id" "github.com/entireio/cli/cmd/entire/cli/strategy" "github.com/entireio/cli/redact" )

func TestAddTokensProfileTokenSignalsSubagentHeavyAvoidsOverflow(t *testing.T) { t.Parallel()

maxInt := int(^uint(0) >> 1) signals := map[string]*tokensProfileSignal{} addTokensProfileTokenSignals(signals, id.MustCheckpointID("999aaa000001"), &sessionTokensUsage{ Total: maxInt, SubagentTotal: maxInt, }, 1)

if signals["subagent-heavy"] == nil { t.Fatalf("expected subagent-heavy signal, got %+v", signals) } }

func TestAddTokensProfileTokenSignalsCacheReplayUsesTopLevelTokenTotal(t *testing.T) { t.Parallel()

signals := map[string]*tokensProfileSignal{} addTokensProfileTokenSignals(signals, id.MustCheckpointID("999aaa000002"), &sessionTokensUsage{ Total: 10000, Input: 100, CacheRead: 800, CacheWrite: 50, Output: 50, APICalls: 20, SubagentTotal: 9000, }, 1)

if signals["context-replay-hotspot"] == nil { t.Fatalf("expected context-replay-hotspot signal, got %+v", signals) } }

func TestTokensProfileCmd_TextOutputAggregatesCommittedCheckpoints(t *testing.T) { repo, _ := runExplainAutoTestRepo(t) ctx := context.Background() store := checkpoint.NewGitStore(repo, checkpoint.DefaultV1Refs())

writeProfileTokenCheckpoint(ctx, t, store, "100aaa000001", "profile-cache-hotspot", &agent.TokenUsage{ InputTokens: 100, CacheCreationTokens: 100, CacheReadTokens: 800, APICallCount: 5, }) writeProfileTokenCheckpoint(ctx, t, store, "100aaa000002", "profile-api-heavy", &agent.TokenUsage{ InputTokens: 400, OutputTokens: 100, APICallCount: 25, }) writeProfileTokenCheckpoint(ctx, t, store, "100aaa000003", "profile-subagent-heavy", &agent.TokenUsage{ InputTokens: 500, OutputTokens: 500, APICallCount: 3, SubagentTokens: &agent.TokenUsage{ InputTokens: 1_000, }, }) writeProfileTokenCheckpoint(ctx, t, store, "100aaa000004", "profile-missing", nil)

cmd := newTokensGroupCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"profile"})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

out := stdout.String() checks := []string{ "Token profile", "Checkpoints analyzed: 4", "With token data: 3", "Missing token data: 1", "Checkpoint-observed token usage", "Total: 3.5k tokens", "Cache read: 800", "API calls: 33", "Repeated signals", "Cache/context replay hotspot: 1 checkpoint", "API call amplification: 1 checkpoint", "Subagent-heavy sessions: 1 checkpoint", "Missing token data: 1 checkpoint", "Recommendations", "Use entire search for prior decisions/checkpoints before broad re-investigation.", "Token totals are summed from analyzed checkpoints and may include overlapping checkpoint history", "Tool-level search/read spend is not captured yet", } for _, check := range checks { if !strings.Contains(out, check) { t.Errorf("expected %q in output, got:\n%s", check, out) } }

tokenUsageIndex := strings.Index(out, "Checkpoint-observed token usage") recommendationsIndex := strings.Index(out, "Recommendations") if tokenUsageIndex == -1 || recommendationsIndex == -1 { t.Fatalf("expected token usage and recommendations sections, got:\n%s", out) } if tokenUsageIndex > recommendationsIndex { t.Fatalf("expected token usage before recommendations, got:\n%s", out) } }

func TestTokensProfileCmd_JSONOutput(t *testing.T) { repo, _ := runExplainAutoTestRepo(t) ctx := context.Background() store := checkpoint.NewGitStore(repo, checkpoint.DefaultV1Refs())

writeProfileTokenCheckpoint(ctx, t, store, "200bbb000001", "profile-json-cache", &agent.TokenUsage{ InputTokens: 100, CacheReadTokens: 900, APICallCount: 2, }) writeProfileTokenCheckpoint(ctx, t, store, "200bbb000002", "profile-json-api", &agent.TokenUsage{ InputTokens: 200, OutputTokens: 100, APICallCount: 22, })

cmd := newTokensGroupCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"profile", "--json"})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

var result tokensProfileReport if err := json.Unmarshal(stdout.Bytes(), &result); err != nil { t.Fatalf("expected valid JSON, got parse error: %v\noutput: %s", err, stdout.String()) } var raw map[string]interface{} if err := json.Unmarshal(stdout.Bytes(), &raw); err != nil { t.Fatalf("expected valid JSON object, got parse error: %v\noutput: %s", err, stdout.String()) } if raw["usage_scope"] != "checkpoint_observed" { t.Fatalf("usage_scope = %v, want checkpoint_observed", raw["usage_scope"]) } if result.CheckpointsAnalyzed != 2 { t.Fatalf("checkpoints_analyzed = %d, want 2", result.CheckpointsAnalyzed) } if result.CheckpointsWithTokenData != 2 { t.Fatalf("checkpoints_with_token_data = %d, want 2", result.CheckpointsWithTokenData) } if result.Tokens == nil || result.Tokens.Total != 1300 { t.Fatalf("unexpected token total: %+v", result.Tokens) } if got := signalCount(result.Signals, "context-replay-hotspot"); got != 1 { t.Fatalf("context-replay-hotspot signal count = %d, want 1", got) } if got := signalCount(result.Signals, "api-call-amplification"); got != 1 { t.Fatalf("api-call-amplification signal count = %d, want 1", got) } if len(result.Recommendations) == 0 { t.Fatalf("expected recommendations, got none") } }

func TestTokensProfileCmd_JSONOutputReportsAPICallOnlyCheckpoints(t *testing.T) { repo, _ := runExplainAutoTestRepo(t) ctx := context.Background() store := checkpoint.NewGitStore(repo, checkpoint.DefaultV1Refs())

writeProfileTokenCheckpoint(ctx, t, store, "250bbb000001", "profile-json-api-only", &agent.TokenUsage{ APICallCount: 25, })

cmd := newTokensGroupCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"profile", "--json"})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

var result tokensProfileReport if err := json.Unmarshal(stdout.Bytes(), &result); err != nil { t.Fatalf("expected valid JSON, got parse error: %v\noutput: %s", err, stdout.String()) } if result.CheckpointsWithTokenData != 1 { t.Fatalf("checkpoints_with_token_data = %d, want 1", result.CheckpointsWithTokenData) } if result.MissingTokenData != 0 { t.Fatalf("missing_token_data = %d, want 0", result.MissingTokenData) } if result.Tokens == nil || result.Tokens.Total != 0 || result.Tokens.APICalls != 25 { t.Fatalf("unexpected token usage: %+v", result.Tokens) } if got := signalCount(result.Signals, "api-call-amplification"); got != 1 { t.Fatalf("api-call-amplification signal count = %d, want 1", got) } }

func TestTokensProfileCmd_LimitScopesAnalyzedCheckpoints(t *testing.T) { repo, _ := runExplainAutoTestRepo(t) ctx := context.Background() store := checkpoint.NewGitStore(repo, checkpoint.DefaultV1Refs())

writeProfileTokenCheckpoint(ctx, t, store, "300ccc000001", "profile-limit-one", &agent.TokenUsage{ InputTokens: 100, OutputTokens: 100, APICallCount: 1, }) writeProfileTokenCheckpoint(ctx, t, store, "300ccc000002", "profile-limit-two", &agent.TokenUsage{ InputTokens: 100, OutputTokens: 100, APICallCount: 1, }) writeProfileTokenCheckpoint(ctx, t, store, "300ccc000003", "profile-limit-three", &agent.TokenUsage{ InputTokens: 100, OutputTokens: 100, APICallCount: 1, })

cmd := newTokensGroupCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"profile", "--limit", "2"})

if err := cmd.ExecuteContext(ctx); err != nil { t.Fatalf("expected no error, got: %v", err) }

out := stdout.String() checks := []string{ "Checkpoints available: 3", "Checkpoints analyzed: 2", "Total: 400 tokens", "Limited to latest 2 of 3 committed checkpoints", } for _, check := range checks { if !strings.Contains(out, check) { t.Errorf("expected %q in output, got:\n%s", check, out) } } }

func TestTokensProfileCmd_LimitAndAllAreMutuallyExclusive(t *testing.T) { runExplainAutoTestRepo(t)

cmd := newTokensGroupCmd() cmd.SetArgs([]string{"profile", "--limit", "2", "--all"})

err := cmd.ExecuteContext(context.Background()) if err == nil { t.Fatal("expected error for --limit with --all") } if !strings.Contains(err.Error(), "limit") || !strings.Contains(err.Error(), "all") { t.Fatalf("expected error to mention limit and all, got: %v", err) } }

func TestTokensProfileCmd_EmptyHistory(t *testing.T) { runExplainAutoTestRepo(t)

cmd := newTokensGroupCmd() var stdout bytes.Buffer cmd.SetOut(&stdout) cmd.SetArgs([]string{"profile"})

if err := cmd.ExecuteContext(context.Background()); err != nil { t.Fatalf("expected no error, got: %v", err) }

out := stdout.String() checks := []string{ "Token profile", "Checkpoints analyzed: 0", "Token data: unavailable", "No committed checkpoints found.", } for _, check := range checks { if !strings.Contains(out, check) { t.Errorf("expected %q in output, got:\n%s", check, out) } } }

func signalCount(signals []tokensProfileSignal, id string) int { for _, signal := range signals { if signal.ID == id { return signal.Count } } return 0 }

func writeProfileTokenCheckpoint(ctx context.Context, t *testing.T, store *checkpoint.GitStore, checkpointID string, sessionID string, usage *agent.TokenUsage) { t.Helper()

if err := store.WriteCommitted(ctx, checkpoint.WriteCommittedOptions{ CheckpointID: id.MustCheckpointID(checkpointID), SessionID: sessionID, Strategy: strategy.StrategyNameManualCommit, Branch: "tokens-profile", Agent: testAgentClaude, Transcript: redact.AlreadyRedacted([]byte({"type":"user","message":{"content":[{"type":"text","text":"profile"}]}} + "\n")), AuthorName: "Test", AuthorEmail: "test@example.com", TokenUsage: usage, }); err != nil { t.Fatalf("WriteCommitted(%s) error = %v", checkpointID, err) } }


Acmd/entire/cli/tokens\_profile\_test.go+324

1

test 1


Dt1.txt-1