-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse.go
More file actions
178 lines (153 loc) · 4.46 KB
/
Copy pathparse.go
File metadata and controls
178 lines (153 loc) · 4.46 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
package transcript
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"strings"
"github.com/GrayCodeAI/trace/cli/textutil"
)
// ParseFromBytes parses transcript content from a byte slice.
// Uses bufio.Reader to handle arbitrarily long lines.
func ParseFromBytes(content []byte) ([]Line, error) {
var lines []Line
reader := bufio.NewReader(bytes.NewReader(content))
for {
lineBytes, err := reader.ReadBytes('\n')
if err != nil && err != io.EOF {
return nil, fmt.Errorf("failed to read transcript: %w", err)
}
// Handle empty line or EOF without content
if len(lineBytes) == 0 {
if err == io.EOF {
break
}
continue
}
var line Line
if err := json.Unmarshal(lineBytes, &line); err == nil {
normalizeLineType(&line)
lines = append(lines, line)
}
if err == io.EOF {
break
}
}
return lines, nil
}
// ParseFromFileAtLine reads and parses a transcript file starting from a specific line.
// Uses bufio.Reader to handle arbitrarily long lines (no size limit).
// Returns:
// - lines: parsed transcript lines from startLine onwards (malformed lines skipped)
// - error: any error encountered during reading
//
// The startLine parameter is 0-indexed (startLine=0 reads from the beginning).
// This is useful for incremental parsing when you've already processed some lines.
func ParseFromFileAtLine(path string, startLine int) ([]Line, error) {
file, err := os.Open(path) //nolint:gosec // path is a controlled transcript file path
if err != nil {
return nil, fmt.Errorf("failed to open transcript: %w", err)
}
defer func() { _ = file.Close() }()
var lines []Line
reader := bufio.NewReader(file)
totalLines := 0
for {
lineBytes, err := reader.ReadBytes('\n')
if err != nil && err != io.EOF {
return nil, fmt.Errorf("failed to read transcript: %w", err)
}
// Handle empty line or EOF without content
if len(lineBytes) == 0 {
if err == io.EOF {
break
}
continue
}
// Count all lines for totalLines, but only parse after startLine
if totalLines >= startLine {
var line Line
if err := json.Unmarshal(lineBytes, &line); err == nil {
normalizeLineType(&line)
lines = append(lines, line)
}
}
totalLines++
if err == io.EOF {
break
}
}
return lines, nil
}
// normalizeLineType ensures line.Type is populated for all transcript formats.
// Claude Code uses "type" while Cursor uses "role" for the same purpose.
// When Type is empty but Role is set, we copy Role into Type so all downstream
// consumers can switch on Type uniformly.
func normalizeLineType(line *Line) {
if line.Type == "" && line.Role != "" {
line.Type = line.Role
}
}
// SliceFromLine returns the content starting from line number `startLine` (0-indexed).
// This is used to extract only the checkpoint-specific portion of a cumulative transcript.
// For example, if startLine is 2, lines 0 and 1 are skipped and the result starts at line 2.
// Returns empty slice if startLine exceeds the number of lines.
func SliceFromLine(content []byte, startLine int) []byte {
if len(content) == 0 || startLine <= 0 {
return content
}
// Find the byte offset where startLine begins
lineCount := 0
offset := 0
for i, b := range content {
if b == '\n' {
lineCount++
if lineCount == startLine {
offset = i + 1
break
}
}
}
// If we didn't find enough lines, return empty
if lineCount < startLine {
return nil
}
// If offset is beyond content, return empty
if offset >= len(content) {
return nil
}
return content[offset:]
}
// ExtractUserContent extracts user content from a raw message.
// Handles both string and array content formats.
// IDE-injected context tags (like <ide_opened_file>) are stripped from the result.
// Returns empty string if the message cannot be parsed or contains no text.
func ExtractUserContent(message json.RawMessage) string {
var msg UserMessage
if err := json.Unmarshal(message, &msg); err != nil {
return ""
}
// Handle string content
if str, ok := msg.Content.(string); ok {
return textutil.StripIDEContextTags(str)
}
// Handle array content (only if it contains text blocks)
if arr, ok := msg.Content.([]interface{}); ok {
var texts []string
for _, item := range arr {
if m, ok := item.(map[string]interface{}); ok {
if m["type"] == ContentTypeText {
if text, ok := m["text"].(string); ok {
texts = append(texts, text)
}
}
}
}
if len(texts) > 0 {
return textutil.StripIDEContextTags(strings.Join(texts, "\n\n"))
}
}
return ""
}