|
| 1 | +package retromine |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "strings" |
| 8 | +) |
| 9 | + |
| 10 | +// Adapters perform the lossy projection from one host's transcript format |
| 11 | +// into neutral events. Lossiness is one-directional by design: an adapter may |
| 12 | +// SKIP entries it does not understand (host formats grow shapes constantly), |
| 13 | +// but a line that fails to parse as the format at all is a typed error — |
| 14 | +// mis-parsing must never silently become "no recurrence found". |
| 15 | +// control-law: retro-derivation-is-offline-and-deterministic |
| 16 | + |
| 17 | +// Format names for ParseTranscript. |
| 18 | +const ( |
| 19 | + FormatNeutral = "events" |
| 20 | + FormatClaudeCode = "claudecode" |
| 21 | + FormatPlaintext = "plaintext" |
| 22 | +) |
| 23 | + |
| 24 | +// ParseTranscript dispatches to the named adapter, or sniffs the format from |
| 25 | +// content when format is empty: a JSON object line with a "role" field is the |
| 26 | +// neutral format, one with "type"/"message" is a Claude Code session line, |
| 27 | +// anything else is plain text. |
| 28 | +func ParseTranscript(format, source string, content []byte) ([]Event, error) { |
| 29 | + if format == "" { |
| 30 | + format = sniffFormat(content) |
| 31 | + } |
| 32 | + switch format { |
| 33 | + case FormatNeutral: |
| 34 | + return ParseNeutralEvents(source, strings.NewReader(string(content))) |
| 35 | + case FormatClaudeCode: |
| 36 | + return ParseClaudeCodeSession(source, strings.NewReader(string(content))) |
| 37 | + case FormatPlaintext: |
| 38 | + return ParsePlaintextTranscript(source, strings.NewReader(string(content))) |
| 39 | + default: |
| 40 | + return nil, fmt.Errorf("unknown transcript format %q (supported: events, claudecode, plaintext)", format) |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +func sniffFormat(content []byte) string { |
| 45 | + for _, line := range strings.Split(string(content), "\n") { |
| 46 | + line = strings.TrimSpace(line) |
| 47 | + if line == "" { |
| 48 | + continue |
| 49 | + } |
| 50 | + if !strings.HasPrefix(line, "{") { |
| 51 | + return FormatPlaintext |
| 52 | + } |
| 53 | + var probe map[string]json.RawMessage |
| 54 | + if err := json.Unmarshal([]byte(line), &probe); err != nil { |
| 55 | + return FormatPlaintext |
| 56 | + } |
| 57 | + if _, ok := probe["role"]; ok { |
| 58 | + return FormatNeutral |
| 59 | + } |
| 60 | + return FormatClaudeCode |
| 61 | + } |
| 62 | + return FormatPlaintext |
| 63 | +} |
| 64 | + |
| 65 | +// claudeCodeLine is the subset of a Claude Code session JSONL entry the |
| 66 | +// projection needs. Message content is either a plain string or an array of |
| 67 | +// typed blocks; only text blocks carry conversational text, and tool_result |
| 68 | +// blocks mark tool output. |
| 69 | +type claudeCodeLine struct { |
| 70 | + Type string `json:"type"` |
| 71 | + SessionID string `json:"sessionId"` |
| 72 | + Timestamp string `json:"timestamp"` |
| 73 | + Message struct { |
| 74 | + Role string `json:"role"` |
| 75 | + Content json.RawMessage `json:"content"` |
| 76 | + } `json:"message"` |
| 77 | +} |
| 78 | + |
| 79 | +// ParseClaudeCodeSession projects a Claude Code session JSONL stream into |
| 80 | +// neutral events. Entries whose type is not user/assistant (summaries, |
| 81 | +// hooks, system reminders) are skipped — projection is lossy — but a line |
| 82 | +// that is not valid JSON is a typed error. |
| 83 | +func ParseClaudeCodeSession(source string, r io.Reader) ([]Event, error) { |
| 84 | + scanner := newLineScanner(r) |
| 85 | + events := []Event{} |
| 86 | + line := 0 |
| 87 | + for scanner.Scan() { |
| 88 | + line++ |
| 89 | + raw := strings.TrimSpace(scanner.Text()) |
| 90 | + if raw == "" { |
| 91 | + continue |
| 92 | + } |
| 93 | + var entry claudeCodeLine |
| 94 | + if err := json.Unmarshal([]byte(raw), &entry); err != nil { |
| 95 | + return nil, fmt.Errorf("parse claudecode session %s line %d: %w", source, line, err) |
| 96 | + } |
| 97 | + role := "" |
| 98 | + switch entry.Type { |
| 99 | + case "user": |
| 100 | + role = RoleOperator |
| 101 | + case "assistant": |
| 102 | + role = RoleAgent |
| 103 | + default: |
| 104 | + continue |
| 105 | + } |
| 106 | + text, isToolPayload := claudeCodeText(entry.Message.Content) |
| 107 | + if isToolPayload { |
| 108 | + role = RoleTool |
| 109 | + } |
| 110 | + if strings.TrimSpace(text) == "" { |
| 111 | + continue |
| 112 | + } |
| 113 | + sessionID := entry.SessionID |
| 114 | + if sessionID == "" { |
| 115 | + sessionID = source |
| 116 | + } |
| 117 | + events = append(events, Event{ |
| 118 | + Source: source, SessionID: sessionID, Timestamp: entry.Timestamp, |
| 119 | + Role: role, Text: text, |
| 120 | + }) |
| 121 | + } |
| 122 | + if err := scanner.Err(); err != nil { |
| 123 | + return nil, fmt.Errorf("read claudecode session %s: %w", source, err) |
| 124 | + } |
| 125 | + return assignSessionIndexes(events), nil |
| 126 | +} |
| 127 | + |
| 128 | +// claudeCodeText extracts conversational text from a message content value. |
| 129 | +// The bool reports that the content was ONLY tool payload (tool results), |
| 130 | +// which projects as RoleTool so it never counts as an operator instruction. |
| 131 | +func claudeCodeText(content json.RawMessage) (string, bool) { |
| 132 | + if len(content) == 0 { |
| 133 | + return "", false |
| 134 | + } |
| 135 | + var plain string |
| 136 | + if err := json.Unmarshal(content, &plain); err == nil { |
| 137 | + return plain, false |
| 138 | + } |
| 139 | + var blocks []struct { |
| 140 | + Type string `json:"type"` |
| 141 | + Text string `json:"text"` |
| 142 | + } |
| 143 | + if err := json.Unmarshal(content, &blocks); err != nil { |
| 144 | + return "", false |
| 145 | + } |
| 146 | + texts := []string{} |
| 147 | + sawTool := false |
| 148 | + for _, block := range blocks { |
| 149 | + switch block.Type { |
| 150 | + case "text": |
| 151 | + if strings.TrimSpace(block.Text) != "" { |
| 152 | + texts = append(texts, block.Text) |
| 153 | + } |
| 154 | + case "tool_result", "tool_use": |
| 155 | + sawTool = true |
| 156 | + } |
| 157 | + } |
| 158 | + if len(texts) == 0 { |
| 159 | + return "", sawTool |
| 160 | + } |
| 161 | + return strings.Join(texts, "\n"), false |
| 162 | +} |
| 163 | + |
| 164 | +// plaintextPrefixes maps a line prefix to a role for the plain-text adapter. |
| 165 | +// Order matters: first match wins. Unprefixed text continues the current |
| 166 | +// speaker's turn; before any prefix appears, text defaults to the operator — |
| 167 | +// fail-open into the INPUT only (the worst a misclassified line can do is |
| 168 | +// create one more proposal for a human to reject; it can never act). |
| 169 | +var plaintextPrefixes = []struct { |
| 170 | + prefix string |
| 171 | + role string |
| 172 | +}{ |
| 173 | + {"user:", RoleOperator}, |
| 174 | + {"operator:", RoleOperator}, |
| 175 | + {"h:", RoleOperator}, |
| 176 | + {">", RoleOperator}, |
| 177 | + {"assistant:", RoleAgent}, |
| 178 | + {"agent:", RoleAgent}, |
| 179 | + {"a:", RoleAgent}, |
| 180 | + {"tool:", RoleTool}, |
| 181 | +} |
| 182 | + |
| 183 | +// ParsePlaintextTranscript projects a prefix-annotated plain-text transcript |
| 184 | +// (`User: …` / `Agent: …`) into neutral events. Consecutive lines of one |
| 185 | +// speaker merge into one event; the whole file is one session identified by |
| 186 | +// its source name. |
| 187 | +func ParsePlaintextTranscript(source string, r io.Reader) ([]Event, error) { |
| 188 | + scanner := newLineScanner(r) |
| 189 | + events := []Event{} |
| 190 | + currentRole := RoleOperator |
| 191 | + var current []string |
| 192 | + flush := func() { |
| 193 | + text := strings.TrimSpace(strings.Join(current, "\n")) |
| 194 | + current = nil |
| 195 | + if text == "" { |
| 196 | + return |
| 197 | + } |
| 198 | + events = append(events, Event{Source: source, SessionID: source, Role: currentRole, Text: text}) |
| 199 | + } |
| 200 | + for scanner.Scan() { |
| 201 | + line := scanner.Text() |
| 202 | + trimmed := strings.TrimSpace(line) |
| 203 | + matched := false |
| 204 | + lower := strings.ToLower(trimmed) |
| 205 | + for _, candidate := range plaintextPrefixes { |
| 206 | + if strings.HasPrefix(lower, candidate.prefix) { |
| 207 | + flush() |
| 208 | + currentRole = candidate.role |
| 209 | + current = append(current, strings.TrimSpace(trimmed[len(candidate.prefix):])) |
| 210 | + matched = true |
| 211 | + break |
| 212 | + } |
| 213 | + } |
| 214 | + if !matched { |
| 215 | + current = append(current, line) |
| 216 | + } |
| 217 | + } |
| 218 | + flush() |
| 219 | + if err := scanner.Err(); err != nil { |
| 220 | + return nil, fmt.Errorf("read plaintext transcript %s: %w", source, err) |
| 221 | + } |
| 222 | + return assignSessionIndexes(events), nil |
| 223 | +} |
0 commit comments