-
Notifications
You must be signed in to change notification settings - Fork 408
Expand file tree
/
Copy pathexplain.go
More file actions
2837 lines (2546 loc) · 106 KB
/
Copy pathexplain.go
File metadata and controls
2837 lines (2546 loc) · 106 KB
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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
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
package cli
import (
"context"
"encoding/hex"
"errors"
"fmt"
"io"
"log/slog"
"os"
"os/exec"
"runtime"
"sort"
"strconv"
"strings"
"time"
"github.com/entireio/cli/cmd/entire/cli/agent"
"github.com/entireio/cli/cmd/entire/cli/agent/claudecode"
"github.com/entireio/cli/cmd/entire/cli/agent/external"
"github.com/entireio/cli/cmd/entire/cli/agent/geminicli"
"github.com/entireio/cli/cmd/entire/cli/agent/opencode"
"github.com/entireio/cli/cmd/entire/cli/agent/types"
"github.com/entireio/cli/cmd/entire/cli/checkpoint"
"github.com/entireio/cli/cmd/entire/cli/checkpoint/id"
"github.com/entireio/cli/cmd/entire/cli/interactive"
"github.com/entireio/cli/cmd/entire/cli/logging"
"github.com/entireio/cli/cmd/entire/cli/paths"
"github.com/entireio/cli/cmd/entire/cli/settings"
"github.com/entireio/cli/cmd/entire/cli/strategy"
"github.com/entireio/cli/cmd/entire/cli/summarize"
"github.com/entireio/cli/cmd/entire/cli/trailers"
"github.com/entireio/cli/cmd/entire/cli/transcript"
transcriptcompact "github.com/entireio/cli/cmd/entire/cli/transcript/compact"
"github.com/entireio/cli/redact"
"charm.land/lipgloss/v2"
"github.com/go-git/go-git/v6"
"github.com/go-git/go-git/v6/plumbing"
"github.com/go-git/go-git/v6/plumbing/object"
"github.com/go-git/go-git/v6/plumbing/storer"
"github.com/go-git/go-git/v6/storage/filesystem"
"github.com/spf13/cobra"
"golang.org/x/term"
)
const defaultCheckpointSummaryTimeout = 5 * time.Minute
const (
pagerEnvVar = "PAGER"
lessEnvVar = "LESS"
lessPagerName = "less"
lessRawControlEnv = "LESS=-R"
windowsGOOS = "windows"
)
var checkpointSummaryTimeout = defaultCheckpointSummaryTimeout
var generateTranscriptSummary = summarize.GenerateFromTranscript
// resolveSummaryTimeout picks the effective deadline for `explain --generate`
// using the precedence: per-run flag > settings.summary_timeout_seconds >
// package default. Zero or negative values at any layer mean "unset; consult
// the next layer down" — matching SummaryTimeoutValue() semantics.
//
// Settings load failures are logged at debug and fall through to the default;
// a parsing hiccup must not break summary generation.
func resolveSummaryTimeout(ctx context.Context, flagSeconds int) time.Duration {
if flagSeconds > 0 {
return time.Duration(flagSeconds) * time.Second
}
s, err := settings.Load(ctx)
if err != nil {
logging.Debug(ctx, "summary timeout: settings load failed, using default",
slog.String("error", err.Error()))
return checkpointSummaryTimeout
}
if v := s.SummaryTimeoutValue(); v > 0 {
return v
}
return checkpointSummaryTimeout
}
// errCannotGenerateTemporaryCheckpoint is returned by runExplainCheckpoint when
// --generate is requested for a target that does not match any committed
// checkpoint. runExplainAuto uses errors.Is to detect this case and fall back
// to resolving the target as a git commit ref.
var errCannotGenerateTemporaryCheckpoint = errors.New("cannot generate summary for temporary checkpoint")
type explainCheckpointLookup struct {
repo *git.Repository
store *checkpoint.GitStore
committed []checkpoint.CommittedInfo
}
func (l *explainCheckpointLookup) Close() error {
if l == nil || l.repo == nil {
return nil
}
if err := l.repo.Close(); err != nil {
return fmt.Errorf("close repository: %w", err)
}
return nil
}
// generateOrRawLabel returns the user-facing verb for the action the user
// requested, used in error messages when a commit target has no trailer.
func generateOrRawLabel(generate bool) string {
if generate {
return "generate summary"
}
return "show raw transcript"
}
// printNoTrailerMessage renders the friendly message shown when a resolved
// commit has no Entire-Checkpoint trailer in read-only modes. Takes the
// repo so the hash can be abbreviated to the minimum unique length for
// this repo's object set (matching git's --abbrev behavior).
func printNoTrailerMessage(w io.Writer, repo *git.Repository, hash plumbing.Hash) {
styles := newStatusStyles(w)
rows := []explainRow{
{Label: "commit", Value: abbreviateCommitHash(repo, hash)},
{Label: "reason", Value: "no Entire-Checkpoint trailer"},
{Label: "hint", Value: "this commit was not created during an Entire session,"},
{Label: "", Value: "or the trailer was removed"},
}
fmt.Fprint(w, styles.renderFailure("No associated Entire checkpoint", rows))
}
// errAmbiguousCommitPrefix is returned by resolveCommitUnambiguous when a
// hex prefix matches more than one commit. Callers use errors.Is to detect
// this case and surface the full wrapped message verbatim.
var errAmbiguousCommitPrefix = errors.New("ambiguous commit prefix")
// commitHashesWithPrefix enumerates all commit hashes in the repo whose
// SHA starts with the given hex prefix. Returns nil when the storer is not
// a *filesystem.Storage or the prefix isn't decodable as hex.
//
// Per PR review (discussion_r3113804961): the reviewer specifically
// suggested repo.Storer.(*filesystem.Storage).HashesWithPrefix followed by
// commit filtering. Using this primitive both in resolution (detect
// ambiguous user input) and in display (dynamically abbreviate shown
// hashes to the minimum unique length).
func commitHashesWithPrefix(repo *git.Repository, prefix string) []plumbing.Hash {
s, ok := repo.Storer.(*filesystem.Storage)
if !ok {
return nil
}
// Truncate to even length for byte-aligned hex decoding.
evenHex := prefix[:len(prefix)&^1]
decoded, err := hex.DecodeString(evenHex)
if err != nil || len(decoded) == 0 {
return nil
}
candidates, err := s.HashesWithPrefix(decoded)
if err != nil {
return nil
}
var commits []plumbing.Hash
for _, h := range candidates {
// HashesWithPrefix matches on even byte boundaries; filter the
// dangling nybble for odd-length prefixes.
if len(evenHex) != len(prefix) && !strings.HasPrefix(h.String(), prefix) {
continue
}
if _, err := repo.CommitObject(h); err != nil {
continue
}
commits = append(commits, h)
}
return commits
}
// resolveCommitUnambiguous resolves a ref to a commit hash, returning
// errAmbiguousCommitPrefix (and the matching hashes) when a hex-prefix input
// matches more than one commit. go-git v6's ResolveRevision silently picks
// the first candidate in ambiguous cases (its source explicitly says "for
// speed purposes don't bother to detect the ambiguity"), which could pick
// the wrong commit. Non-hex refs (HEAD, branch names, HEAD~1) bypass the
// ambiguity check via commitHashesWithPrefix returning nil.
//
// The structured ambiguous return lets callers render a styled failure
// block (with each match's timestamp/session) without re-resolving the
// matches themselves.
func resolveCommitUnambiguous(repo *git.Repository, ref string) (plumbing.Hash, []plumbing.Hash, error) {
hash, err := repo.ResolveRevision(plumbing.Revision(ref))
if err != nil {
return plumbing.ZeroHash, nil, err //nolint:wrapcheck // caller contextualizes
}
matches := commitHashesWithPrefix(repo, ref)
if len(matches) <= 1 {
return *hash, nil, nil
}
return plumbing.ZeroHash, matches, errAmbiguousCommitPrefix
}
// abbreviateCommitHash returns the shortest prefix of hash unique among
// commit objects in the repo, matching git's --abbrev-commit auto-growth
// so displayed short SHAs stay unambiguous as the repo grows. Falls back
// to a fixed 12-char prefix if the storer doesn't support fast prefix
// lookup, or to the full hash if somehow never unique.
func abbreviateCommitHash(repo *git.Repository, hash plumbing.Hash) string {
full := hash.String()
for length := 7; length < len(full); length++ {
matches := commitHashesWithPrefix(repo, full[:length])
if matches == nil {
return full[:12]
}
if len(matches) <= 1 {
return full[:length]
}
}
return full
}
// interaction holds a single prompt and its responses for display.
type interaction struct {
Prompt string
Responses []string // Multiple responses can occur between tool calls
Files []string
}
// associatedCommit holds information about a git commit associated with a checkpoint.
type associatedCommit struct {
SHA string
ShortSHA string
Message string
Author string
Email string
Date time.Time
}
// checkpointDetail holds detailed information about a checkpoint for display.
type checkpointDetail struct {
Index int
ShortID string
Timestamp time.Time
IsTaskCheckpoint bool
Message string
// Interactions contains all prompt/response pairs in this checkpoint.
// Most strategies have one, but shadow condensations may have multiple.
Interactions []interaction
// Files is the aggregate list of all files modified (for backwards compat)
Files []string
}
func newExplainCmd() *cobra.Command {
var sessionFlag string
var commitFlag string
var checkpointFlag string
var noPagerFlag bool
var shortFlag bool
var fullFlag bool
var rawTranscriptFlag bool
var generateFlag bool
var forceFlag bool
var searchAllFlag bool
var jsonFlag bool
var transcriptFlag bool
var summaryTimeoutSecondsFlag int
sessionIndex := -1
listLimit := 0 // 0 means "use default (branchCheckpointsLimit)"
cmd := &cobra.Command{
Use: "explain [checkpoint-id | commit-sha]",
Short: "Explain a session, commit, or checkpoint",
Long: `Explain provides human-readable context about sessions, commits, and checkpoints.
Use this command to understand what happened during agent-driven development,
either for self-review or to understand a teammate's work.
By default, shows checkpoints on the current branch. Pass a checkpoint ID or
commit SHA as a positional argument to explain a specific item, or use flags.
Viewing specific items:
entire explain <id-or-sha> Auto-detects checkpoint ID or commit SHA
entire explain --checkpoint <id> Force interpretation as checkpoint ID
entire explain --commit <ref> Force interpretation as commit ref
Filtering the list view:
--session Filter checkpoints by session ID (or prefix)
Output verbosity levels (when explaining a specific item):
Default: Detailed view with scoped prompts (ID, session, tokens, intent, prompts, files)
--short Summary only (ID, session, timestamp, tokens, intent)
--full Parsed full transcript (all prompts/responses from entire session)
--raw-transcript Raw transcript file (JSONL format)
Machine-readable export modes (additive surface for external consumers):
--json Metadata-only JSON. Lists checkpoints when no target is given;
emits a single checkpoint envelope when a target is supplied.
Transcript bytes are NEVER embedded in the JSON envelope.
--transcript Stream stored checkpoint transcript bytes (JSONL) to stdout
for the selected session. Same bytes as --raw-transcript
while checkpoints v1 is the checkpoint store.
--session-index Pick a session within a multi-session checkpoint (0-based).
Defaults to the latest session. Only meaningful with
--transcript or --raw-transcript.
--limit Cap the number of checkpoints returned by the list view.
Defaults to 100. When the cap is hit, a stderr note
says how many were skipped. Only meaningful with --json.
Summary generation:
--generate Generate an AI summary for the checkpoint
--force Regenerate even if a summary already exists (requires --generate)
Performance options:
--search-all Remove branch/depth limits when searching for commits (may be slow)
Checkpoint detail view shows:
- Author of the checkpoint
- Associated git commits that reference the checkpoint
- Prompts and responses from the session
Note: --session filters the list view; the positional arg, --commit, and --checkpoint are mutually exclusive.`,
Args: func(_ *cobra.Command, args []string) error {
if len(args) > 1 {
return fmt.Errorf("accepts at most 1 argument (checkpoint ID or commit SHA), received %d\nHint: use --session to filter the list view, or pass a single checkpoint ID / commit SHA", len(args))
}
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
// Check if Entire is disabled
if checkDisabledGuard(cmd.Context(), cmd.OutOrStdout()) {
return nil
}
// Only initialize logging when inside a git worktree to avoid
// creating .entire/logs/ in arbitrary directories.
if _, err := paths.WorktreeRoot(cmd.Context()); err == nil {
logging.SetLogLevelGetter(GetLogLevel)
if err := logging.Init(cmd.Context(), ""); err == nil {
defer logging.Close()
}
}
// Positional arg is mutually exclusive with --checkpoint, --commit, --session
var positional string
if len(args) > 0 {
positional = args[0]
if checkpointFlag != "" || commitFlag != "" || sessionFlag != "" {
return errors.New("cannot combine positional argument with --checkpoint, --commit, or --session")
}
}
// --generate and --raw-transcript need a specific target — either the
// positional arg, --checkpoint/-c, or --commit (which forwards to
// the checkpoint path via the commit's Entire-Checkpoint trailer).
hasCheckpointTarget := checkpointFlag != "" || commitFlag != "" || positional != ""
if generateFlag && !hasCheckpointTarget {
return errors.New("--generate requires a checkpoint ID or commit SHA (positional), --checkpoint/-c, or --commit flag")
}
if forceFlag && !generateFlag {
return errors.New("--force requires --generate flag")
}
if rawTranscriptFlag && !hasCheckpointTarget {
return errors.New("--raw-transcript requires a checkpoint ID or commit SHA (positional), --checkpoint/-c, or --commit flag")
}
if transcriptFlag && !hasCheckpointTarget {
return errors.New("--transcript requires a checkpoint ID or commit SHA (positional), --checkpoint/-c, or --commit flag")
}
if cmd.Flags().Changed("session-index") {
if !transcriptFlag && !rawTranscriptFlag {
return errors.New("--session-index only applies with --transcript or --raw-transcript")
}
if sessionIndex < 0 {
return errors.New("--session-index must be non-negative")
}
}
if cmd.Flags().Changed("limit") {
if !jsonFlag {
return errors.New("--limit only applies with --json")
}
if listLimit <= 0 {
return errors.New("--limit must be positive")
}
}
// --summary-timeout-seconds only makes sense with --generate.
if cmd.Flags().Changed("summary-timeout-seconds") {
if !generateFlag {
return errors.New("--summary-timeout-seconds only applies with --generate")
}
if summaryTimeoutSecondsFlag < 0 {
return errors.New("--summary-timeout-seconds must be non-negative")
}
}
// Export modes — emit machine-readable output and skip the prose pipeline.
// --raw-transcript also routes here when --session-index is explicit; the
// legacy raw-transcript path (with spinner + prefetch) handles the default
// case where the caller wants the latest session.
rawWithSessionIndex := rawTranscriptFlag && cmd.Flags().Changed("session-index")
if jsonFlag || transcriptFlag || rawWithSessionIndex {
return runExplainExport(cmd.Context(), cmd.OutOrStdout(), cmd.ErrOrStderr(), explainExportOptions{
sessionFilter: sessionFlag,
commitRef: commitFlag,
checkpointFlag: checkpointFlag,
target: positional,
json: jsonFlag,
transcript: transcriptFlag,
rawTranscript: rawTranscriptFlag,
sessionIndex: sessionIndex,
listLimit: listLimit,
})
}
// Convert short flag to verbose (verbose = !short)
verbose := !shortFlag
return runExplain(cmd.Context(), cmd.OutOrStdout(), cmd.ErrOrStderr(), sessionFlag, commitFlag, checkpointFlag, positional, noPagerFlag, verbose, fullFlag, rawTranscriptFlag, generateFlag, forceFlag, searchAllFlag, summaryTimeoutSecondsFlag)
},
}
cmd.Flags().StringVar(&sessionFlag, "session", "", "Filter checkpoints by session ID (or prefix)")
cmd.Flags().StringVar(&commitFlag, "commit", "", "Explain a specific commit (SHA or ref, \"commit-ish\")")
cmd.Flags().StringVarP(&checkpointFlag, "checkpoint", "c", "", "Explain a specific checkpoint (ID or prefix)")
cmd.Flags().BoolVar(&noPagerFlag, "no-pager", false, "Disable pager output")
cmd.Flags().BoolVarP(&shortFlag, "short", "s", false, "Show summary only (omit prompts and files)")
cmd.Flags().BoolVar(&fullFlag, "full", false, "Show full parsed transcript (all prompts/responses)")
cmd.Flags().BoolVar(&rawTranscriptFlag, "raw-transcript", false, "Show raw transcript file (JSONL format)")
cmd.Flags().BoolVar(&generateFlag, "generate", false, "Generate an AI summary for the checkpoint")
cmd.Flags().BoolVar(&forceFlag, "force", false, "Regenerate summary even if one already exists (requires --generate)")
cmd.Flags().BoolVar(&searchAllFlag, "search-all", false, "Search all commits (no branch/depth limit, may be slow)")
cmd.Flags().BoolVar(&jsonFlag, "json", false, "Output metadata as JSON (no transcript bytes)")
cmd.Flags().BoolVar(&transcriptFlag, "transcript", false, "Stream stored checkpoint transcript bytes to stdout")
cmd.Flags().IntVar(&sessionIndex, "session-index", -1, "Session index within a multi-session checkpoint (0-based, defaults to latest)")
cmd.Flags().IntVar(&listLimit, "limit", 0, "Cap the list view at N checkpoints (default: 100). Only meaningful with --json.")
cmd.Flags().IntVar(&summaryTimeoutSecondsFlag, "summary-timeout-seconds", 0, "Hard deadline in seconds for --generate summary generation; overrides summary_timeout_seconds setting. 0 = use setting or 5m default.")
// Verbosity / transcript output modes are mutually exclusive
cmd.MarkFlagsMutuallyExclusive("short", "full", "raw-transcript", "transcript", "json")
// --generate and --raw-transcript are incompatible (summary would be generated but not shown)
cmd.MarkFlagsMutuallyExclusive("generate", "raw-transcript")
// --generate is a write op; export modes are reader-only
cmd.MarkFlagsMutuallyExclusive("generate", "json")
cmd.MarkFlagsMutuallyExclusive("generate", "transcript")
return cmd
}
// runExplain routes to the appropriate explain function based on flags and the
// optional positional target.
func runExplain(ctx context.Context, w, errW io.Writer, sessionID, commitRef, checkpointID, target string, noPager, verbose, full, rawTranscript, generate, force, searchAll bool, summaryTimeoutSeconds int) error {
// Count mutually exclusive flags (--commit and --checkpoint are mutually exclusive)
// --session is now a filter for the list view, not a separate mode
flagCount := 0
if commitRef != "" {
flagCount++
}
if checkpointID != "" {
flagCount++
}
// If --session is combined with --commit or --checkpoint, that's still an error
if sessionID != "" && flagCount > 0 {
return errors.New("cannot specify multiple of --session, --commit, --checkpoint")
}
if flagCount > 1 {
return errors.New("cannot specify multiple of --session, --commit, --checkpoint")
}
// Route to appropriate handler
if target != "" {
return runExplainAuto(ctx, w, errW, target, noPager, verbose, full, rawTranscript, generate, force, searchAll, summaryTimeoutSeconds)
}
if commitRef != "" {
return runExplainCommit(ctx, w, errW, commitRef, noPager, verbose, full, rawTranscript, generate, force, searchAll, summaryTimeoutSeconds)
}
if checkpointID != "" {
return runExplainCheckpoint(ctx, w, errW, checkpointID, noPager, verbose, full, rawTranscript, generate, force, searchAll, summaryTimeoutSeconds)
}
// Default or with session filter: show list view (optionally filtered by session)
return runExplainBranchWithFilter(ctx, w, noPager, sessionID)
}
// runExplainAuto resolves a positional target as either a checkpoint ID
// (or prefix) or a git commit ref. Ordering: checkpoint path first (which
// also handles shadow-branch temp checkpoints), falling back to commit
// resolution only on checkpoint.ErrCheckpointNotFound. --generate runs
// an ambiguity pre-check to avoid writing a summary to the wrong
// checkpoint on short-prefix collisions.
func runExplainAuto(ctx context.Context, w, errW io.Writer, target string, noPager, verbose, full, rawTranscript, generate, force, searchAll bool, summaryTimeoutSeconds int) error {
stop := startSpinner(errW, "Loading checkpoints")
lookup, lookupErr := newExplainCheckpointLookup(ctx)
stop(false)
if lookup != nil {
defer lookup.Close()
}
if generate {
if err := runExplainAutoAmbiguityGuard(ctx, target, lookup, lookupErr); err != nil {
return err
}
}
checkpointErr := runExplainCheckpointWithLookup(ctx, w, errW, target, noPager, verbose, full, rawTranscript, generate, force, searchAll, lookup, lookupErr, summaryTimeoutSeconds)
if checkpointErr == nil {
return nil
}
// Fall back to commit resolution ONLY when nothing (committed or temp)
// matched the target. errCannotGenerateTemporaryCheckpoint signals that
// we DID match a temp checkpoint but --generate is unsupported for it;
// falling back to commit in that case would produce a misleading
// "no trailer" error for the shadow-branch commit.
if !errors.Is(checkpointErr, checkpoint.ErrCheckpointNotFound) {
return checkpointErr
}
logging.Debug(ctx, "explain auto: checkpoint lookup failed, trying commit fallback",
slog.String("target", target),
slog.String("checkpoint_error", checkpointErr.Error()))
if lookupErr != nil {
// Composed message beats errors.Join here — the latter renders
// two lines (one per error) and users act on the first/stale one.
return fmt.Errorf("no checkpoint matched %q, and commit fallback failed: %w", target, lookupErr)
}
hash, ambiguousMatches, resolveErr := resolveCommitUnambiguous(lookup.repo, target)
if resolveErr != nil {
if errors.Is(resolveErr, errAmbiguousCommitPrefix) {
renderAmbiguousPrefixFailure(errW, target, "commits", buildAmbiguousCommitMatches(lookup.repo, ambiguousMatches))
return NewSilentError(resolveErr)
}
logging.Debug(ctx, "explain auto: git ref resolution failed",
slog.String("target", target),
slog.String("error", resolveErr.Error()))
return fmt.Errorf("no checkpoint or commit found matching %q", target)
}
commit, commitErr := lookup.repo.CommitObject(hash)
if commitErr != nil {
return fmt.Errorf("failed to get commit %s: %w", abbreviateCommitHash(lookup.repo, hash), commitErr)
}
cpID, hasCheckpoint := trailers.ParseCheckpoint(commit.Message)
if !hasCheckpoint {
// Side-effect modes must error — silently succeeding would leave
// scripts unable to distinguish "done" from "didn't happen".
if generate || rawTranscript {
return fmt.Errorf("cannot %s: commit %s has no Entire-Checkpoint trailer", generateOrRawLabel(generate), abbreviateCommitHash(lookup.repo, hash))
}
printNoTrailerMessage(w, lookup.repo, hash)
return nil
}
logging.Debug(ctx, "explain auto: resolved commit to checkpoint via trailer",
slog.String("target", target),
slog.String("commit", abbreviateCommitHash(lookup.repo, hash)),
slog.String("checkpoint_id", cpID.String()))
return runExplainCheckpointWithLookup(ctx, w, errW, cpID.String(), noPager, verbose, full, rawTranscript, generate, force, searchAll, lookup, nil, summaryTimeoutSeconds)
}
// runExplainAutoAmbiguityGuard refuses --generate when the positional
// target resolves as both a git revision and a committed-checkpoint prefix.
// Writing a summary to the wrong checkpoint is destructive; read-only flows
// tolerate the same ambiguity by preferring the checkpoint path.
//
// Best-effort: on repo/list failures we return nil so the main flow
// surfaces the real error instead of double-reporting.
func runExplainAutoAmbiguityGuard(ctx context.Context, target string, lookup *explainCheckpointLookup, lookupErr error) error {
// Targets longer than a checkpoint ID can't prefix-match one.
// This is coupled to checkpoint IDs being fixed-width; longer targets
// cannot be prefixes of committed checkpoint IDs.
if len(target) > id.ShortIDLength {
return nil
}
if lookupErr != nil {
logging.Warn(ctx, "explain ambiguity guard degraded: failed to prepare checkpoint lookup",
"target", target,
"error", lookupErr)
return nil
}
hash, err := lookup.repo.ResolveRevision(plumbing.Revision(target))
if err != nil {
return nil //nolint:nilerr // target isn't a git ref
}
if lookup == nil {
logging.Warn(ctx, "explain ambiguity guard degraded: checkpoint lookup unavailable",
"target", target)
return nil
}
if lookup.committed == nil {
logging.Warn(ctx, "explain ambiguity guard degraded: committed checkpoint list unavailable",
"target", target)
return nil
}
for _, info := range lookup.committed {
if strings.HasPrefix(info.CheckpointID.String(), target) {
return fmt.Errorf("ambiguous target %q with --generate: matches both git revision %s and checkpoint prefix (e.g. %s)\nUse --commit <ref> or --checkpoint <id> to disambiguate", target, abbreviateCommitHash(lookup.repo, *hash), info.CheckpointID)
}
}
return nil
}
// runExplainCheckpoint explains a specific checkpoint.
// Supports both committed checkpoints (by checkpoint ID) and temporary checkpoints (by git SHA).
// First tries to match committed checkpoints, then falls back to temporary checkpoints.
// When generate is true, generates an AI summary for the checkpoint.
// When force is true, regenerates even if a summary already exists.
// When rawTranscript is true, outputs only the raw transcript file (JSONL format).
// When searchAll is true, searches all commits without branch/depth limits (used for finding associated commits).
//
func runExplainCheckpoint(ctx context.Context, w, errW io.Writer, checkpointIDPrefix string, noPager, verbose, full, rawTranscript, generate, force, searchAll bool, summaryTimeoutSeconds int) error {
return runExplainCheckpointWithLookup(ctx, w, errW, checkpointIDPrefix, noPager, verbose, full, rawTranscript, generate, force, searchAll, nil, nil, summaryTimeoutSeconds)
}
func runExplainCheckpointWithLookup(ctx context.Context, w, errW io.Writer, checkpointIDPrefix string, noPager, verbose, full, rawTranscript, generate, force, searchAll bool, lookup *explainCheckpointLookup, lookupErr error, summaryTimeoutSeconds int) error {
ownLookup := false
if lookup == nil {
var err error
lookup, err = newExplainCheckpointLookup(ctx)
if err != nil {
return err
}
ownLookup = true
} else if lookupErr != nil {
return lookupErr
}
initialLookup := lookup
defer func() {
if ownLookup && initialLookup != nil {
_ = initialLookup.Close()
}
if lookup != nil && lookup != initialLookup {
_ = lookup.Close()
}
}()
// Match the prefix locally; on miss, fetch from remote and retry once.
matches, lookup := matchCheckpointPrefixWithRemoteFallback(ctx, errW, lookup, checkpointIDPrefix)
var fullCheckpointID id.CheckpointID
switch len(matches) {
case 0:
// Check temp checkpoints BEFORE returning errCannotGenerateTemporaryCheckpoint
// so runExplainAuto can distinguish:
// - target matched a real temp checkpoint (sentinel returned, no fallback)
// - target matched nothing (ErrCheckpointNotFound, safe to fall back to commit)
// Previously the --generate path bailed before checking temp checkpoints,
// which made runExplainAuto fall back to commit resolution for temp
// checkpoint SHAs and produce a misleading "no trailer" error.
//
// --generate and --raw-transcript are mutually exclusive at the flag
// layer, so rawTranscript is always false when generate is true; the
// direct-to-w write path inside explainTemporaryCheckpoint is not
// reachable here and won't leak partial output on error.
output, found, tempErr := explainTemporaryCheckpoint(ctx, w, errW, lookup.repo, checkpoint.NewGitStore(lookup.repo), checkpointIDPrefix, verbose, full, rawTranscript)
if tempErr != nil {
return tempErr
}
if found {
if generate {
return fmt.Errorf("%w %s (only committed checkpoints supported)", errCannotGenerateTemporaryCheckpoint, checkpointIDPrefix)
}
outputExplainContent(w, output, noPager)
return nil
}
return fmt.Errorf("%w: %s", checkpoint.ErrCheckpointNotFound, checkpointIDPrefix)
case 1:
fullCheckpointID = matches[0]
default:
// Ambiguous prefix: render styled failure block, return SilentError so
// main.go does not double-print. Matches the temporary-side and
// commit-side ambiguity paths.
ambig := buildAmbiguousCheckpointMatches(matches, lookup.committed)
renderAmbiguousPrefixFailure(errW, checkpointIDPrefix, "committed checkpoints", ambig)
return NewSilentError(fmt.Errorf("%w: %s matches %d checkpoints", errAmbiguousCommitPrefix, checkpointIDPrefix, len(matches)))
}
// One spinner covers the entire data-loading pipeline: prefetch's
// missing-blob analysis (which spawns one cat-file -e per blob and
// can take seconds on a deep checkpoint subtree), the prefetch fetch
// itself, the committed checkpoint metadata read, session content
// reads, and getAssociatedCommits' git log walk. Stop strictly before
// any write to w (stdout) so stderr spinner frames and stdout output
// never interleave.
stopLoad := startSpinner(errW, fmt.Sprintf("Loading checkpoint %s", fullCheckpointID))
summary, content, err := loadCheckpointForExplain(ctx, lookup, fullCheckpointID)
if err != nil {
stopLoad(false)
return err
}
// Handle summary generation — uses raw transcript.
if generate {
stopLoad(false) // generation prints its own progress to w/errW
writeStore := checkpoint.NewGitStore(lookup.repo)
if err := generateCheckpointSummary(ctx, w, errW, writeStore, fullCheckpointID, summary, content, force, summaryTimeoutSeconds); err != nil {
return err
}
// Reload to get the updated summary.
stopLoad = startSpinner(errW, fmt.Sprintf("Reloading checkpoint %s", fullCheckpointID))
lookup.store = checkpoint.NewCommittedReadStore(ctx, lookup.repo)
lookup.store.SetBlobFetcher(FetchBlobsByHash)
content, err = checkpoint.ReadLatestSessionContent(ctx, lookup.store, fullCheckpointID, summary)
if err != nil {
stopLoad(false)
return fmt.Errorf("failed to reload checkpoint: %w", err)
}
}
// Handle raw transcript output
if rawTranscript {
stopLoad(false)
if len(content.Transcript) == 0 {
return fmt.Errorf("checkpoint %s has no transcript", fullCheckpointID)
}
// Output raw transcript directly (no pager, no formatting)
if _, err = w.Write(content.Transcript); err != nil {
return fmt.Errorf("failed to write transcript: %w", err)
}
return nil
}
// Find associated commits (git commits with matching Entire-Checkpoint trailer)
associatedCommits, _ := getAssociatedCommits(ctx, lookup.repo, fullCheckpointID, searchAll) //nolint:errcheck // Best-effort
// Derive author from the first associated commit (the user who made the commit).
// Fall back to the committed checkpoint store for checkpoints
// not reachable from the current branch.
var author checkpoint.Author
if len(associatedCommits) > 0 {
author = checkpoint.Author{
Name: associatedCommits[0].Author,
Email: associatedCommits[0].Email,
}
} else {
author, _ = lookup.store.GetCheckpointAuthor(ctx, fullCheckpointID) //nolint:errcheck // Author is optional
}
// Format and output. Stop spinner BEFORE any write to w to keep stderr
// frames and stdout content from interleaving.
stopLoad(false)
output := formatCheckpointOutput(summary, content, fullCheckpointID, associatedCommits, author, verbose, full, w)
outputExplainContent(w, output, noPager)
return nil
}
// loadCheckpointForExplain runs prefetchCheckpointBlobs + summary read +
// session content read for the given checkpoint. Extracts the bulk of the
// data-load pipeline out of runExplainCheckpointWithLookup so that
// function stays under maintidx limits. Caller is responsible for the
// surrounding spinner.
func loadCheckpointForExplain(ctx context.Context, lookup *explainCheckpointLookup, cpID id.CheckpointID) (*checkpoint.CheckpointSummary, *checkpoint.SessionContent, error) {
prefetchCheckpointBlobs(ctx, lookup.repo, cpID)
store := lookup.store
summary, err := checkpoint.ReadCommittedCheckpoint(ctx, store, cpID)
if err != nil {
return nil, nil, fmt.Errorf("failed to read checkpoint: %w", err)
}
content, contentErr := checkpoint.ReadLatestSessionContent(ctx, store, cpID, summary)
if contentErr != nil {
return nil, nil, fmt.Errorf("failed to read checkpoint content: %w", contentErr)
}
return summary, content, nil
}
// prefetchCheckpointBlobs navigates to the checkpoint's local subtree(s),
// collects every locally-missing blob, and
// fetches them all in a single `git fetch-pack` invocation per store.
// Best-effort — failure is logged and the read path falls back to the
// FetchingTree's per-File fetcher.
//
// Caller is expected to wrap this with a spinner; both the missing-blob
// analysis (one cat-file -e per blob) and the actual fetch are silent
// inside this function so the caller's spinner provides continuous
// feedback.
func prefetchCheckpointBlobs(ctx context.Context, repo *git.Repository, cpID id.CheckpointID) {
v1FT := buildCheckpointFetchingTree(ctx, repo, cpID, "v1", loadV1MetadataRootTree)
missingCount := 0
if v1FT != nil {
missingCount += len(v1FT.CollectMissingBlobs())
}
if missingCount == 0 {
return
}
logging.Debug(ctx, "explain prefetch: fetching missing checkpoint blobs",
slog.String("checkpoint_id", cpID.String()),
slog.Int("blob_count", missingCount),
)
runPreFetch(ctx, v1FT, cpID, "v1")
}
// buildCheckpointFetchingTree navigates to the checkpoint subtree using
// loadRoot and wraps it in a FetchingTree with FetchBlobsByHash. Returns
// nil when the root tree or cp subtree isn't navigable.
func buildCheckpointFetchingTree(ctx context.Context, repo *git.Repository, cpID id.CheckpointID, label string, loadRoot func(*git.Repository) (*object.Tree, error)) *checkpoint.FetchingTree {
rootTree, err := loadRoot(repo)
if err != nil {
return nil
}
cpSubtree, err := rootTree.Tree(cpID.Path())
if err != nil {
logging.Debug(ctx, "explain prefetch: cp subtree not found",
slog.String("store", label),
slog.String("checkpoint_id", cpID.String()),
slog.String("error", err.Error()),
)
return nil
}
return checkpoint.NewFetchingTree(ctx, cpSubtree, repo.Storer, FetchBlobsByHash)
}
func runPreFetch(ctx context.Context, ft *checkpoint.FetchingTree, cpID id.CheckpointID, label string) {
if ft == nil {
return
}
prefetched, err := ft.PreFetch()
if err != nil {
logging.Debug(ctx, "explain prefetch: PreFetch failed",
slog.String("store", label),
slog.String("checkpoint_id", cpID.String()),
slog.String("error", err.Error()),
)
return
}
if prefetched > 0 {
logging.Debug(ctx, "explain prefetch: blobs fetched in one round-trip",
slog.String("store", label),
slog.String("checkpoint_id", cpID.String()),
slog.Int("blob_count", prefetched),
)
}
}
func loadV1MetadataRootTree(repo *git.Repository) (*object.Tree, error) {
if tree, err := strategy.GetMetadataBranchTree(repo); err == nil {
return tree, nil
}
tree, err := strategy.GetRemoteMetadataBranchTree(repo)
if err != nil {
return nil, fmt.Errorf("read v1 metadata tree (local + remote-tracking): %w", err)
}
return tree, nil
}
func newExplainCheckpointLookup(ctx context.Context) (*explainCheckpointLookup, error) {
repo, err := openRepository(ctx)
if err != nil {
return nil, fmt.Errorf("not a git repository: %w", err)
}
closeOnError := true
defer func() {
if closeOnError {
_ = repo.Close()
}
}()
// FetchBlobsByHash uses `git fetch-pack` for blob SHAs (porcelain
// `git fetch` fails against partial-clone repos with "did not send all
// necessary objects"). Falls back to a full metadata-branch fetch if
// fetch-pack also can't reach the blobs.
store := checkpoint.NewCommittedReadStore(ctx, repo)
store.SetBlobFetcher(FetchBlobsByHash)
lookup := &explainCheckpointLookup{
repo: repo,
store: store,
}
committed, err := store.ListCommitted(ctx)
if err != nil {
return nil, fmt.Errorf("failed to list checkpoints: %w", err)
}
lookup.committed = committed
closeOnError = false
return lookup, nil
}
// generateCheckpointSummary generates an AI summary for a checkpoint and persists it.
// The summary is generated from the scoped transcript (only this checkpoint's portion),
// not the entire session transcript.
//
// summaryTimeoutSeconds is the per-invocation --summary-timeout-seconds flag
// value (0 = unset). Effective precedence for the deadline: flag > settings >
// package default. See resolveSummaryTimeout for the resolution.
func generateCheckpointSummary(ctx context.Context, w, errW io.Writer, store *checkpoint.GitStore, checkpointID id.CheckpointID, cpSummary *checkpoint.CheckpointSummary, content *checkpoint.SessionContent, force bool, summaryTimeoutSeconds int) error {
// Check if summary already exists
if content.Metadata.Summary != nil && !force {
return renderExplainFailure(errW, "Summary already exists", []explainRow{
{Label: "id", Value: checkpointID.String()},
{Label: "try", Value: fmt.Sprintf("entire explain --generate --force %s", checkpointID)},
}, fmt.Errorf("checkpoint %s already has a summary", checkpointID))
}
// Check if transcript exists
if len(content.Transcript) == 0 {
return renderExplainFailure(errW, "Checkpoint has no transcript", []explainRow{
{Label: "id", Value: checkpointID.String()},
}, fmt.Errorf("checkpoint %s has no transcript to summarize", checkpointID))
}
// Scope the transcript to only this checkpoint's portion
scopedTranscript := scopeTranscriptForCheckpoint(content.Transcript, content.Metadata.GetTranscriptStart(), content.Metadata.Agent)
if len(scopedTranscript) == 0 {
return renderExplainFailure(errW, "Checkpoint has no transcript content (scoped)", []explainRow{
{Label: "id", Value: checkpointID.String()},
}, fmt.Errorf("checkpoint %s has no transcript content for this checkpoint (scoped)", checkpointID))
}
provider, err := resolveCheckpointSummaryProvider(ctx, w)
if err != nil {
return fmt.Errorf("failed to resolve summary provider: %w", err)
}
scopedTranscript = maybeCompactExternalTranscriptForSummary(ctx, scopedTranscript, content.Metadata.Agent)
// Generate summary using shared helper
logging.Info(ctx, "generating checkpoint summary")
if errW != nil {
fmt.Fprintln(errW, "Generating checkpoint summary...")
}
timeout := resolveSummaryTimeout(ctx, summaryTimeoutSeconds)
start := time.Now()
summary, appliedDeadline, err := generateCheckpointAISummary(ctx, scopedTranscript, cpSummary.FilesTouched, content.Metadata.Agent, provider.Generator, timeout)
if err != nil {
label, rows, structured := formatCheckpointSummaryError(err, appliedDeadline)
styles := newStatusStyles(errW)
fmt.Fprint(errW, styles.renderFailure(label, rows))
return NewSilentError(structured)
}
elapsed := time.Since(start)
if err := store.UpdateSummary(ctx, checkpointID, summary); err != nil {
return fmt.Errorf("failed to save summary: %w", err)
}
if refs := checkpoint.ResolveCommittedRefs(ctx); refs.HasMirror() {
if err := strategy.MirrorCommittedMetadataRef(ctx, store.Repository(), refs); err != nil {
return fmt.Errorf("summary was written to %s, but failed to mirror to %s: %w", refs.Primary, refs.Mirror, err)
}
}
styles := newStatusStyles(w)
rows := summaryProviderRows(provider)
rows = append(rows, explainRow{Label: "duration", Value: formatSummaryDuration(elapsed)})
fmt.Fprint(w, styles.renderSuccess(fmt.Sprintf("Summary generated for %s", checkpointID), rows))
return nil
}
// formatSummaryDuration rounds wall-clock generation time to a human-friendly value.
func formatSummaryDuration(d time.Duration) string {
return d.Round(100 * time.Millisecond).String()
}
func maybeCompactExternalTranscriptForSummary(ctx context.Context, scopedTranscript []byte, agentType types.AgentType) []byte {
if transcriptHasSummaryContent(scopedTranscript, agentType) {
return scopedTranscript
}
ag, err := agent.GetByAgentType(agentType)
if err != nil {
external.DiscoverAndRegister(ctx)
ag, err = agent.GetByAgentType(agentType)
}
if err != nil || !external.IsExternal(ag) {
return scopedTranscript
}
compactor, ok := agent.AsTranscriptCompactor(ag)
if !ok {
return scopedTranscript
}
tmpFile, err := os.CreateTemp("", "entire-summary-transcript-*.jsonl")
if err != nil {
logging.Debug(ctx, "external summary compaction unavailable",
slog.String("agent", string(agentType)),
slog.String("error", err.Error()))
return scopedTranscript
}
tmpPath := tmpFile.Name()
defer func() {
if removeErr := os.Remove(tmpPath); removeErr != nil {
logging.Debug(ctx, "failed to remove temporary summary transcript",
slog.String("path", tmpPath),
slog.String("error", removeErr.Error()))
}
}()
if _, err := tmpFile.Write(scopedTranscript); err != nil {
_ = tmpFile.Close()
logging.Debug(ctx, "external summary compaction transcript write failed",
slog.String("agent", string(agentType)),
slog.String("error", err.Error()))
return scopedTranscript
}
if err := tmpFile.Close(); err != nil {
logging.Debug(ctx, "external summary compaction transcript close failed",
slog.String("agent", string(agentType)),
slog.String("error", err.Error()))
return scopedTranscript
}
compacted, err := compactor.CompactTranscript(ctx, tmpPath)
if err != nil || compacted == nil || len(compacted.Transcript) == 0 {
if err != nil {
logging.Debug(ctx, "external summary compaction failed",
slog.String("agent", string(agentType)),
slog.String("error", err.Error()))
}
return scopedTranscript