-
Notifications
You must be signed in to change notification settings - Fork 513
Expand file tree
/
Copy pathclaude.go
More file actions
2122 lines (1966 loc) · 59 KB
/
Copy pathclaude.go
File metadata and controls
2122 lines (1966 loc) · 59 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
// ABOUTME: Parses Claude Code JSONL session files into structured session data.
// ABOUTME: Detects DAG forks in uuid/parentUuid trees and splits large-gap forks into separate sessions.
package parser
import (
"encoding/json"
"fmt"
"log"
"os"
"path/filepath"
"regexp"
"slices"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/tidwall/gjson"
)
var (
xmlTaskIDRe = regexp.MustCompile(`<task-id>([^<]+)</task-id>`)
xmlToolUseRe = regexp.MustCompile(`<tool-use-id>([^<]+)</tool-use-id>`)
xmlCmdNameRe = regexp.MustCompile(`<command-name>([^<]+)</command-name>`)
xmlCmdMsgRe = regexp.MustCompile(`<command-message>([^<]+)</command-message>`)
xmlCmdArgsRe = regexp.MustCompile(`<command-args>([^<]*)</command-args>`)
xmlCmdStripRe = regexp.MustCompile(`<command-(?:name|message|args)>[^<]*</command-(?:name|message|args)>`)
persistedToolResultPathRe = regexp.MustCompile(`(?m)Full output saved to:\s*(.+)$`)
)
const (
initialScanBufSize = 64 * 1024 // 64KB
maxLineSize = 64 * 1024 * 1024 // 64MB
forkThreshold = 3
)
// dagEntry holds metadata for a single JSONL entry participating
// in the uuid/parentUuid DAG.
type dagEntry struct {
uuid string
parentUuid string
entryType string // "user" or "assistant"
lineIndex int
line string
timestamp time.Time
}
// claudeQueuedCommand is a user message Claude Code persisted as
// type=attachment with attachment.type=queued_command — i.e. a
// prompt the user typed while a tool call was still running.
// These records have no uuid/parentUuid, so we collect them out
// of band and splice them into the message stream by timestamp
// after DAG processing completes.
type claudeQueuedCommand struct {
prompt string
timestamp time.Time
}
// claudeParseWithExclusions parses a Claude Code JSONL session file
// and also returns session IDs intentionally excluded from the
// archive, such as content-free /usage probes. Sync uses those IDs
// during full resync so orphan preservation does not restore rows the
// current parser deliberately dropped. This is the provider-owned
// parse body shared by the Claude provider (both its discovered-session
// Parse path and its ParseUploadedTranscript entry) and the Cowork
// parser (which reuses the Claude transcript format); it carries no
// legacy entrypoint naming so the provider can call it without shimming
// a Parse* free function.
func claudeParseWithExclusions(
path, project, machine string,
) ([]ParseResult, []string, error) {
info, err := os.Stat(path)
if err != nil {
return nil, nil, fmt.Errorf("stat %s: %w", path, err)
}
sessionID := strings.TrimSuffix(filepath.Base(path), ".jsonl")
f, err := os.Open(path)
if err != nil {
return nil, nil, fmt.Errorf("open %s: %w", path, err)
}
defer f.Close()
// First pass: collect all valid lines with metadata.
var (
entries = make([]dagEntry, 0)
queuedCommands []claudeQueuedCommand
hasAnyUUID bool
allHaveUUID bool
parentSessionID string
sourceSessionID string
sourceVersion string
cwd string
gitBranch string
displayName string
foundParentSID bool
lineIndex int
malformedLines int
lastLine string
subagentMap = map[string]string{}
globalStart time.Time
globalEnd time.Time
)
allHaveUUID = true
parentSessionID = claudeCompanionParentSessionID(path, sessionID)
lr := newLineReader(f, maxLineSize)
lastLineFailed := false
for {
line, ok := lr.next()
if !ok {
break
}
lastLine = line
if !gjson.Valid(line) {
malformedLines++
lastLineFailed = true
continue
}
line = resolveClaudePersistedToolResults(path, line)
lastLineFailed = false
entryType := gjson.Get(line, "type").Str
// Extract source version from first line that has it.
if sourceVersion == "" {
if v := gjson.Get(line, "version").Str; v != "" {
sourceVersion = v
}
}
// Track global timestamps from all lines for session
// bounds, including non-message events.
if ts := extractTimestamp(line); !ts.IsZero() {
if globalStart.IsZero() || ts.Before(globalStart) {
globalStart = ts
}
if ts.After(globalEnd) {
globalEnd = ts
}
}
// Collect queue-operation enqueue entries for subagent mapping.
if entryType == "queue-operation" {
if gjson.Get(line, "operation").Str == "enqueue" {
contentStr := gjson.Get(line, "content").Str
if contentStr != "" {
tuid := gjson.Get(contentStr, "tool_use_id").Str
taskID := gjson.Get(contentStr, "task_id").Str
if tuid == "" || taskID == "" {
// Fallback: extract from XML <task-id> and <tool-use-id> tags.
if m := xmlTaskIDRe.FindStringSubmatch(contentStr); m != nil {
taskID = m[1]
}
if m := xmlToolUseRe.FindStringSubmatch(contentStr); m != nil {
tuid = m[1]
}
}
if tuid != "" && taskID != "" {
subagentMap[tuid] = "agent-" + taskID
}
}
}
continue
}
// Collect agent_progress events for subagent mapping.
// Claude Code v2.1+ emits these instead of queue-operation for Agent tool calls.
if entryType == "progress" {
if gjson.Get(line, "data.type").Str == "agent_progress" {
tuid := gjson.Get(line, "parentToolUseID").Str
agentID := gjson.Get(line, "data.agentId").Str
if tuid != "" && agentID != "" {
subagentMap[tuid] = "agent-" + agentID
}
}
continue
}
// Collect queued_command attachments — user messages
// the user typed mid-tool-call. Other attachment types
// (e.g. task_reminder) are intentionally dropped.
if entryType == "attachment" {
if qc, ok := extractQueuedCommand(line); ok {
queuedCommands = append(queuedCommands, qc)
}
continue
}
// Handle system records. /rename local commands update the
// display name; last rename wins (empty arg clears it).
if entryType == "system" {
if name, ok := extractRenameName(
gjson.Get(line, "content").Str,
); ok {
displayName = name
}
continue
}
if entryType != "user" && entryType != "assistant" {
continue
}
// Collect subagent links and cwd/gitBranch from user entries.
if entryType == "user" {
collectToolResultAgentID(line, subagentMap)
if cwd == "" {
cwd = gjson.Get(line, "cwd").Str
}
if gitBranch == "" {
gitBranch = gjson.Get(line, "gitBranch").Str
}
}
// Capture sourceSessionID from first sessionId seen,
// then check whether it differs from the file-derived
// ID to detect parent sessions.
if !foundParentSID {
if sid := gjson.Get(line, "sessionId").Str; sid != "" {
foundParentSID = true
sourceSessionID = sid
if sid != sessionID {
parentSessionID = sid
}
}
}
uuid := gjson.Get(line, "uuid").Str
parentUuid := gjson.Get(line, "parentUuid").Str
if uuid != "" {
hasAnyUUID = true
} else {
allHaveUUID = false
}
ts := extractTimestamp(line)
entries = append(entries, dagEntry{
uuid: uuid,
parentUuid: parentUuid,
entryType: entryType,
lineIndex: lineIndex,
line: line,
timestamp: ts,
})
lineIndex++
}
if err := lr.Err(); err != nil {
return nil, nil, fmt.Errorf("reading %s: %w", path, err)
}
// Detect truncation: last line is non-empty, invalid JSON,
// AND the file did not end with a newline. A newline-
// terminated invalid line is just a complete malformed
// record, not a truncated write.
isTruncated := lastLine != "" &&
strings.TrimSpace(lastLine) != "" &&
!gjson.Valid(lastLine) &&
!fileEndsWithNewline(f, info.Size())
// Merge consecutive assistant entries that share the same
// message.id. Claude Code writes both cumulative streaming
// snapshots and additive chunks for one response under the same
// provider message id. Keep final metadata/token usage while
// preserving distinct content blocks from the whole run.
entries = mergeClaudeAssistantMessageChunks(entries)
fileInfo := FileInfo{
Path: path,
Size: info.Size(),
Mtime: info.ModTime().UnixNano(),
}
meta := claudeSessionMeta{
sourceSessionID: sourceSessionID,
sourceVersion: sourceVersion,
cwd: cwd,
gitBranch: gitBranch,
displayName: displayName,
malformedLines: malformedLines,
isTruncated: isTruncated,
}
var (
results []ParseResult
parseErr error
)
// If all user/assistant entries have uuids, use DAG-aware processing.
if hasAnyUUID && allHaveUUID {
results, parseErr = parseDAG(
entries, sessionID, project, machine,
parentSessionID, fileInfo, subagentMap,
globalStart, globalEnd, meta,
)
} else {
// Fall back to linear processing.
results, parseErr = parseLinear(
entries, sessionID, project, machine,
parentSessionID, fileInfo, subagentMap,
globalStart, globalEnd, meta,
)
}
if parseErr != nil {
return nil, nil, parseErr
}
// Splice queued_command attachments into the main session
// by timestamp. Attachments have no uuid/parentUuid and so
// can't participate in DAG fork detection; they belong to
// the original conversation timeline (results[0]).
if len(queuedCommands) > 0 && len(results) > 0 {
results[0] = applyQueuedCommands(results[0], queuedCommands)
}
// Classify termination status for each result. All forks
// from a single file share lastLineFailed because a
// truncated tail affects every branch. The stop_reason is
// pulled from the last assistant message in each branch so
// "awaiting_user" can be distinguished from a generic clean
// termination.
for i := range results {
results[i].Session.TerminationStatus = Classify(
results[i].Messages,
lastAssistantStopReason(results[i].Messages),
lastLineFailed,
)
}
// Drop content-free /usage probe sessions (e.g. CodexBar's
// ClaudeProbe) after the queued-command splice so both inline
// and queued /usage prompts are visible to the check. They never
// enter the archive.
kept := results[:0]
var excluded []string
for _, r := range results {
if isUsageProbeSession(r.Messages) {
excluded = append(excluded, r.Session.ID)
continue
}
kept = append(kept, r)
}
return kept, excluded, nil
}
// lastAssistantStopReason returns the StopReason of the most
// recent assistant message in the slice, or "" when there is
// none. Used by Classify to decide between awaiting_user and
// clean for sessions that ended without an orphan tool_use.
func lastAssistantStopReason(messages []ParsedMessage) string {
for _, v := range slices.Backward(messages) {
if v.Role == RoleAssistant {
return v.StopReason
}
}
return ""
}
// claudeParseSessionFrom parses only new lines from a Claude JSONL
// file starting at the given byte offset. Returns only the newly
// parsed messages (with ordinals starting at startOrdinal) and the
// latest timestamp. Fork detection is skipped — new entries are
// processed linearly. Used by the Claude provider for incremental
// re-parsing of append-only session files. ErrDAGDetected is returned
// when appended lines contain uuid fields that require DAG-aware fork
// detection, which incremental parsing cannot handle. This is the
// provider-owned incremental body; it carries no legacy entrypoint
// naming so the provider can call it without shimming a Parse* free
// function.
var ErrDAGDetected = fmt.Errorf(
"incremental parse: DAG uuid detected",
)
// ErrClaudeIncrementalNeedsFullParse signals that appended Claude
// lines contain content the incremental path cannot stitch into
// already-stored rows (subagent linkage updates from
// toolUseResult.agentId, or same-message.id chunk merging).
var ErrClaudeIncrementalNeedsFullParse = fmt.Errorf(
"incremental parse: appended Claude lines require full parse",
)
func claudeParseSessionFrom(
path string,
offset int64,
startOrdinal int,
lastEntryUUID string,
) ([]ParsedMessage, time.Time, int64, error) {
var (
entries []dagEntry
queuedCommands []claudeQueuedCommand
subagentMap = make(map[string]string)
lineIndex = startOrdinal
// Track latest timestamp from all lines, including
// non-message events (progress, queue-operation) so
// callers can update ended_at even when no new
// messages are found.
latestTS time.Time
sawRename bool
)
consumed, err := readJSONLFrom(
path, offset, func(line string) {
line = resolveClaudePersistedToolResults(path, line)
if ts := extractTimestamp(line); !ts.IsZero() {
if ts.After(latestTS) {
latestTS = ts
}
}
entryType := gjson.Get(line, "type").Str
if entryType == "system" {
if _, ok := extractRenameName(
gjson.Get(line, "content").Str,
); ok {
sawRename = true
}
return
}
if entryType == "attachment" {
if qc, ok := extractQueuedCommand(line); ok {
queuedCommands = append(queuedCommands, qc)
}
return
}
if entryType == "queue-operation" {
if gjson.Get(line, "operation").Str == "enqueue" {
contentStr := gjson.Get(line, "content").Str
if contentStr != "" {
tuid := gjson.Get(contentStr, "tool_use_id").Str
taskID := gjson.Get(contentStr, "task_id").Str
if tuid == "" || taskID == "" {
if m := xmlTaskIDRe.FindStringSubmatch(contentStr); m != nil {
taskID = m[1]
}
if m := xmlToolUseRe.FindStringSubmatch(contentStr); m != nil {
tuid = m[1]
}
}
if tuid != "" && taskID != "" {
subagentMap[tuid] = "agent-" + taskID
}
}
}
return
}
if entryType == "progress" {
if gjson.Get(line, "data.type").Str == "agent_progress" {
tuid := gjson.Get(line, "parentToolUseID").Str
agentID := gjson.Get(line, "data.agentId").Str
if tuid != "" && agentID != "" {
subagentMap[tuid] = "agent-" + agentID
}
}
return
}
if entryType != "user" &&
entryType != "assistant" {
return
}
ts := extractTimestamp(line)
entries = append(entries, dagEntry{
uuid: gjson.Get(line, "uuid").Str,
parentUuid: gjson.Get(line, "parentUuid").Str,
entryType: entryType,
lineIndex: lineIndex,
line: line,
timestamp: ts,
})
lineIndex++
},
)
if err != nil {
return nil, time.Time{}, 0, fmt.Errorf(
"reading claude %s from offset %d: %w",
path, offset, err,
)
}
// A rename-only append produces no entries and no queued commands, so
// the empty-entries early return below would silently succeed. Check
// first and force a full parse so the display name is persisted.
if sawRename {
return nil, time.Time{}, 0, ErrClaudeIncrementalNeedsFullParse
}
// Queue/progress events can repair subagent linkage on an already-stored
// tool call. If the mapped tool_use_id is not introduced in this append,
// incremental parsing would advance file_size without updating that row.
if needsClaudeFullParseForSubagentMap(entries, subagentMap) {
return nil, time.Time{}, 0, ErrClaudeIncrementalNeedsFullParse
}
if len(entries) == 0 && len(queuedCommands) == 0 {
return nil, latestTS, consumed, nil
}
// Detect forks: if any entry's parentUuid doesn't
// match the previous entry's uuid, the appended data
// contains a branch that requires full DAG processing.
if hasDAGFork(entries, lastEntryUUID) {
return nil, time.Time{}, 0, ErrDAGDetected
}
// Subagent linkage updates (toolUseResult.agentId) and
// same-message.id chunk merging both need state the full
// parser builds across the whole file. Bail to a full parse
// when appended lines contain either.
if needsClaudeFullParse(entries) {
return nil, time.Time{}, 0,
ErrClaudeIncrementalNeedsFullParse
}
msgs, _, endedAt := extractMessagesFrom(
entries, startOrdinal,
)
annotateSubagentSessions(msgs, subagentMap)
if len(queuedCommands) > 0 {
msgs = mergeQueuedCommands(
msgs, queuedCommands, startOrdinal,
)
for _, qc := range queuedCommands {
if qc.timestamp.After(endedAt) {
endedAt = qc.timestamp
}
}
}
// Use the latest timestamp from all lines (including
// non-message events) if it's later than what
// extractMessagesFrom found.
if latestTS.After(endedAt) {
endedAt = latestTS
}
return msgs, endedAt, consumed, nil
}
// needsClaudeFullParse returns true when appended entries contain
// either a tool_result with toolUseResult.agentId (whose linkage
// must update an already-stored tool_call row) or a consecutive
// same-message.id assistant run (whose chunks the full parser
// merges into one message). Both cases require a full re-parse.
func needsClaudeFullParse(entries []dagEntry) bool {
toolUseIDs := make(map[string]struct{})
var prevAssistantMID string
for _, e := range entries {
if e.entryType == "user" {
if gjson.Get(e.line, "toolUseResult.agentId").Str != "" {
return true
}
content := gjson.Get(e.line, "message.content")
if content.IsArray() {
unmatched := false
content.ForEach(func(_, part gjson.Result) bool {
if part.Get("type").Str != "tool_result" {
return true
}
toolUseID := part.Get("tool_use_id").Str
if toolUseID == "" {
return true
}
if _, ok := toolUseIDs[toolUseID]; !ok {
unmatched = true
return false
}
return true
})
if unmatched {
return true
}
}
}
if e.entryType == "assistant" {
mid := gjson.Get(e.line, "message.id").Str
if mid != "" && mid == prevAssistantMID {
return true
}
content := gjson.Get(e.line, "message.content")
if content.IsArray() {
content.ForEach(func(_, part gjson.Result) bool {
if part.Get("type").Str != "tool_use" {
return true
}
if toolUseID := part.Get("id").Str; toolUseID != "" {
toolUseIDs[toolUseID] = struct{}{}
}
return true
})
}
prevAssistantMID = mid
continue
}
prevAssistantMID = ""
}
return false
}
func needsClaudeFullParseForSubagentMap(
entries []dagEntry, subagentMap map[string]string,
) bool {
if len(subagentMap) == 0 {
return false
}
appendedToolUseIDs := make(map[string]struct{})
for _, e := range entries {
if e.entryType != "assistant" {
continue
}
content := gjson.Get(e.line, "message.content")
if !content.IsArray() {
continue
}
content.ForEach(func(_, part gjson.Result) bool {
if part.Get("type").Str != "tool_use" {
return true
}
if toolUseID := part.Get("id").Str; toolUseID != "" {
appendedToolUseIDs[toolUseID] = struct{}{}
}
return true
})
}
for toolUseID := range subagentMap {
if _, ok := appendedToolUseIDs[toolUseID]; !ok {
return true
}
}
return false
}
// hasDAGFork returns true if the entries contain a fork —
// i.e. any entry whose parentUuid doesn't point to the
// immediately preceding entry's uuid. Linear UUID chains
// (each entry parenting the next) are safe for incremental
// parsing; forks require full DAG processing.
func hasDAGFork(entries []dagEntry, lastEntryUUID string) bool {
lastUUID := lastEntryUUID
for _, e := range entries {
if e.uuid == "" {
continue // non-UUID entries are always linear
}
if lastUUID != "" &&
e.parentUuid != lastUUID {
return true
}
lastUUID = e.uuid
}
return false
}
// extractMessagesFrom is like extractMessages but uses a
// custom starting ordinal for incremental parsing.
func extractMessagesFrom(
entries []dagEntry, startOrdinal int,
) ([]ParsedMessage, time.Time, time.Time) {
var (
messages []ParsedMessage
startedAt time.Time
endedAt time.Time
ordinal = startOrdinal
)
for _, e := range entries {
if !e.timestamp.IsZero() {
if startedAt.IsZero() {
startedAt = e.timestamp
}
endedAt = e.timestamp
}
// Detect compact summaries before the user/assistant
// gates: Claude can emit isCompactSummary=true with
// either top-level type, and the record must always
// be persisted as a system boundary regardless.
if gjson.Get(e.line, "isCompactSummary").Bool() {
summary := extractCompactSummary(e.line)
messages = append(messages, ParsedMessage{
Ordinal: ordinal,
Role: RoleAssistant,
Content: summary,
Timestamp: e.timestamp,
IsSystem: true,
ContentLength: len(summary),
SourceType: "system",
SourceSubtype: "compact_boundary",
SourceUUID: e.uuid,
SourceParentUUID: e.parentUuid,
IsSidechain: gjson.Get(e.line, "isSidechain").Bool(),
IsCompactBoundary: true,
})
ordinal++
continue
}
if e.entryType == "user" {
if gjson.Get(e.line, "isMeta").Bool() {
continue
}
}
content := gjson.Get(e.line, "message.content")
text, thinkingText, hasThinking, hasToolUse, tcs, trs :=
ExtractTextContent(content)
// Convert command/skill invocation XML into readable
// text (e.g. "/roborev-fix 450"). If the content
// looks like a command envelope but can't be
// normalized, skip it to avoid raw XML in transcripts.
if e.entryType == "user" {
if cmdText, ok := extractCommandText(text); ok {
text = cmdText
} else if isCommandEnvelope(text) {
continue
}
}
if strings.TrimSpace(text) == "" && len(trs) == 0 {
continue
}
if e.entryType == "user" {
if subtype := classifyClaudeSystemMessage(text); subtype != "" {
// Preserve Role=user so analytics that compute
// turn-cycle/throughput on role alone (see
// internal/db/analytics.go) don't count these as
// assistant replies. is_system + source_subtype
// let the UI and filters route them correctly.
messages = append(messages, ParsedMessage{
Ordinal: ordinal,
Role: RoleUser,
Content: text,
Timestamp: e.timestamp,
IsSystem: true,
ContentLength: len(text),
SourceType: "system",
SourceSubtype: subtype,
SourceUUID: e.uuid,
SourceParentUUID: e.parentUuid,
IsSidechain: gjson.Get(e.line, "isSidechain").Bool(),
})
ordinal++
continue
}
// Skip unclassified noise (e.g. non-caveat
// <local-command-*> envelopes).
if isClaudeSystemMessage(text) {
continue
}
}
msg := ParsedMessage{
Ordinal: ordinal,
Role: RoleType(e.entryType),
Content: text,
ThinkingText: thinkingText,
Timestamp: e.timestamp,
HasThinking: hasThinking,
HasToolUse: hasToolUse,
ContentLength: len(text),
ToolCalls: tcs,
ToolResults: trs,
SourceType: e.entryType,
SourceUUID: e.uuid,
SourceParentUUID: e.parentUuid,
IsSidechain: gjson.Get(e.line, "isSidechain").Bool(),
tokenPresenceKnown: e.entryType == "assistant",
}
if e.entryType == "assistant" {
extractClaudeTokenFields(&msg, e.line)
msg.StopReason = gjson.Get(e.line, "message.stop_reason").Str
}
messages = append(messages, msg)
ordinal++
}
return messages, startedAt, endedAt
}
// claudeSessionMeta holds source metadata extracted during the
// main parse loop and applied to all resulting ParsedSessions.
type claudeSessionMeta struct {
sourceSessionID string
sourceVersion string
cwd string
gitBranch string
displayName string
malformedLines int
isTruncated bool
}
// applyTo sets source metadata fields on a ParsedSession.
func (m claudeSessionMeta) applyTo(sess *ParsedSession) {
sess.SourceSessionID = m.sourceSessionID
sess.SourceVersion = m.sourceVersion
sess.Cwd = m.cwd
sess.GitBranch = m.gitBranch
sess.SessionName = m.displayName
sess.MalformedLines = m.malformedLines
sess.IsTruncated = m.isTruncated
}
// parseLinear processes entries sequentially without DAG awareness.
func parseLinear(
entries []dagEntry,
sessionID, project, machine, parentSessionID string,
fileInfo FileInfo,
subagentMap map[string]string,
globalStart, globalEnd time.Time,
meta claudeSessionMeta,
) ([]ParseResult, error) {
messages, startedAt, endedAt := extractMessages(entries)
startedAt = earlierTime(globalStart, startedAt)
endedAt = laterTime(globalEnd, endedAt)
annotateSubagentSessions(messages, subagentMap)
// Promoted system messages (continuation/resume/interrupted/
// task_notification/stop_hook) carry Role=user so role-keyed
// analytics ignore them, but they are not real user turns;
// firstMessageAndUserCount skips them when computing
// user_message_count / first_message. It also skips leading
// /clear and /effort command envelopes so the sidebar shows
// the next real message instead of the command.
firstMsg, userCount := firstMessageAndUserCount(messages)
sess := ParsedSession{
ID: sessionID,
Project: project,
Machine: machine,
Agent: AgentClaude,
ParentSessionID: parentSessionID,
FirstMessage: firstMsg,
StartedAt: startedAt,
EndedAt: endedAt,
MessageCount: len(messages),
UserMessageCount: userCount,
File: fileInfo,
}
meta.applyTo(&sess)
accumulateMessageTokenUsage(&sess, messages)
return []ParseResult{{Session: sess, Messages: messages}}, nil
}
// parseDAG builds a parent->children adjacency map and walks the
// tree to detect fork points. Large-gap forks produce separate
// ParseResults; small-gap retries follow the latest branch.
func parseDAG(
entries []dagEntry,
sessionID, project, machine, parentSessionID string,
fileInfo FileInfo,
subagentMap map[string]string,
globalStart, globalEnd time.Time,
meta claudeSessionMeta,
) ([]ParseResult, error) {
// Build parent -> children ordered by line position and
// collect the set of all uuids for connectivity checks.
children := make(map[string][]int, len(entries))
uuidSet := make(map[string]struct{}, len(entries))
var roots []int
for i, e := range entries {
if e.uuid != "" {
uuidSet[e.uuid] = struct{}{}
}
if e.parentUuid == "" {
roots = append(roots, i)
} else {
children[e.parentUuid] = append(children[e.parentUuid], i)
}
}
// A well-formed DAG has exactly one root and all parentUuid
// references resolve to an existing entry's uuid. If not,
// fall back to linear parsing to avoid dropping messages.
if len(roots) != 1 {
return parseLinear(
entries, sessionID, project, machine,
parentSessionID, fileInfo, subagentMap,
globalStart, globalEnd, meta,
)
}
for _, e := range entries {
if e.parentUuid != "" {
if _, ok := uuidSet[e.parentUuid]; !ok {
return parseLinear(
entries, sessionID, project, machine,
parentSessionID, fileInfo, subagentMap,
globalStart, globalEnd, meta,
)
}
}
}
// Walk from the root, collecting branches.
// branches[0] is the main branch; subsequent entries are forks.
type branch struct {
indices []int
parentID string // immediate parent session ID
}
var branches []branch
// walkBranch follows the DAG from a starting index, collecting
// all entries on the chosen path. At fork points, it either
// follows the latest child (small gap) or splits (large gap).
// ownerID is the session ID of the branch that owns this walk.
var walkBranch func(startIdx int, ownerID string) []int
var forkBranches []branch
walkBranch = func(startIdx int, ownerID string) []int {
var path []int
current := startIdx
for current >= 0 {
path = append(path, current)
uuid := entries[current].uuid
kids := children[uuid]
if len(kids) == 0 {
break
}
if len(kids) == 1 {
current = kids[0]
continue
}
// Fork point: count user turns on first child's branch.
firstChildTurns := countUserTurns(entries, children, kids[0])
if firstChildTurns <= forkThreshold {
// Small-gap retry: follow the last child.
current = kids[len(kids)-1]
} else {
// Large-gap fork: follow first child on main,
// collect other children as fork branches.
for _, kid := range kids[1:] {
forkSID := sessionID + "-" +
entries[kid].uuid
forkPath := walkBranch(kid, forkSID)
forkBranches = append(
forkBranches,
branch{
indices: forkPath,
parentID: ownerID,
},
)
}
current = kids[0]
}
}
return path
}
mainPath := walkBranch(roots[0], sessionID)
branches = append(
branches,
branch{indices: mainPath, parentID: parentSessionID},
)
branches = append(branches, forkBranches...)
// Build results for each branch.
var results []ParseResult
for i, b := range branches {
branchEntries := make([]dagEntry, len(b.indices))
for j, idx := range b.indices {
branchEntries[j] = entries[idx]
}
messages, startedAt, endedAt := extractMessages(branchEntries)
// Main session uses global bounds to capture timestamps
// from non-message events (e.g. queue-operation).
if i == 0 {
startedAt = earlierTime(globalStart, startedAt)
endedAt = laterTime(globalEnd, endedAt)
}
annotateSubagentSessions(messages, subagentMap)
firstMsg, userCount := firstMessageAndUserCount(messages)
sid := sessionID
pSID := b.parentID
relType := RelationshipType("")
if i > 0 {
// Fork session: ID derived from first entry's uuid,
// parent is the branch that forked.
firstEntry := entries[b.indices[0]]
sid = sessionID + "-" + firstEntry.uuid
relType = RelFork
}
sess := ParsedSession{
ID: sid,
Project: project,
Machine: machine,
Agent: AgentClaude,
ParentSessionID: pSID,