-
Notifications
You must be signed in to change notification settings - Fork 394
Expand file tree
/
Copy pathv2_committed.go
More file actions
1242 lines (1105 loc) · 44.2 KB
/
Copy pathv2_committed.go
File metadata and controls
1242 lines (1105 loc) · 44.2 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 checkpoint
import (
"context"
"crypto/sha256"
"errors"
"fmt"
"io"
"log/slog"
"os"
"strconv"
"strings"
"github.com/entireio/cli/cmd/entire/cli/agent"
"github.com/entireio/cli/cmd/entire/cli/agent/types"
"github.com/entireio/cli/cmd/entire/cli/checkpoint/id"
"github.com/entireio/cli/cmd/entire/cli/jsonutil"
"github.com/entireio/cli/cmd/entire/cli/logging"
"github.com/entireio/cli/cmd/entire/cli/paths"
"github.com/entireio/cli/cmd/entire/cli/validation"
"github.com/entireio/cli/cmd/entire/cli/versioninfo"
"github.com/entireio/cli/redact"
"github.com/go-git/go-git/v6/plumbing"
"github.com/go-git/go-git/v6/plumbing/filemode"
"github.com/go-git/go-git/v6/plumbing/object"
)
// WriteCommitted writes a committed checkpoint to both v2 refs:
// - /main: metadata and prompts (no raw transcript or content hash)
// - /full/current: raw transcript + content hash (replaces previous content)
//
// This is the public entry point for v2 dual-writes. The session index is
// determined from the /main ref and passed to the /full/current write to
// keep both refs consistent.
func (s *V2GitStore) WriteCommitted(ctx context.Context, opts WriteCommittedOptions) error {
_, err := s.WriteCommittedWithSessionIndex(ctx, opts)
return err
}
// WriteCommittedWithSessionIndex writes a committed checkpoint and returns the
// v2 session index used for the write. The index may point at an existing
// session when the checkpoint already contains the same session ID.
func (s *V2GitStore) WriteCommittedWithSessionIndex(ctx context.Context, opts WriteCommittedOptions) (int, error) {
// Validate upfront before any writes to avoid partial ref updates
if err := validateWriteOpts(opts); err != nil {
return 0, err
}
sessionIndex, err := s.writeCommittedMain(ctx, opts)
if err != nil {
return 0, fmt.Errorf("v2 /main write failed: %w", err)
}
if err := s.writeCommittedFullTranscript(ctx, opts, sessionIndex); err != nil {
return 0, fmt.Errorf("v2 /full/current write failed: %w", err)
}
return sessionIndex, nil
}
// WriteCommittedMainBatch writes /main entries for every (checkpoint, session)
// pair in batch using a single commit and a single ref CAS. The /full ref is
// left untouched — callers handle full-transcript artifacts via the existing
// pack flow.
//
// Matches per-session writeCommittedMain semantics within each checkpoint
// group: existing-SessionID dedupe, slot-0 refuse-overwrite, last non-nil
// combinedAttribution, and sticky HasReview.
func (s *V2GitStore) WriteCommittedMainBatch(ctx context.Context, batch []WriteCommittedOptions) error {
if len(batch) == 0 {
return nil
}
for i, opts := range batch {
if err := validateWriteOpts(opts); err != nil {
return fmt.Errorf("batch entry %d: %w", i, err)
}
}
refName := plumbing.ReferenceName(paths.V2MainRefName)
if err := s.ensureRef(ctx, refName); err != nil {
return fmt.Errorf("failed to ensure /main ref: %w", err)
}
parentHash, rootTreeHash, err := s.GetRefState(refName)
if err != nil {
return err
}
// Group opts by checkpoint ID, preserving first-seen order so the
// resulting tree changes are stable regardless of map iteration order.
groupOrder := []id.CheckpointID{}
groups := map[id.CheckpointID][]WriteCommittedOptions{}
for _, opts := range batch {
if _, ok := groups[opts.CheckpointID]; !ok {
groupOrder = append(groupOrder, opts.CheckpointID)
}
groups[opts.CheckpointID] = append(groups[opts.CheckpointID], opts)
}
existingCheckpoints, err := s.existingMainCheckpointIDs(ctx, rootTreeHash)
if err != nil {
return err
}
changes := make([]TreeChange, 0, len(groupOrder))
for _, cpID := range groupOrder {
groupOpts := groups[cpID]
var checkpointTreeHash plumbing.Hash
if _, exists := existingCheckpoints[cpID]; exists {
checkpointTreeHash, err = s.buildMainBatchGroupTree(ctx, rootTreeHash, cpID, groupOpts)
} else {
checkpointTreeHash, err = s.buildFreshMainBatchGroupTree(ctx, cpID, groupOpts)
}
if err != nil {
return err
}
changes = append(changes, TreeChange{
Path: cpID.Path(),
Entry: &object.TreeEntry{
Mode: filemode.Dir,
Hash: checkpointTreeHash,
},
})
}
if len(changes) > 0 {
rootTreeHash, err = ApplyTreeChanges(ctx, s.repo, rootTreeHash, changes)
if err != nil {
return fmt.Errorf("failed to apply batched /main checkpoint trees: %w", err)
}
}
// One commit, one ref update for the entire batch.
commitMsg := fmt.Sprintf("Migrate batch: %d checkpoint(s), %d session(s)\n", len(groupOrder), len(batch))
last := batch[len(batch)-1]
authorName, authorEmail := last.AuthorName, last.AuthorEmail
if authorName == "" || authorEmail == "" {
fallbackName, fallbackEmail := GetGitAuthorFromRepo(s.repo)
if authorName == "" {
authorName = fallbackName
}
if authorEmail == "" {
authorEmail = fallbackEmail
}
}
return s.updateRef(ctx, refName, rootTreeHash, parentHash, commitMsg, authorName, authorEmail)
}
func (s *V2GitStore) existingMainCheckpointIDs(ctx context.Context, rootTreeHash plumbing.Hash) (map[id.CheckpointID]struct{}, error) {
existing := make(map[id.CheckpointID]struct{})
if rootTreeHash == plumbing.ZeroHash {
return existing, nil
}
rootTree, err := s.repo.TreeObject(rootTreeHash)
if err != nil {
return nil, fmt.Errorf("failed to read /main root tree: %w", err)
}
if err := WalkCheckpointShards(ctx, s.repo, rootTree, func(cpID id.CheckpointID, _ plumbing.Hash) error {
existing[cpID] = struct{}{}
return nil
}); err != nil {
return nil, fmt.Errorf("failed to walk existing /main checkpoints: %w", err)
}
return existing, nil
}
func (s *V2GitStore) buildFreshMainBatchGroupTree(ctx context.Context, cpID id.CheckpointID, groupOpts []WriteCommittedOptions) (plumbing.Hash, error) {
basePath := cpID.Path() + "/"
entries := make(map[string]object.TreeEntry)
sessions := make([]SessionFilePaths, len(groupOpts))
for sessionIndex, opts := range groupOpts {
sessionPath := fmt.Sprintf("%s%d/", basePath, sessionIndex)
filePaths, err := s.writeMainSessionToSubdirectory(ctx, opts, sessionPath, entries)
if err != nil {
return plumbing.ZeroHash, err
}
sessions[sessionIndex] = filePaths
}
lastOpts := groupOpts[len(groupOpts)-1]
if err := s.writeFreshMainBatchCheckpointSummary(lastOpts, basePath, entries, sessions, groupOpts); err != nil {
return plumbing.ZeroHash, err
}
return s.buildCheckpointSubtree(ctx, basePath, entries)
}
func (s *V2GitStore) writeFreshMainBatchCheckpointSummary(lastOpts WriteCommittedOptions, basePath string, entries map[string]object.TreeEntry, sessions []SessionFilePaths, groupOpts []WriteCommittedOptions) error {
var checkpointsCount int
var filesTouched []string
var tokenUsage *agent.TokenUsage
var combinedAttribution *InitialAttribution
var hasReview bool
for _, opts := range groupOpts {
checkpointsCount += opts.CheckpointsCount
filesTouched = mergeFilesTouched(filesTouched, opts.FilesTouched)
tokenUsage = aggregateTokenUsage(tokenUsage, opts.TokenUsage)
if opts.CombinedAttribution != nil {
combinedAttribution = opts.CombinedAttribution
}
hasReview = hasReview || opts.HasReview
}
summary := CheckpointSummary{
CheckpointID: lastOpts.CheckpointID,
CLIVersion: versioninfo.Version,
Strategy: lastOpts.Strategy,
Branch: lastOpts.Branch,
CheckpointsCount: checkpointsCount,
FilesTouched: filesTouched,
Sessions: sessions,
TokenUsage: tokenUsage,
CombinedAttribution: combinedAttribution,
HasReview: hasReview,
}
metadataJSON, err := jsonutil.MarshalIndentWithNewline(summary, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal checkpoint summary: %w", err)
}
metadataHash, err := CreateBlobFromContent(s.repo, metadataJSON)
if err != nil {
return err
}
entries[basePath+paths.MetadataFileName] = object.TreeEntry{
Name: basePath + paths.MetadataFileName,
Mode: filemode.Regular,
Hash: metadataHash,
}
return nil
}
// buildMainBatchGroupTree writes every session in one checkpoint group into an
// isolated checkpoint subtree. WriteCommittedMainBatch splices all returned
// checkpoint trees into /main in one pass, instead of rewriting the root and
// shard trees once per checkpoint.
func (s *V2GitStore) buildMainBatchGroupTree(ctx context.Context, rootTreeHash plumbing.Hash, cpID id.CheckpointID, groupOpts []WriteCommittedOptions) (plumbing.Hash, error) {
basePath := cpID.Path() + "/"
checkpointPath := cpID.Path()
entries, err := s.gs.flattenCheckpointEntries(rootTreeHash, checkpointPath)
if err != nil {
return plumbing.ZeroHash, err
}
var existingSummary *CheckpointSummary
if entry, exists := entries[basePath+paths.MetadataFileName]; exists {
if existing, readErr := readJSONFromBlob[CheckpointSummary](s.repo, entry.Hash); readErr == nil {
existingSummary = existing
}
}
// Track the sessions slice as we write so writeCheckpointSummary at the
// end of the group sees a complete picture and findSessionIndex on later
// entries in the group can dedupe against earlier ones.
var sessions []SessionFilePaths
if existingSummary != nil {
sessions = make([]SessionFilePaths, len(existingSummary.Sessions))
copy(sessions, existingSummary.Sessions)
}
for _, opts := range groupOpts {
// findSessionIndex needs a summary whose Sessions length reflects
// what we've written so far in this group.
runningSummary := existingSummary
if len(sessions) > 0 {
runningSummary = &CheckpointSummary{Sessions: sessions}
}
sessionIndex := s.gs.findSessionIndex(ctx, basePath, runningSummary, entries, opts.SessionID)
if sessionIndex == 0 {
if entry, exists := entries[fmt.Sprintf("%s0/%s", basePath, paths.MetadataFileName)]; exists {
if existingMeta, readErr := s.gs.readMetadataFromBlob(entry.Hash); readErr == nil && existingMeta.SessionID != opts.SessionID {
logging.Error(ctx, "refusing v2 checkpoint write: session 0 holds a different sessionID",
slog.String("checkpoint_id", opts.CheckpointID.String()),
slog.String("existing_session_id", existingMeta.SessionID),
slog.String("write_session_id", opts.SessionID),
slog.Bool("existing_summary_nil", existingSummary == nil))
return plumbing.ZeroHash, fmt.Errorf(
"refusing to overwrite session 0 of checkpoint %s: existing session ID %q differs from write session ID %q. The v2 checkpoint tree is inconsistent (session 0 belongs to a different session than this write claims). No automated repair exists for this shape — please report it along with the output of `git ls-tree %s %s/`",
opts.CheckpointID, existingMeta.SessionID, opts.SessionID, paths.V2MainRefName, opts.CheckpointID.Path(),
)
}
}
}
sessionPath := fmt.Sprintf("%s%d/", basePath, sessionIndex)
filePaths, err := s.writeMainSessionToSubdirectory(ctx, opts, sessionPath, entries)
if err != nil {
return plumbing.ZeroHash, err
}
if sessionIndex >= len(sessions) {
grown := make([]SessionFilePaths, sessionIndex+1)
copy(grown, sessions)
sessions = grown
}
sessions[sessionIndex] = filePaths
}
// Last write wins for combinedAttribution / HasReview, matching the
// behavior of N sequential writeCommittedMain calls where each rewrites
// the summary blob.
lastOpts := groupOpts[len(groupOpts)-1]
if err := s.gs.writeCheckpointSummary(lastOpts, basePath, entries, sessions); err != nil {
return plumbing.ZeroHash, err
}
return s.buildCheckpointSubtree(ctx, basePath, entries)
}
func (s *V2GitStore) buildCheckpointSubtree(ctx context.Context, basePath string, entries map[string]object.TreeEntry) (plumbing.Hash, error) {
relEntries := make(map[string]object.TreeEntry, len(entries))
for path, entry := range entries {
relPath := strings.TrimPrefix(path, basePath)
if relPath == path {
continue
}
relEntries[relPath] = entry
}
checkpointTreeHash, err := BuildTreeFromEntries(ctx, s.repo, relEntries)
if err != nil {
return plumbing.ZeroHash, fmt.Errorf("failed to build checkpoint subtree: %w", err)
}
return checkpointTreeHash, nil
}
// UpdateCommitted replaces the prompts and/or transcript for an existing v2
// checkpoint. Called at stop time to finalize checkpoints with the complete
// session transcript.
//
// On /main: replaces prompts and compact transcript (if provided).
// On /full/*: replaces the raw transcript where the session artifacts already
// live, or writes to /full/current if the session has no full artifacts yet.
//
// Returns ErrCheckpointNotFound if the checkpoint doesn't exist on /main.
func (s *V2GitStore) UpdateCommitted(ctx context.Context, opts UpdateCommittedOptions) error {
if opts.CheckpointID.IsEmpty() {
return errors.New("invalid update options: checkpoint ID is required")
}
sessionIndex, err := s.updateCommittedMain(ctx, opts)
if err != nil {
return fmt.Errorf("v2 /main update failed: %w", err)
}
if opts.Transcript.Len() > 0 {
if err := s.updateCommittedFullTranscript(ctx, opts, sessionIndex); err != nil {
return fmt.Errorf("v2 /full/* update failed: %w", err)
}
}
return nil
}
// fullSessionArtifacts describes where a checkpoint session's raw transcript
// artifacts live across the v2 /full/* refs.
type fullSessionArtifacts struct {
RefName plumbing.ReferenceName
Found bool
HasTranscript bool
HasHash bool
}
// HasFullSessionArtifacts reports whether the raw transcript and content hash
// for a checkpoint session exist in any local v2 /full/* ref.
func (s *V2GitStore) HasFullSessionArtifacts(checkpointID id.CheckpointID, sessionIndex int) (bool, error) {
artifacts, err := s.findFullSessionArtifacts(checkpointID, sessionIndex)
if err != nil {
return false, err
}
return artifacts.Found && artifacts.HasTranscript && artifacts.HasHash, nil
}
func (s *V2GitStore) findFullSessionArtifacts(checkpointID id.CheckpointID, sessionIndex int) (fullSessionArtifacts, error) {
refNames, err := s.fullRefSearchOrder()
if err != nil {
return fullSessionArtifacts{}, err
}
var firstFound fullSessionArtifacts
for _, refName := range refNames {
artifacts, inspectErr := s.inspectFullSessionArtifacts(refName, checkpointID, sessionIndex)
if inspectErr != nil {
return fullSessionArtifacts{}, inspectErr
}
if !artifacts.Found {
continue
}
if artifacts.HasTranscript && artifacts.HasHash {
return artifacts, nil
}
if !firstFound.Found {
firstFound = artifacts
}
}
if firstFound.Found {
return firstFound, nil
}
return fullSessionArtifacts{}, nil
}
// FullSessionArtifactsIndex answers "does this session have complete /full/*
// artifacts?" with an O(1) map lookup. Build it once via
// BuildFullSessionArtifactsIndex.
type FullSessionArtifactsIndex map[string]struct{}
// Has reports whether the given session has a complete pair of
// raw_transcript and raw_transcript_hash.txt entries in some /full/* ref.
func (idx FullSessionArtifactsIndex) Has(checkpointID id.CheckpointID, sessionIndex int) bool {
if idx == nil {
return false
}
_, ok := idx[fullArtifactsIndexKey(checkpointID, sessionIndex)]
return ok
}
func fullArtifactsIndexKey(checkpointID id.CheckpointID, sessionIndex int) string {
return string(checkpointID) + "/" + strconv.Itoa(sessionIndex)
}
// BuildFullSessionArtifactsIndex walks every /full/* ref's tree once and
// records sessions whose subtree contains both raw_transcript[/.NNN] and
// raw_transcript_hash.txt. Amortizes per-session HasFullSessionArtifacts
// calls — each of which would otherwise list every git ref and re-walk every
// /full/* tree — across the rest of the run.
func (s *V2GitStore) BuildFullSessionArtifactsIndex() (FullSessionArtifactsIndex, error) {
refNames, err := s.fullRefSearchOrder()
if err != nil {
return nil, err
}
index := make(FullSessionArtifactsIndex)
for _, refName := range refNames {
_, rootTreeHash, refErr := s.GetRefState(refName)
if refErr != nil {
if errors.Is(refErr, plumbing.ErrReferenceNotFound) {
continue
}
return nil, fmt.Errorf("read %s: %w", refName, refErr)
}
rootTree, treeErr := s.repo.TreeObject(rootTreeHash)
if treeErr != nil {
return nil, fmt.Errorf("read %s root tree: %w", refName, treeErr)
}
keys, err := s.listFullSessionsInTree(rootTree)
if err != nil {
return nil, fmt.Errorf("walk %s: %w", refName, err)
}
for _, key := range keys {
index[key] = struct{}{}
}
}
return index, nil
}
func (s *V2GitStore) listFullSessionsInTree(rootTree *object.Tree) ([]string, error) {
var keys []string
for _, shardEntry := range rootTree.Entries {
if shardEntry.Mode != filemode.Dir || len(shardEntry.Name) != 2 {
continue
}
shardTree, err := s.repo.TreeObject(shardEntry.Hash)
if err != nil {
return nil, fmt.Errorf("read shard %s: %w", shardEntry.Name, err)
}
for _, cpEntry := range shardTree.Entries {
if cpEntry.Mode != filemode.Dir {
continue
}
cpTree, err := s.repo.TreeObject(cpEntry.Hash)
if err != nil {
return nil, fmt.Errorf("read checkpoint tree %s/%s: %w", shardEntry.Name, cpEntry.Name, err)
}
cpid := id.CheckpointID(shardEntry.Name + cpEntry.Name)
for _, sessionEntry := range cpTree.Entries {
if sessionEntry.Mode != filemode.Dir {
continue
}
sessionIdx, atoiErr := strconv.Atoi(sessionEntry.Name)
if atoiErr != nil {
continue
}
sessionTree, err := s.repo.TreeObject(sessionEntry.Hash)
if err != nil {
return nil, fmt.Errorf("read session tree %s/%s/%d: %w", shardEntry.Name, cpEntry.Name, sessionIdx, err)
}
if !sessionHasCompleteFullArtifacts(sessionTree.Entries) {
continue
}
keys = append(keys, fullArtifactsIndexKey(cpid, sessionIdx))
}
}
}
return keys, nil
}
func sessionHasCompleteFullArtifacts(entries []object.TreeEntry) bool {
hasTranscript := false
hasHash := false
for _, entry := range entries {
switch {
case entry.Name == paths.V2RawTranscriptFileName,
strings.HasPrefix(entry.Name, paths.V2RawTranscriptFileName+"."):
hasTranscript = true
case entry.Name == paths.V2RawTranscriptHashFileName:
hasHash = true
}
}
return hasTranscript && hasHash
}
func (s *V2GitStore) fullRefSearchOrder() ([]plumbing.ReferenceName, error) {
refNames := []plumbing.ReferenceName{plumbing.ReferenceName(paths.V2FullCurrentRefName)}
archived, err := s.ListArchivedGenerations()
if err != nil {
return nil, err
}
for i := len(archived) - 1; i >= 0; i-- {
refNames = append(refNames, plumbing.ReferenceName(paths.V2FullRefPrefix+archived[i]))
}
return refNames, nil
}
func (s *V2GitStore) inspectFullSessionArtifacts(refName plumbing.ReferenceName, checkpointID id.CheckpointID, sessionIndex int) (fullSessionArtifacts, error) {
_, rootTreeHash, err := s.GetRefState(refName)
if err != nil {
if errors.Is(err, plumbing.ErrReferenceNotFound) {
return fullSessionArtifacts{}, nil
}
return fullSessionArtifacts{}, err
}
rootTree, err := s.repo.TreeObject(rootTreeHash)
if err != nil {
return fullSessionArtifacts{}, fmt.Errorf("failed to read %s tree: %w", refName, err)
}
sessionPath := fmt.Sprintf("%s/%d", checkpointID.Path(), sessionIndex)
sessionTree, err := rootTree.Tree(sessionPath)
if err != nil {
if errors.Is(err, object.ErrDirectoryNotFound) {
return fullSessionArtifacts{}, nil
}
return fullSessionArtifacts{}, fmt.Errorf("failed to read %s session tree %s: %w", refName, sessionPath, err)
}
artifacts := fullSessionArtifacts{RefName: refName, Found: true}
for _, entry := range sessionTree.Entries {
switch {
case entry.Name == paths.V2RawTranscriptFileName:
artifacts.HasTranscript = true
case strings.HasPrefix(entry.Name, paths.V2RawTranscriptFileName+"."):
artifacts.HasTranscript = true
case entry.Name == paths.V2RawTranscriptHashFileName:
artifacts.HasHash = true
}
}
return artifacts, nil
}
// updateCommittedMain updates prompts and compact transcript on the /main ref for an existing checkpoint.
// Returns the session index for coordination with /full/current.
func (s *V2GitStore) updateCommittedMain(ctx context.Context, opts UpdateCommittedOptions) (int, error) {
refName := plumbing.ReferenceName(paths.V2MainRefName)
parentHash, rootTreeHash, err := s.GetRefState(refName)
if err != nil {
return 0, ErrCheckpointNotFound
}
basePath := opts.CheckpointID.Path() + "/"
checkpointPath := opts.CheckpointID.Path()
entries, err := s.gs.flattenCheckpointEntries(rootTreeHash, checkpointPath)
if err != nil {
return 0, err
}
rootMetadataPath := basePath + paths.MetadataFileName
entry, exists := entries[rootMetadataPath]
if !exists {
return 0, ErrCheckpointNotFound
}
summary, err := readJSONFromBlob[CheckpointSummary](s.repo, entry.Hash)
if err != nil {
return 0, fmt.Errorf("failed to read checkpoint summary: %w", err)
}
if len(summary.Sessions) == 0 {
return 0, ErrCheckpointNotFound
}
// Find session index by ID, fall back to latest
sessionIndex := s.gs.findSessionIndex(ctx, basePath, summary, entries, opts.SessionID)
if sessionIndex >= len(summary.Sessions) {
// findSessionIndex returns next-available when not found; fall back to latest
sessionIndex = len(summary.Sessions) - 1
logging.Debug(ctx, "v2 UpdateCommitted: session ID not found, falling back to latest",
slog.String("session_id", opts.SessionID),
slog.String("checkpoint_id", string(opts.CheckpointID)),
slog.Int("fallback_index", sessionIndex),
)
}
sessionPath := fmt.Sprintf("%s%d/", basePath, sessionIndex)
if len(opts.Prompts) > 0 {
promptContent := redactedJoinedPrompts(opts.Prompts)
blobHash, err := CreateBlobFromContent(s.repo, []byte(promptContent))
if err != nil {
return 0, fmt.Errorf("failed to create prompt blob: %w", err)
}
entries[sessionPath+paths.PromptFileName] = object.TreeEntry{
Name: sessionPath + paths.PromptFileName,
Mode: filemode.Regular,
Hash: blobHash,
}
}
// Replace compact transcript if provided
if len(opts.CompactTranscript) > 0 {
blobHash, err := CreateBlobFromContent(s.repo, opts.CompactTranscript)
if err != nil {
return 0, fmt.Errorf("failed to create compact transcript blob: %w", err)
}
entries[sessionPath+paths.CompactTranscriptFileName] = object.TreeEntry{
Name: sessionPath + paths.CompactTranscriptFileName,
Mode: filemode.Regular,
Hash: blobHash,
}
if err := s.writeCompactTranscriptHash(opts.CompactTranscript, sessionPath, entries); err != nil {
return 0, fmt.Errorf("failed to write compact transcript hash: %w", err)
}
// Keep root checkpoint summary in sync with compact artifact paths.
if sessionIndex >= 0 && sessionIndex < len(summary.Sessions) {
summary.Sessions[sessionIndex].Transcript = "/" + sessionPath + paths.CompactTranscriptFileName
summary.Sessions[sessionIndex].ContentHash = "/" + sessionPath + paths.CompactTranscriptHashFileName
summaryBytes, err := jsonutil.MarshalIndentWithNewline(summary, "", " ")
if err != nil {
return 0, fmt.Errorf("failed to marshal checkpoint summary: %w", err)
}
summaryHash, err := CreateBlobFromContent(s.repo, summaryBytes)
if err != nil {
return 0, fmt.Errorf("failed to create checkpoint summary blob: %w", err)
}
entries[rootMetadataPath] = object.TreeEntry{
Name: rootMetadataPath,
Mode: filemode.Regular,
Hash: summaryHash,
}
}
}
newTreeHash, err := s.gs.spliceCheckpointSubtree(ctx, rootTreeHash, opts.CheckpointID, basePath, entries)
if err != nil {
return 0, err
}
authorName, authorEmail := GetGitAuthorFromRepo(s.repo)
commitMsg := fmt.Sprintf("Finalize checkpoint: %s\n", opts.CheckpointID)
if err := s.updateRef(ctx, refName, newTreeHash, parentHash, commitMsg, authorName, authorEmail); err != nil {
return 0, err
}
return sessionIndex, nil
}
// updateCommittedFullTranscript replaces the transcript for a specific checkpoint
// on the /full/* ref where that checkpoint session already lives, while
// preserving other checkpoints' transcripts in the tree. If the session has no
// full-transcript artifacts yet, it writes to /full/current.
func (s *V2GitStore) updateCommittedFullTranscript(ctx context.Context, opts UpdateCommittedOptions, sessionIndex int) error {
refName := plumbing.ReferenceName(paths.V2FullCurrentRefName)
existing, findErr := s.findFullSessionArtifacts(opts.CheckpointID, sessionIndex)
if findErr != nil {
return findErr
}
if existing.Found {
refName = existing.RefName
}
if refName == plumbing.ReferenceName(paths.V2FullCurrentRefName) {
if err := s.ensureRef(ctx, refName); err != nil {
return fmt.Errorf("failed to ensure /full/current ref: %w", err)
}
}
parentHash, rootTreeHash, err := s.GetRefState(refName)
if err != nil {
return err
}
basePath := opts.CheckpointID.Path() + "/"
checkpointPath := opts.CheckpointID.Path()
sessionPath := fmt.Sprintf("%s%d/", basePath, sessionIndex)
// Read existing entries and replace transcript for this checkpoint only
entries, err := s.gs.flattenCheckpointEntries(rootTreeHash, checkpointPath)
if err != nil {
return err
}
// Ignore precompute if invariants are violated — fall back to fresh chunking.
precomputed := opts.PrecomputedBlobs
if precomputed != nil && !precomputed.isUsable() {
precomputed = nil
}
// Short-circuit: if the existing raw_transcript_hash.txt already matches
// the new transcript's sha256, the existing chunk entries represent the
// same content — preserve them and skip chunking + zlib.
rawTranscriptPath := sessionPath + paths.V2RawTranscriptFileName
rawHashPath := sessionPath + paths.V2RawTranscriptHashFileName
var newContentHash string
if precomputed != nil {
newContentHash = precomputed.ContentHash
} else {
newContentHash = fmt.Sprintf("sha256:%x", sha256.Sum256(opts.Transcript.Bytes()))
}
if existing, ok := entries[rawHashPath]; ok {
if blob, err := s.repo.BlobObject(existing.Hash); err == nil {
if rdr, rerr := blob.Reader(); rerr == nil {
existingHash, readErr := io.ReadAll(rdr)
_ = rdr.Close()
if readErr == nil && string(existingHash) == newContentHash {
// Content unchanged — skip tree surgery and ref advance to
// avoid a no-op commit on /full/current. The existing ref
// already references the correct tree.
return nil
}
}
}
}
// Clear existing transcript artifacts for this session path before writing new ones.
// Preserve non-transcript metadata under the same session (e.g., tasks/*).
for key := range entries {
switch {
case key == rawTranscriptPath:
delete(entries, key)
case strings.HasPrefix(key, rawTranscriptPath+"."):
delete(entries, key)
case key == rawHashPath:
delete(entries, key)
}
}
if err := s.writeTranscriptBlobs(ctx, opts.Transcript, opts.Agent, precomputed, sessionPath, entries); err != nil {
return err
}
if err := s.writeContentHashFromPrecompute(newContentHash, precomputed, sessionPath, entries); err != nil {
return err
}
// Splice into existing root tree (preserves other checkpoints' transcripts)
newTreeHash, err := s.gs.spliceCheckpointSubtree(ctx, rootTreeHash, opts.CheckpointID, basePath, entries)
if err != nil {
return err
}
authorName, authorEmail := GetGitAuthorFromRepo(s.repo)
commitMsg := fmt.Sprintf("Finalize checkpoint: %s\n", opts.CheckpointID)
if err := s.updateRef(ctx, refName, newTreeHash, parentHash, commitMsg, authorName, authorEmail); err != nil {
return err
}
if refName == plumbing.ReferenceName(paths.V2FullCurrentRefName) {
s.rotateCurrentIfNeeded(ctx, newTreeHash)
}
return nil
}
// writeCommittedMain writes metadata entries to the /main ref.
// This includes session metadata and prompts — but NOT the raw transcript
// (raw_transcript) or content hash (raw_transcript_hash.txt), which go to /full/current.
// Returns the session index used, so the caller can pass it to writeCommittedFullTranscript.
func (s *V2GitStore) writeCommittedMain(ctx context.Context, opts WriteCommittedOptions) (int, error) {
refName := plumbing.ReferenceName(paths.V2MainRefName)
if err := s.ensureRef(ctx, refName); err != nil {
return 0, fmt.Errorf("failed to ensure /main ref: %w", err)
}
parentHash, rootTreeHash, err := s.GetRefState(refName)
if err != nil {
return 0, err
}
basePath := opts.CheckpointID.Path() + "/"
checkpointPath := opts.CheckpointID.Path()
// Read existing entries at this checkpoint's shard path
entries, err := s.gs.flattenCheckpointEntries(rootTreeHash, checkpointPath)
if err != nil {
return 0, err
}
// Build main session entries (metadata, prompts — no transcript or content hash)
sessionIndex, err := s.writeMainCheckpointEntries(ctx, opts, basePath, entries)
if err != nil {
return 0, err
}
// Splice entries into root tree
newTreeHash, err := s.gs.spliceCheckpointSubtree(ctx, rootTreeHash, opts.CheckpointID, basePath, entries)
if err != nil {
return 0, err
}
commitMsg := fmt.Sprintf("Checkpoint: %s\n", opts.CheckpointID)
if err := s.updateRef(ctx, refName, newTreeHash, parentHash, commitMsg, opts.AuthorName, opts.AuthorEmail); err != nil {
return 0, err
}
return sessionIndex, nil
}
// writeMainCheckpointEntries orchestrates writing session data to the /main ref.
// It mirrors GitStore.writeStandardCheckpointEntries but excludes raw transcript blobs.
// Returns the session index used, for coordination with writeCommittedFullTranscript.
func (s *V2GitStore) writeMainCheckpointEntries(ctx context.Context, opts WriteCommittedOptions, basePath string, entries map[string]object.TreeEntry) (int, error) {
// Read existing summary to get current session count
var existingSummary *CheckpointSummary
metadataPath := basePath + paths.MetadataFileName
if entry, exists := entries[metadataPath]; exists {
existing, err := readJSONFromBlob[CheckpointSummary](s.repo, entry.Hash)
if err == nil {
existingSummary = existing
}
}
// Determine session index
sessionIndex := s.gs.findSessionIndex(ctx, basePath, existingSummary, entries, opts.SessionID)
// Refuse if slot 0 already holds metadata for a DIFFERENT session ID.
// Mirrors GitStore.writeStandardCheckpointEntries: findSessionIndex only
// picks slot 0 when existingSummary is nil or when the summary claims slot 0
// belongs to us, so the actual tree holding session-0 metadata for someone
// else is a corruption / stale-summary shape. Read BEFORE
// writeMainSessionToSubdirectory clears the subtree, or we'd only ever see
// our own write.
if sessionIndex == 0 {
if entry, exists := entries[fmt.Sprintf("%s0/%s", basePath, paths.MetadataFileName)]; exists {
if existingMeta, readErr := s.gs.readMetadataFromBlob(entry.Hash); readErr == nil && existingMeta.SessionID != opts.SessionID {
logging.Error(ctx, "refusing v2 checkpoint write: session 0 holds a different sessionID",
slog.String("checkpoint_id", opts.CheckpointID.String()),
slog.String("existing_session_id", existingMeta.SessionID),
slog.String("write_session_id", opts.SessionID),
slog.Bool("existing_summary_nil", existingSummary == nil))
return 0, fmt.Errorf(
"refusing to overwrite session 0 of checkpoint %s: existing session ID %q differs from write session ID %q. The v2 checkpoint tree is inconsistent (session 0 belongs to a different session than this write claims). No automated repair exists for this shape — please report it along with the output of `git ls-tree %s %s/`",
opts.CheckpointID, existingMeta.SessionID, opts.SessionID, paths.V2MainRefName, opts.CheckpointID.Path(),
)
}
}
}
// Write session files (metadata and prompts — no transcript or content hash)
sessionPath := fmt.Sprintf("%s%d/", basePath, sessionIndex)
sessionFilePaths, err := s.writeMainSessionToSubdirectory(ctx, opts, sessionPath, entries)
if err != nil {
return 0, err
}
// Build the sessions array
var sessions []SessionFilePaths
if existingSummary != nil {
sessions = make([]SessionFilePaths, max(len(existingSummary.Sessions), sessionIndex+1))
copy(sessions, existingSummary.Sessions)
} else {
sessions = make([]SessionFilePaths, 1)
}
sessions[sessionIndex] = sessionFilePaths
// Write root CheckpointSummary
if err := s.gs.writeCheckpointSummary(opts, basePath, entries, sessions); err != nil {
return 0, err
}
return sessionIndex, nil
}
// writeMainSessionToSubdirectory writes a single session's metadata, prompts,
// and compact transcript to a session subdirectory (0/, 1/, 2/, … indexed by
// session order within the checkpoint). The raw transcript (raw_transcript) and its
// content hash (raw_transcript_hash.txt) go to /full/current, not here.
func (s *V2GitStore) writeMainSessionToSubdirectory(_ context.Context, opts WriteCommittedOptions, sessionPath string, entries map[string]object.TreeEntry) (SessionFilePaths, error) {
filePaths := SessionFilePaths{}
// Clear existing entries at this session path
for key := range entries {
if strings.HasPrefix(key, sessionPath) {
delete(entries, key)
}
}
// Write prompts
if len(opts.Prompts) > 0 {
promptContent := redactedJoinedPrompts(opts.Prompts)
blobHash, err := CreateBlobFromContent(s.repo, []byte(promptContent))
if err != nil {
return filePaths, err
}
entries[sessionPath+paths.PromptFileName] = object.TreeEntry{
Name: sessionPath + paths.PromptFileName,
Mode: filemode.Regular,
Hash: blobHash,
}
filePaths.Prompt = "/" + sessionPath + paths.PromptFileName
}
// Write compact transcript (transcript.jsonl) + hash if provided
if len(opts.CompactTranscript) > 0 {
blobHash, err := CreateBlobFromContent(s.repo, opts.CompactTranscript)
if err != nil {
return filePaths, fmt.Errorf("failed to create compact transcript blob: %w", err)
}
entries[sessionPath+paths.CompactTranscriptFileName] = object.TreeEntry{
Name: sessionPath + paths.CompactTranscriptFileName,
Mode: filemode.Regular,
Hash: blobHash,
}
filePaths.Transcript = "/" + sessionPath + paths.CompactTranscriptFileName
if err := s.writeCompactTranscriptHash(opts.CompactTranscript, sessionPath, entries); err != nil {
return filePaths, fmt.Errorf("failed to write compact transcript hash: %w", err)
}
filePaths.ContentHash = "/" + sessionPath + paths.CompactTranscriptHashFileName
}
// Write session metadata
sessionMetadata := CommittedMetadata{
CheckpointID: opts.CheckpointID,
SessionID: opts.SessionID,
Strategy: opts.Strategy,
CreatedAt: checkpointCreatedAt(opts),
Branch: opts.Branch,
CheckpointsCount: opts.CheckpointsCount,
FilesTouched: opts.FilesTouched,
Agent: opts.Agent,
Model: opts.Model,
TurnID: opts.TurnID,
IsTask: opts.IsTask,
ToolUseID: opts.ToolUseID,
TranscriptIdentifierAtStart: opts.TranscriptIdentifierAtStart,
CheckpointTranscriptStart: opts.CompactTranscriptStart,
TokenUsage: opts.TokenUsage,
SessionMetrics: opts.SessionMetrics,
InitialAttribution: opts.InitialAttribution,
PromptAttributions: opts.PromptAttributionsJSON,
Summary: redactSummary(opts.Summary),
CLIVersion: versioninfo.Version,
Kind: opts.Kind,
ReviewSkills: opts.ReviewSkills,
ReviewPrompt: opts.ReviewPrompt,
}
metadataJSON, err := jsonutil.MarshalIndentWithNewline(sessionMetadata, "", " ")
if err != nil {
return filePaths, fmt.Errorf("failed to marshal session metadata: %w", err)
}
metadataHash, err := CreateBlobFromContent(s.repo, metadataJSON)
if err != nil {
return filePaths, err
}
entries[sessionPath+paths.MetadataFileName] = object.TreeEntry{
Name: sessionPath + paths.MetadataFileName,
Mode: filemode.Regular,
Hash: metadataHash,
}
filePaths.Metadata = "/" + sessionPath + paths.MetadataFileName
return filePaths, nil
}
// writeCompactTranscriptHash computes and writes the SHA-256 hash of the compact transcript.
func (s *V2GitStore) writeCompactTranscriptHash(compactTranscript []byte, sessionPath string, entries map[string]object.TreeEntry) error {
hash := fmt.Sprintf("sha256:%x", sha256.Sum256(compactTranscript))
blobHash, err := CreateBlobFromContent(s.repo, []byte(hash))
if err != nil {
return err
}
entries[sessionPath+paths.CompactTranscriptHashFileName] = object.TreeEntry{
Name: sessionPath + paths.CompactTranscriptHashFileName,
Mode: filemode.Regular,
Hash: blobHash,
}
return nil
}
// writeCommittedFullTranscript writes the raw transcript to the /full/current ref.
// Transcripts accumulate across checkpoints — each write splices into the existing
// tree. Generation metadata (generation.json) at the tree root is updated on every