-
Notifications
You must be signed in to change notification settings - Fork 513
Expand file tree
/
Copy pathdiscovery.go
More file actions
1093 lines (1005 loc) · 29 KB
/
Copy pathdiscovery.go
File metadata and controls
1093 lines (1005 loc) · 29 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 parser
import (
"bufio"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
"unicode"
"github.com/tidwall/gjson"
)
// uuidRe matches a standard UUID (8-4-4-4-12 hex) at the end of a rollout filename stem.
var uuidRe = regexp.MustCompile(
`^rollout-.*-([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-` +
`[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$`,
)
const (
copilotStateDir = "session-state"
geminiChatsDir = "chats"
)
// isDirOrSymlink reports whether the entry is a directory or a
// symlink that resolves to a directory. parentDir is needed to
// build the full path for symlink resolution.
func isDirOrSymlink(
entry os.DirEntry, parentDir string,
) bool {
if entry.IsDir() {
return true
}
if entry.Type()&os.ModeSymlink == 0 {
return false
}
fi, err := os.Stat(
filepath.Join(parentDir, entry.Name()),
)
if err != nil || fi == nil {
return false
}
return fi.IsDir()
}
// DiscoveredFile holds a discovered session file.
type DiscoveredFile struct {
Path string
Project string // pre-extracted project name
Agent AgentType // which agent this file belongs to
ForceParse bool // bypass stored-state skips for sidecar-driven refreshes
ProviderSource *SourceRef // provider-owned source identity, when known
ProviderProcess bool // true when this caller may parse via ProviderSource
}
// OpenCodeSourceMode identifies the usable OpenCode storage
// backend found under an OPENCODE_DIR root.
type OpenCodeSourceMode string
const (
OpenCodeSourceNone OpenCodeSourceMode = ""
OpenCodeSourceStorage OpenCodeSourceMode = "storage"
OpenCodeSourceSQLite OpenCodeSourceMode = "sqlite"
)
// OpenCodeSource describes the resolved storage backend for an
// OpenCode root.
type OpenCodeSource struct {
Mode OpenCodeSourceMode
Root string
SessionRoot string
DBPath string
}
// openCodeFormat parameterizes the shared OpenCode storage format by
// the per-agent SQLite filename, the storage/<sessionSubdir> that holds
// session JSON, and the agent label stamped on discovered sessions.
// Kilo is a fork of OpenCode with an identical on-disk layout; MiMoCode
// is a fork that stores sessions under storage/session_diff and a
// mimocode.db SQLite fallback. All share one implementation and differ
// only in these values.
type openCodeFormat struct {
agent AgentType
dbName string
sessionSubdir string
}
var (
openCodeFmt = openCodeFormat{
agent: AgentOpenCode, dbName: "opencode.db", sessionSubdir: "session",
}
kiloFmt = openCodeFormat{
agent: AgentKilo, dbName: "kilo.db", sessionSubdir: "session",
}
mimoFmt = openCodeFormat{
agent: AgentMiMoCode, dbName: "mimocode.db",
sessionSubdir: "session_diff",
}
)
func resolveOpenCodeFormatSource(
f openCodeFormat, root string,
) OpenCodeSource {
if root == "" {
return OpenCodeSource{}
}
sessionRoot := filepath.Join(root, "storage", f.sessionSubdir)
if info, err := os.Stat(sessionRoot); err == nil && info.IsDir() {
return OpenCodeSource{
Mode: OpenCodeSourceStorage,
Root: root,
SessionRoot: sessionRoot,
DBPath: filepath.Join(root, f.dbName),
}
} else if err != nil && !os.IsNotExist(err) {
storageRoot := filepath.Join(root, "storage")
if info, serr := os.Stat(storageRoot); serr == nil && info.IsDir() {
return OpenCodeSource{
Mode: OpenCodeSourceStorage,
Root: root,
SessionRoot: sessionRoot,
DBPath: filepath.Join(root, f.dbName),
}
}
}
dbPath := filepath.Join(root, f.dbName)
if info, err := os.Stat(dbPath); err == nil && !info.IsDir() {
return OpenCodeSource{
Mode: OpenCodeSourceSQLite,
Root: root,
DBPath: dbPath,
}
}
return OpenCodeSource{Root: root}
}
func discoverOpenCodeFormatSessions(
f openCodeFormat, root string,
) []DiscoveredFile {
src := resolveOpenCodeFormatSource(f, root)
if src.Mode != OpenCodeSourceStorage {
return nil
}
var files []DiscoveredFile
entries, err := os.ReadDir(src.SessionRoot)
if err != nil {
return nil
}
for _, entry := range entries {
if !isDirOrSymlink(entry, src.SessionRoot) {
continue
}
projectDir := filepath.Join(src.SessionRoot, entry.Name())
sessionEntries, err := os.ReadDir(projectDir)
if err != nil {
continue
}
for _, sessionEntry := range sessionEntries {
if sessionEntry.IsDir() ||
!strings.HasSuffix(sessionEntry.Name(), ".json") {
continue
}
path := filepath.Join(projectDir, sessionEntry.Name())
files = append(files, DiscoveredFile{
Path: path,
Project: openCodeSessionProject(path),
Agent: f.agent,
})
}
}
sort.Slice(files, func(i, j int) bool {
return files[i].Path < files[j].Path
})
return files
}
func findOpenCodeFormatSourceFile(
f openCodeFormat, root, sessionID string,
) string {
if !IsValidSessionID(sessionID) {
return ""
}
src := resolveOpenCodeFormatSource(f, root)
switch src.Mode {
case OpenCodeSourceStorage:
if entries, err := os.ReadDir(src.SessionRoot); err == nil {
for _, entry := range entries {
if !isDirOrSymlink(entry, src.SessionRoot) {
continue
}
path := filepath.Join(
src.SessionRoot, entry.Name(),
sessionID+".json",
)
if info, err := os.Stat(path); err == nil &&
!info.IsDir() {
return path
}
}
}
if OpenCodeSQLiteSessionExists(src.DBPath, sessionID) {
return OpenCodeSQLiteVirtualPath(src.DBPath, sessionID)
}
return ""
case OpenCodeSourceSQLite:
if OpenCodeSQLiteSessionExists(src.DBPath, sessionID) {
return OpenCodeSQLiteVirtualPath(src.DBPath, sessionID)
}
return ""
default:
return ""
}
}
func openCodeFormatStorageSessionIDs(
f openCodeFormat, root string,
) map[string]struct{} {
src := resolveOpenCodeFormatSource(f, root)
if src.Mode != OpenCodeSourceStorage {
return nil
}
entries, err := os.ReadDir(src.SessionRoot)
if err != nil {
return nil
}
ids := make(map[string]struct{})
for _, entry := range entries {
if !isDirOrSymlink(entry, src.SessionRoot) {
continue
}
projectDir := filepath.Join(src.SessionRoot, entry.Name())
sessionEntries, err := os.ReadDir(projectDir)
if err != nil {
continue
}
for _, sessionEntry := range sessionEntries {
name := sessionEntry.Name()
if sessionEntry.IsDir() ||
!strings.HasSuffix(name, ".json") {
continue
}
id := strings.TrimSuffix(name, ".json")
if id == "" {
continue
}
ids[id] = struct{}{}
}
}
return ids
}
func resolveOpenCodeFormatWatchRoots(
f openCodeFormat, root string,
) []string {
if root == "" {
return nil
}
src := resolveOpenCodeFormatSource(f, root)
switch src.Mode {
case OpenCodeSourceStorage:
if info, err := os.Stat(src.DBPath); err == nil &&
!info.IsDir() {
return []string{root}
}
return []string{filepath.Join(root, "storage")}
case OpenCodeSourceSQLite:
return []string{root}
}
if info, err := os.Stat(root); err == nil && info.IsDir() {
return []string{root}
}
return nil
}
func parseOpenCodeFormatVirtualPath(
dbName, sourcePath string,
) (dbPath, sessionID string, ok bool) {
idx := strings.LastIndex(sourcePath, "#")
if idx <= 0 || idx >= len(sourcePath)-1 {
return "", "", false
}
dbPath = sourcePath[:idx]
sessionID = sourcePath[idx+1:]
if filepath.Base(dbPath) != dbName {
return "", "", false
}
return dbPath, sessionID, true
}
// ResolveOpenCodeSource detects whether an OpenCode root is using
// file-backed storage or legacy SQLite storage.
func ResolveOpenCodeSource(root string) OpenCodeSource {
return resolveOpenCodeFormatSource(openCodeFmt, root)
}
// OpenCodeStorageSessionIDs returns the set of session IDs that
// have a JSON file under storage/session/*/ in the given root.
// Returns nil for non-storage roots. In hybrid roots (storage and
// SQLite both present) the storage transcript is canonical, so
// callers use this to skip duplicate SQLite metas during sync.
func OpenCodeStorageSessionIDs(root string) map[string]struct{} {
return openCodeFormatStorageSessionIDs(openCodeFmt, root)
}
// ResolveOpenCodeWatchRoots returns the directories that should be
// watched for live OpenCode updates under a configured root. Pure
// storage mode targets the storage/ subtree so fsnotify does not
// recurse over unrelated opencode state (binaries, logs, caches),
// while still covering the session/message/part subdirs — including
// ones that OpenCode creates lazily after the watcher starts, since
// the watcher auto-adds new subdirectories on Create events. Hybrid
// storage+SQLite roots and pure SQLite mode watch the root so DB/WAL
// updates are observed too.
func ResolveOpenCodeWatchRoots(root string) []string {
return resolveOpenCodeFormatWatchRoots(openCodeFmt, root)
}
func OpenCodeSQLiteVirtualPath(
dbPath, sessionID string,
) string {
return dbPath + "#" + sessionID
}
func openCodeSessionProject(path string) string {
data, err := os.ReadFile(path)
if err == nil {
if cwd := gjson.GetBytes(data, "directory").Str; cwd != "" {
if project := ExtractProjectFromCwd(cwd); project != "" {
return project
}
}
}
if project := NormalizeName(filepath.Base(filepath.Dir(path))); project != "" {
return project
}
return "unknown"
}
// ResolveKiloSource detects whether a Kilo root is using file-backed
// storage or legacy SQLite storage.
func ResolveKiloSource(root string) OpenCodeSource {
return resolveOpenCodeFormatSource(kiloFmt, root)
}
func KiloStorageSessionIDs(root string) map[string]struct{} {
return openCodeFormatStorageSessionIDs(kiloFmt, root)
}
func ResolveKiloWatchRoots(root string) []string {
return resolveOpenCodeFormatWatchRoots(kiloFmt, root)
}
func KiloSQLiteVirtualPath(dbPath, sessionID string) string {
return OpenCodeSQLiteVirtualPath(dbPath, sessionID)
}
// ResolveMiMoCodeSource detects whether a MiMoCode root is using
// file-backed storage (storage/session_diff) or SQLite storage.
func ResolveMiMoCodeSource(root string) OpenCodeSource {
return resolveOpenCodeFormatSource(mimoFmt, root)
}
func MiMoCodeStorageSessionIDs(root string) map[string]struct{} {
return openCodeFormatStorageSessionIDs(mimoFmt, root)
}
func ResolveMiMoCodeWatchRoots(root string) []string {
return resolveOpenCodeFormatWatchRoots(mimoFmt, root)
}
func MiMoCodeSQLiteVirtualPath(dbPath, sessionID string) string {
return OpenCodeSQLiteVirtualPath(dbPath, sessionID)
}
// ResolveCodexShallowWatchRoots returns directories that should be watched
// shallowly (root only) for live Codex updates, in addition to the recursive
// watch on the configured sessions root. Codex writes title renames to
// session_index.jsonl in the parent of sessions/ and archived_sessions/, so
// that parent must be watched for renames to surface without waiting for the
// periodic sync. A shallow watch avoids recursing over unrelated Codex state
// such as logs.
func ResolveCodexShallowWatchRoots(root string) []string {
parent := filepath.Dir(root)
if parent == "" || parent == "." || parent == root {
return nil
}
return []string{parent}
}
// ClaudeProjectSessionFiles finds all project directories under the
// Claude projects dir and returns their JSONL session files. It is the
// provider-owned enumeration body shared by the Claude provider source
// set (full-sync discovery) and the engine's duplicate-candidate
// expansion. The name carries no legacy entrypoint verb so the
// provider can call it without shimming a Discover* free function.
func ClaudeProjectSessionFiles(projectsDir string) []DiscoveredFile {
entries, err := os.ReadDir(projectsDir)
if err != nil {
return nil
}
var files []DiscoveredFile
for _, entry := range entries {
if !isDirOrSymlink(entry, projectsDir) {
continue
}
projDir := filepath.Join(projectsDir, entry.Name())
sessionFiles, err := os.ReadDir(projDir)
if err != nil {
continue
}
for _, sf := range sessionFiles {
if sf.IsDir() {
continue
}
name := sf.Name()
if !strings.HasSuffix(name, ".jsonl") {
continue
}
stem := strings.TrimSuffix(name, ".jsonl")
if strings.HasPrefix(stem, "agent-") {
continue
}
files = append(files, DiscoveredFile{
Path: filepath.Join(projDir, name),
Project: entry.Name(),
Agent: AgentClaude,
})
}
// Scan session directories for subagent files. Claude workflow
// tools group subagents under nested paths such as
// subagents/workflows/<workflow-id>/agent-<id>.jsonl, so walk the
// whole subagents tree instead of assuming transcripts are direct
// children of subagents/.
for _, sf := range sessionFiles {
if !sf.IsDir() {
continue
}
subagentsDir := filepath.Join(
projDir, sf.Name(), "subagents",
)
_ = filepath.WalkDir(
subagentsDir,
func(path string, sub os.DirEntry, err error) error {
if err != nil || sub.IsDir() {
return nil
}
name := sub.Name()
if !strings.HasPrefix(name, "agent-") ||
!strings.HasSuffix(name, ".jsonl") {
return nil
}
files = append(files, DiscoveredFile{
Path: path,
Project: entry.Name(),
Agent: AgentClaude,
})
return nil
},
)
}
}
sort.Slice(files, func(i, j int) bool {
return files[i].Path < files[j].Path
})
return files
}
// claudeFindSourceFile finds the original JSONL file for a Claude
// session ID by searching all project directories. It is the
// provider-owned lookup body used by the Claude provider source set's
// FindSource. The name carries no legacy entrypoint verb so the
// provider can call it without shimming a Find* free function.
func claudeFindSourceFile(
projectsDir, sessionID string,
) string {
if !IsValidSessionID(sessionID) {
return ""
}
entries, err := os.ReadDir(projectsDir)
if err != nil {
return ""
}
target := sessionID + ".jsonl"
for _, entry := range entries {
if !isDirOrSymlink(entry, projectsDir) {
continue
}
candidate := filepath.Join(
projectsDir, entry.Name(), target,
)
if _, err := os.Stat(candidate); err == nil {
return candidate
}
}
// Subagent files live under session directories:
// <project>/<session>/subagents/**/agent-<id>.jsonl
if strings.HasPrefix(sessionID, "agent-") {
for _, entry := range entries {
if !isDirOrSymlink(entry, projectsDir) {
continue
}
projDir := filepath.Join(
projectsDir, entry.Name(),
)
sessionDirs, err := os.ReadDir(projDir)
if err != nil {
continue
}
for _, sd := range sessionDirs {
if !sd.IsDir() {
continue
}
var found string
subagentsDir := filepath.Join(
projDir, sd.Name(), "subagents",
)
_ = filepath.WalkDir(
subagentsDir,
func(path string, d os.DirEntry, err error) error {
if err != nil || d.IsDir() || d.Name() != target {
return nil
}
found = path
return filepath.SkipAll
},
)
if found != "" {
return found
}
}
}
}
return ""
}
func isCodexSessionFilename(name string) bool {
return strings.HasPrefix(name, "rollout-") &&
strings.HasSuffix(name, ".jsonl")
}
// CodexSessionUUIDFromFilename extracts the canonical session UUID
// from a Codex rollout filename. Returns "" when the filename does
// not match Codex session naming.
func CodexSessionUUIDFromFilename(name string) string {
if !isCodexSessionFilename(name) {
return ""
}
return extractUUIDFromRollout(name)
}
// CodexLayout reports which on-disk layout a Codex session path uses.
type CodexLayout int
const (
CodexLayoutUnknown CodexLayout = iota
CodexLayoutArchivedFlat
CodexLayoutDated
)
// CodexSessionPathInfo parses a Codex path relative to a configured
// root and reports whether it is a valid session path plus its layout
// and canonical session UUID.
func CodexSessionPathInfo(root, path string) (CodexLayout, string, bool) {
root = filepath.Clean(root)
path = filepath.Clean(path)
rel, err := filepath.Rel(root, path)
if err != nil {
return CodexLayoutUnknown, "", false
}
sep := string(filepath.Separator)
if rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+sep) {
return CodexLayoutUnknown, "", false
}
if !strings.HasSuffix(path, ".jsonl") {
return CodexLayoutUnknown, "", false
}
parts := strings.Split(rel, sep)
switch len(parts) {
case 1:
if !isCodexSessionFilename(parts[0]) {
return CodexLayoutUnknown, "", false
}
return CodexLayoutArchivedFlat,
CodexSessionUUIDFromFilename(parts[0]), true
case 4:
if !IsDigits(parts[0]) || !IsDigits(parts[1]) || !IsDigits(parts[2]) {
return CodexLayoutUnknown, "", false
}
if !isCodexSessionFilename(parts[3]) {
return CodexLayoutUnknown, "", false
}
return CodexLayoutDated,
CodexSessionUUIDFromFilename(parts[3]), true
default:
return CodexLayoutUnknown, "", false
}
}
// walkCodexDayDirs traverses a Codex sessions directory with
// year/month/day structure, calling fn for each valid day directory.
// fn returns false to stop traversal.
func walkCodexDayDirs(
root string, fn func(dayPath string) bool,
) {
years, err := os.ReadDir(root)
if err != nil {
return
}
for _, year := range years {
if !year.IsDir() || !IsDigits(year.Name()) {
continue
}
yearPath := filepath.Join(root, year.Name())
months, err := os.ReadDir(yearPath)
if err != nil {
continue
}
for _, month := range months {
if !month.IsDir() || !IsDigits(month.Name()) {
continue
}
monthPath := filepath.Join(yearPath, month.Name())
days, err := os.ReadDir(monthPath)
if err != nil {
continue
}
for _, day := range days {
if !day.IsDir() || !IsDigits(day.Name()) {
continue
}
if !fn(filepath.Join(monthPath, day.Name())) {
return
}
}
}
}
}
// extractUUIDFromRollout extracts the UUID from a Codex filename
// like rollout-{timestamp}-{uuid}.jsonl using regex matching on the
// standard 8-4-4-4-12 hex format.
func extractUUIDFromRollout(filename string) string {
stem := strings.TrimSuffix(filename, ".jsonl")
match := uuidRe.FindStringSubmatch(stem)
if len(match) < 2 {
return ""
}
return match[1]
}
// IsDigits reports whether s is non-empty and contains only
// Unicode digit characters.
func IsDigits(s string) bool {
if s == "" {
return false
}
for _, r := range s {
if !unicode.IsDigit(r) {
return false
}
}
return true
}
// IsValidSessionID reports whether id contains only
// alphanumeric characters, dashes, and underscores.
func IsValidSessionID(id string) bool {
if id == "" {
return false
}
for _, c := range id {
if !isAlphanumOrDashUnderscore(c) {
return false
}
}
return true
}
func isAlphanumOrDashUnderscore(c rune) bool {
return isAlphanum(c) ||
c == '-' || c == '_'
}
func isAlphanum(c rune) bool {
return (c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9')
}
func isValidAmpThreadID(id string) bool {
if !strings.HasPrefix(id, "T-") {
return false
}
if len(id) == len("T-") {
return false
}
if !isAlphanum(rune(id[len("T-")])) {
return false
}
return IsValidSessionID(id)
}
// IsAmpThreadFileName reports whether name matches the Amp
// thread file pattern (T-*.json).
func IsAmpThreadFileName(name string) bool {
if !strings.HasSuffix(name, ".json") {
return false
}
return isValidAmpThreadID(strings.TrimSuffix(name, ".json"))
}
func isGeminiSessionFilename(name string) bool {
return strings.HasPrefix(name, "session-") &&
(strings.HasSuffix(name, ".json") ||
strings.HasSuffix(name, ".jsonl"))
}
// geminiProjectsFile holds the structure of
// ~/.gemini/projects.json.
type geminiProjectsFile struct {
Projects map[string]string `json:"projects"`
}
// geminiTrustedFoldersFile holds the structure of
// ~/.gemini/trustedFolders.json.
type geminiTrustedFoldersFile struct {
TrustedFolders []string `json:"trustedFolders"`
}
// buildGeminiProjectMap reads ~/.gemini/projects.json and
// ~/.gemini/trustedFolders.json to build a map from directory
// name to resolved project name.
// BuildGeminiProjectMap reads Gemini config files and returns
// a map from directory name to resolved project name.
func BuildGeminiProjectMap(
geminiDir string,
) map[string]string {
result := make(map[string]string)
data, err := os.ReadFile(
filepath.Join(geminiDir, "projects.json"),
)
if err == nil {
var pf geminiProjectsFile
if err := json.Unmarshal(data, &pf); err == nil {
addProjectPaths(result, pf.Projects)
}
}
tfData, err := os.ReadFile(
filepath.Join(geminiDir, "trustedFolders.json"),
)
if err == nil {
var tf geminiTrustedFoldersFile
if err := json.Unmarshal(tfData, &tf); err == nil {
paths := make(
map[string]string, len(tf.TrustedFolders),
)
for _, p := range tf.TrustedFolders {
paths[p] = ""
}
addProjectPaths(result, paths)
}
}
return result
}
// addProjectPaths adds hash and name entries for the given
// absolute paths.
func addProjectPaths(
result map[string]string,
paths map[string]string,
) {
sorted := make([]string, 0, len(paths))
for absPath := range paths {
sorted = append(sorted, absPath)
}
sort.Strings(sorted)
for _, absPath := range sorted {
name := paths[absPath]
project := ExtractProjectFromCwd(absPath)
if project == "" {
project = "unknown"
}
hash := geminiPathHash(absPath)
if _, exists := result[hash]; !exists {
result[hash] = project
}
if name != "" {
if _, exists := result[name]; !exists {
result[name] = project
}
}
}
}
// geminiPathHash computes the SHA-256 hex hash of a path,
// matching Gemini CLI's project hash algorithm.
func geminiPathHash(path string) string {
h := sha256.Sum256([]byte(path))
return fmt.Sprintf("%x", h)
}
// isHexHash reports whether s is a 64-character lowercase hex
// string (i.e. a SHA-256 hash).
func isHexHash(s string) bool {
if len(s) != 64 {
return false
}
_, err := hex.DecodeString(s)
return err == nil
}
// resolveGeminiProject maps a tmp/ subdirectory name to a
// project name.
// ResolveGeminiProject maps a tmp/ subdirectory name to a
// project name using the project map.
func ResolveGeminiProject(
dirName string,
projectMap map[string]string,
) string {
if p := projectMap[dirName]; p != "" {
return p
}
if isHexHash(dirName) {
return "unknown"
}
return NormalizeName(dirName)
}
// IsPiSessionFile reads the first non-blank line of path and returns true
// when the JSON type field equals "session". The scanner buffer grows up to
// 64 MiB to match parser.maxLineSize. Leading blank lines are skipped to
// match lineReader behavior.
func IsPiSessionFile(path string) bool {
f, err := os.Open(path)
if err != nil {
return false
}
defer f.Close()
s := bufio.NewScanner(f)
s.Buffer(make([]byte, 0, 64*1024), 64*1024*1024) // up to 64 MiB, matches parser.maxLineSize
for s.Scan() {
line := strings.TrimSpace(s.Text())
if line == "" {
continue
}
return gjson.Get(line, "type").Str == "session"
}
return false
}
// isRegularFile returns true if path exists and is a regular
// file (not a symlink, directory, or other special file).
// IsRegularFile reports whether path is a regular file (not
// a symlink, directory, or special file).
func IsRegularFile(path string) bool {
info, err := os.Lstat(path)
if err != nil {
return false
}
return info.Mode().IsRegular()
}
// isCursorTranscriptExt returns true if the filename has a
// recognized Cursor transcript extension (.txt or .jsonl).
// IsCursorTranscriptExt reports whether the filename has a
// recognized Cursor transcript extension (.txt or .jsonl).
func IsCursorTranscriptExt(name string) bool {
return strings.HasSuffix(name, ".txt") ||
strings.HasSuffix(name, ".jsonl")
}
// isContainedIn returns true if child is a path strictly
// under root. Both paths must be absolute / canonical.
func isContainedIn(child, root string) bool {
rel, err := filepath.Rel(root, child)
if err != nil {
return false
}
return rel != "." && rel != ".." &&
!strings.HasPrefix(rel, ".."+string(filepath.Separator))
}
// discoverVSCodeSessionFiles collects .json and .jsonl
// session files from a directory, preferring .jsonl when
// both exist for the same UUID.
func discoverVSCodeSessionFiles(
dir string, entries []os.DirEntry, project string, agent AgentType,
) []DiscoveredFile {
// Collect UUIDs that have .jsonl files
hasJSONL := make(map[string]bool)
for _, e := range entries {
if e.IsDir() {
continue
}
if uuid, ok := strings.CutSuffix(
e.Name(), ".jsonl",
); ok {
hasJSONL[uuid] = true
}
}
var files []DiscoveredFile
for _, e := range entries {
if e.IsDir() {
continue
}
name := e.Name()
if strings.HasSuffix(name, ".jsonl") {
files = append(files, DiscoveredFile{
Path: filepath.Join(dir, name),
Project: project,
Agent: agent,
})
} else if uuid, ok := strings.CutSuffix(name, ".json"); ok {
// Skip .json if a .jsonl exists for the same UUID
if hasJSONL[uuid] {
continue
}
files = append(files, DiscoveredFile{
Path: filepath.Join(dir, name),
Project: project,
Agent: agent,
})
}
}
return files
}
// discoverVisualStudioCopilotSessionFiles emits one work item per conversation
// found across the trace files in a directory. A single physical trace file
// can hold spans for several conversations, and one conversation can be split
// across rotating trace files, so each conversation is keyed independently and
// represented by the latest trace file that contains it. The work item path is
// a <traceFile>#<conversationID> virtual path so the parser can re-gather that
// conversation's spans from all sibling files.
func discoverVisualStudioCopilotSessionFiles(
dir string, entries []os.DirEntry,
) []DiscoveredFile {
type candidate struct {
path string
mtime time.Time
}
bestByConversation := map[string]candidate{}
var unreadable []DiscoveredFile
for _, entry := range entries {
name := entry.Name()
if entry.IsDir() || !strings.HasSuffix(name, ".jsonl") ||
!strings.Contains(name, "_VSGitHubCopilot_traces") {
continue
}
path := filepath.Join(dir, name)
mtime := time.Time{}
if info, err := entry.Info(); err == nil {
mtime = info.ModTime()
}
ids, err := VisualStudioCopilotFileConversationIDs(path)
if err != nil {
// Enqueue the physical file so the sync worker surfaces the
// read failure instead of silently dropping every
// conversation it might contain.
unreadable = append(unreadable, DiscoveredFile{
Path: path,
Project: "visualstudio",
Agent: AgentVSCopilot,
})
continue
}
for _, id := range ids {
current, ok := bestByConversation[id]
if !ok || mtime.After(current.mtime) ||
(mtime.Equal(current.mtime) && path > current.path) {
bestByConversation[id] = candidate{path: path, mtime: mtime}
}