package claude import ( "bufio" "bytes" "container/list" "encoding/json" "io" "os" "sort" "strings" "sync" "time" "git.a-wan.net/alan/pipelines/internal/protocol" ) // A Claude session file grows to tens of megabytes, and reading a history // page used to parse all of it. A transcriptIndex records, per message the // history would show, which lines of the file build it. A page then re-reads // and replays only its own messages' lines, so the newest page costs about as // much as its messages. The index is kept per file and brought up to date by // reading only what was appended since; a file that was replaced, truncated or // rewritten is indexed again from the start. // // The replay must give exactly what building the whole file gives // (fullTranscriptPage). Where the index cannot promise that (a user turn with // no uuid, one tool id used by two messages, a parseable last line that has no // newline yet), the page is built from the whole file as before. // transcriptIndexesRetained bounds how many session files keep an index. const transcriptIndexesRetained = 64 type lineRef struct { offset int64 length int64 } type indexedMessage struct { // lines build the message, in file order: its own entries and the tool // results that land on it. lines []lineRef shown bool // A user turn's trimmed text and how many earlier turns had that text name // it after the prompt the operator's client sent (promptMatcher). user bool text string ordinal int } type transcriptIndex struct { mu sync.Mutex path string // The indexed file: its identity, size and time when last read, where the // index starts (past an oversized file's skipped head), where the last // whole line ends, and the bytes just before that end. info os.FileInfo size int64 modTime time.Time start int64 offset int64 boundary []byte // fragment is set while the file ends with a parseable line that has no // newline yet: a whole-file read includes it, the index does not. fragment bool // exact is cleared once the file holds a shape the index cannot replay // exactly. exact bool firstStamp int64 hasStamp bool meta transcriptMeta messages []indexedMessage messageIndex map[string]int toolIndex map[string]int injectedSeen map[string]bool textCount map[string]int } var transcriptIndexes = struct { sync.Mutex byPath map[string]*list.Element order *list.List }{byPath: map[string]*list.Element{}, order: list.New()} func transcriptIndexFor(path string) *transcriptIndex { transcriptIndexes.Lock() defer transcriptIndexes.Unlock() if element, ok := transcriptIndexes.byPath[path]; ok { transcriptIndexes.order.MoveToFront(element) return element.Value.(*transcriptIndex) } index := &transcriptIndex{path: path} transcriptIndexes.byPath[path] = transcriptIndexes.order.PushFront(index) for transcriptIndexes.order.Len() > transcriptIndexesRetained { oldest := transcriptIndexes.order.Back() transcriptIndexes.order.Remove(oldest) delete(transcriptIndexes.byPath, oldest.Value.(*transcriptIndex).path) } return index } func forgetTranscriptIndex(path string) { transcriptIndexes.Lock() defer transcriptIndexes.Unlock() if element, ok := transcriptIndexes.byPath[path]; ok { transcriptIndexes.order.Remove(element) delete(transcriptIndexes.byPath, path) } } func (x *transcriptIndex) reset(start int64) { x.info, x.size, x.modTime, x.boundary, x.fragment = nil, 0, time.Time{}, nil, false x.start, x.offset, x.exact = start, start, true x.firstStamp, x.hasStamp, x.meta = 0, false, transcriptMeta{} x.messages = nil x.messageIndex = map[string]int{} x.toolIndex = map[string]int{} x.injectedSeen = map[string]bool{} x.textCount = map[string]int{} } // windowStart is where a read of the file begins: 0, or for a file larger // than maxTranscriptBytes the first whole line of its newest bytes // (readTranscriptTail). func windowStart(file *os.File, size int64) (int64, error) { if size <= maxTranscriptBytes { return 0, nil } skipped := size - maxTranscriptBytes reader := bufio.NewReaderSize(io.NewSectionReader(file, skipped, size-skipped), 64<<10) partial, err := reader.ReadBytes('\n') if err != nil && err != io.EOF { return 0, err } return skipped + int64(len(partial)), nil } // update brings the index up to date with the file, reading only what was // appended since the last update when the file is the same one grown. func (x *transcriptIndex) update() error { file, err := os.Open(x.path) if err != nil { return err } defer file.Close() info, err := file.Stat() if err != nil { return err } size := info.Size() start, err := windowStart(file, size) if err != nil { return err } if x.info != nil && os.SameFile(x.info, info) && start == x.start && size == x.size && info.ModTime().Equal(x.modTime) { return nil } if x.info == nil || !os.SameFile(x.info, info) || start != x.start || size < x.offset || size == x.size || !x.sameBoundary(file) { x.reset(start) } if err := x.read(file, size); err != nil { return err } x.info, x.size, x.modTime = info, size, info.ModTime() return nil } // sameBoundary checks the bytes before the indexed end are unchanged, so the // file only grew past them. func (x *transcriptIndex) sameBoundary(file *os.File) bool { if len(x.boundary) == 0 { return x.offset == x.start } held := make([]byte, len(x.boundary)) if _, err := file.ReadAt(held, x.offset-int64(len(held))); err != nil { return false } return bytes.Equal(held, x.boundary) } // read indexes the whole lines between the indexed end and size. func (x *transcriptIndex) read(file *os.File, size int64) error { reader := bufio.NewReaderSize(io.NewSectionReader(file, x.offset, size-x.offset), 256<<10) position := x.offset var long []byte for { chunk, err := reader.ReadSlice('\n') if err == bufio.ErrBufferFull { long = append(long, chunk...) if len(long) > maxLineBytes { return bufio.ErrTooLong } continue } line := chunk if long != nil { line = append(long, chunk...) long = nil } if err == io.EOF { // A last line with no newline yet is not indexed: it is either // still being written or will be followed by one. var entry transcriptEntry trimmed := bytes.TrimSpace(line) x.fragment = len(trimmed) > 0 && json.Unmarshal(trimmed, &entry) == nil if len(line) > maxLineBytes { return bufio.ErrTooLong } break } if err != nil { return err } if len(line) > maxLineBytes { return bufio.ErrTooLong } ref := lineRef{offset: position, length: int64(len(line) - 1)} position += int64(len(line)) if ref.length > 0 { var entry transcriptEntry if json.Unmarshal(line[:ref.length], &entry) == nil { x.add(entry, ref) } } } x.offset = position if position > x.start { count := min(position-x.start, 64) x.boundary = make([]byte, count) if _, err := file.ReadAt(x.boundary, position-count); err != nil { return err } } return nil } // add mirrors transcriptBuilder.add, recording which message each line builds // instead of building it. func (x *transcriptIndex) add(entry transcriptEntry, ref lineRef) { if stamp, ok := transcriptTime(entry.Timestamp); ok && !x.hasStamp { x.firstStamp, x.hasStamp = stamp, true } x.meta.note(entry) if entry.IsSidechain { return } switch entry.Type { case "assistant": messageID := assistantMessageID(entry) if messageID == "" { return } index, exists := x.messageIndex[messageID] if !exists { x.messages = append(x.messages, indexedMessage{}) index = len(x.messages) - 1 x.messageIndex[messageID] = index } x.attach(index, ref) for _, block := range decodeBlocks(entry.Message.Content) { if !shownAssistantBlock(block) { continue } x.messages[index].shown = true if block.Type == "tool_use" { if held, ok := x.toolIndex[block.ID]; ok && held != index { x.exact = false } x.toolIndex[block.ID] = index } } case "user", "attachment": input := entryInputOf(entry) for _, block := range input.results { if index, ok := x.toolIndex[block.ToolUseID]; ok { x.attach(index, ref) } } if input.injected.id != "" { if !x.injectedSeen[input.injected.id] { x.injectedSeen[input.injected.id] = true x.messages = append(x.messages, indexedMessage{lines: []lineRef{ref}, shown: true}) } } else if input.user { if entry.UUID == "" { // Whether such a turn is shown depends on the prompts sent. x.exact = false } text := strings.TrimSpace(input.text) x.messages = append(x.messages, indexedMessage{lines: []lineRef{ref}, shown: true, user: true, text: text, ordinal: x.textCount[text]}) x.textCount[text]++ } } } func (x *transcriptIndex) attach(index int, ref lineRef) { lines := x.messages[index].lines if len(lines) > 0 && lines[len(lines)-1] == ref { return } x.messages[index].lines = append(lines, ref) } // indexedTranscriptMeta is the session description transcriptSession reads, // from the file's index. ok is false when the index cannot answer exactly. func indexedTranscriptMeta(path string) (transcriptMeta, bool) { x := transcriptIndexFor(path) x.mu.Lock() defer x.mu.Unlock() if err := x.update(); err != nil { x.reset(0) forgetTranscriptIndex(path) return transcriptMeta{}, false } return x.meta, !x.fragment } // indexedTranscriptPage serves a history page from the file's index. ok is // false (with no error) when the page must be built from the whole file. func indexedTranscriptPage(path, sessionID string, prompts []promptRecord, limit int, cursor string) (protocol.ChatHistoryPage, bool, error) { x := transcriptIndexFor(path) x.mu.Lock() if err := x.update(); err != nil { // The whole-file read reports the error as it always did. x.reset(0) x.mu.Unlock() forgetTranscriptIndex(path) return protocol.ChatHistoryPage{}, false, nil } if x.fragment || !x.exact { x.mu.Unlock() return protocol.ChatHistoryPage{}, false, nil } notice := x.start > 0 shown := make([]int, 0, len(x.messages)+1) if notice { shown = append(shown, -1) } for index, message := range x.messages { if message.shown { shown = append(shown, index) } } start, end, offset := pageBounds(len(shown), limit, cursor) var refs []lineRef users := map[int64]indexedMessage{} wanted := 0 for _, index := range shown[start:end] { if index < 0 { continue } wanted++ message := x.messages[index] refs = append(refs, message.lines...) if message.user { users[message.lines[0].offset] = message } } skipped, firstStamp := x.start, x.firstStamp x.mu.Unlock() lines, err := readLines(path, refs) if err != nil { return protocol.ChatHistoryPage{}, false, nil } ids := promptIDs(prompts) var current int64 builder := newTranscriptBuilder(sessionID, func(entry transcriptEntry, _ string) string { if message, ok := users[current]; ok && message.ordinal < len(ids[message.text]) { return ids[message.text][message.ordinal] } return entry.UUID }) for _, line := range lines { var entry transcriptEntry if json.Unmarshal(line.data, &entry) != nil { return protocol.ChatHistoryPage{}, false, nil } current = line.offset builder.add(entry) } messages := builder.shown() if len(messages) != wanted { // The file changed under the read: build it whole. return protocol.ChatHistoryPage{}, false, nil } if notice && start == 0 && end > 0 { messages = append([]protocol.ChatMessage{earlierHistoryNotice(sessionID, skipped, firstStamp)}, messages...) } return historyPage(messages, start, offset), true, nil } type readLine struct { offset int64 data []byte } // readLines reads the given lines in file order, each once, joining reads of // lines that lie close together. func readLines(path string, refs []lineRef) ([]readLine, error) { sort.Slice(refs, func(i, j int) bool { return refs[i].offset < refs[j].offset }) file, err := os.Open(path) if err != nil { return nil, err } defer file.Close() const gap = 64 << 10 var lines []readLine for i := 0; i < len(refs); { first := refs[i].offset last := i end := refs[i].offset + refs[i].length for last+1 < len(refs) && refs[last+1].offset-end <= gap { last++ end = max(end, refs[last].offset+refs[last].length) } buffer := make([]byte, end-first) if _, err := file.ReadAt(buffer, first); err != nil { return nil, err } for ; i <= last; i++ { ref := refs[i] if len(lines) > 0 && lines[len(lines)-1].offset == ref.offset { continue } lines = append(lines, readLine{offset: ref.offset, data: buffer[ref.offset-first : ref.offset-first+ref.length]}) } } return lines, nil }