| 1 | package agent |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "context" |
| 6 | "crypto/sha256" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | "io" |
| 11 | "os" |
| 12 | "time" |
| 13 | |
| 14 | fileencoding "reasonix/internal/fileutil/encoding" |
| 15 | "reasonix/internal/provider" |
| 16 | "reasonix/internal/store" |
| 17 | ) |
| 18 | |
| 19 | // SessionDisplayIndexSchemaVersion is the on-disk schema of the display index |
| 20 | // sidecar. Loaders reject any other version so a future layout change fails |
| 21 | // closed into the rescan fallback instead of misreading offsets. |
| 22 | const SessionDisplayIndexSchemaVersion = 1 |
| 23 | |
| 24 | // sessionDisplayIndexMaxLineBytes keeps recovery scans bounded when a damaged |
| 25 | // transcript has no newline for an arbitrarily large payload. A normal |
| 26 | // provider message can contain attachments, so this stays comfortably above |
| 27 | // the usual attachment threshold while refusing a single corrupt line before |
| 28 | // it can exhaust the desktop process. |
| 29 | const sessionDisplayIndexMaxLineBytes = 16 << 20 |
| 30 | |
| 31 | // SessionDisplayIndex pages history by exact canonical JSONL byte ranges. |
| 32 | // Consumers validate TranscriptSize and content identity before using it. |
| 33 | type SessionDisplayIndex struct { |
| 34 | SchemaVersion int `json:"schema_version"` |
| 35 | Revision int64 `json:"revision"` |
| 36 | RevisionKnown bool `json:"revision_known"` |
| 37 | ContentDigest string `json:"content_digest"` |
| 38 | TranscriptSize int64 `json:"transcript_size"` |
| 39 | MessageCount int `json:"message_count"` |
| 40 | AuthoredTurns int `json:"authored_turns"` |
| 41 | // ListingPreview is derived from the same transcript generation as |
| 42 | // AuthoredTurns. The explicit known bit keeps old v1 indexes compatible: |
| 43 | // an empty preview may be authoritative, while an omitted preview must |
| 44 | // still fall back to a repair scan. |
| 45 | ListingPreview string `json:"listing_preview,omitempty"` |
| 46 | ListingPreviewKnown bool `json:"listing_preview_known,omitempty"` |
| 47 | Entries []DisplayIndexEntry `json:"entries"` |
| 48 | UpdatedAt time.Time `json:"updated_at"` |
| 49 | } |
| 50 | |
| 51 | // DisplayIndexEntry is one message's metadata. AuthoredTurn is the absolute |
| 52 | // authored-turn number the message belongs to, counted with |
| 53 | // SessionPreviewFromMessages semantics (IsUserAuthoredTurn over |
| 54 | // UserMessageText); messages before the first authored turn carry 0. |
| 55 | type DisplayIndexEntry struct { |
| 56 | Index int `json:"index"` |
| 57 | Offset int64 `json:"offset"` |
| 58 | Length int64 `json:"length"` |
| 59 | Role provider.Role `json:"role"` |
| 60 | AuthoredTurn int `json:"authored_turn"` |
| 61 | StartsTurn bool `json:"starts_turn,omitempty"` |
| 62 | HasImages bool `json:"has_images,omitempty"` |
| 63 | HasToolCalls bool `json:"has_tool_calls,omitempty"` |
| 64 | LocalOnly bool `json:"local_only,omitempty"` |
| 65 | ToolResult bool `json:"tool_result,omitempty"` |
| 66 | // PinnedContextRevision distinguishes the hidden host revision from other |
| 67 | // user-role records. History paging needs this bit to keep legacy persisted |
| 68 | // user timestamps aligned without decoding the entire transcript prefix. |
| 69 | PinnedContextRevision bool `json:"pinned_context_revision,omitempty"` |
| 70 | // Synthetic and Steer use raw authored text; desktop may first resolve |
| 71 | // @file references for display, but the control-message predicates match. |
| 72 | Synthetic bool `json:"synthetic,omitempty"` |
| 73 | Steer bool `json:"steer,omitempty"` |
| 74 | } |
| 75 | |
| 76 | // BuildSessionDisplayIndex derives the index from an in-memory message slice. |
| 77 | // It is a pure function: same messages, same entries. It returns nil when a |
| 78 | // message fails to marshal — impossible for a slice that already survived |
| 79 | // digestAndSizeSessionMessages, so save-path callers can treat nil as a |
| 80 | // warn-only failure. |
| 81 | func BuildSessionDisplayIndex(messages []provider.Message, revision int64, revisionKnown bool, digest [sha256.Size]byte) *SessionDisplayIndex { |
| 82 | idx, _ := BuildSessionDisplayIndexContext(context.Background(), messages, revision, revisionKnown, digest) |
| 83 | return idx |
| 84 | } |
| 85 | |
| 86 | func BuildSessionDisplayIndexContext(ctx context.Context, messages []provider.Message, revision int64, revisionKnown bool, digest [sha256.Size]byte) (*SessionDisplayIndex, error) { |
| 87 | preview, _ := SessionPreviewFromMessages(messages) |
| 88 | idx := &SessionDisplayIndex{ |
| 89 | SchemaVersion: SessionDisplayIndexSchemaVersion, |
| 90 | Revision: revision, |
| 91 | RevisionKnown: revisionKnown, |
| 92 | ContentDigest: digestString(digest), |
| 93 | MessageCount: len(messages), |
| 94 | ListingPreview: preview, |
| 95 | ListingPreviewKnown: true, |
| 96 | Entries: make([]DisplayIndexEntry, 0, len(messages)), |
| 97 | UpdatedAt: time.Now().UTC(), |
| 98 | } |
| 99 | if _, _, err := encodeDisplayIndexEntriesContext(ctx, idx, messages, 0, 0, 0); err != nil { |
| 100 | return nil, err |
| 101 | } |
| 102 | return idx, nil |
| 103 | } |
| 104 | |
| 105 | // encodeDisplayIndexEntries appends the entries for msgs[startIndex:] to idx, |
| 106 | // beginning at byte offset and authored-turn count turn. The encoding must |
| 107 | // match writeSessionMessages byte-for-byte (json.Marshal + '\n'), NOT the |
| 108 | // digest encoding: the digest zeroes CreatedAt while the transcript file |
| 109 | // stores the real bytes, and the offsets describe the file. |
| 110 | func encodeDisplayIndexEntries(idx *SessionDisplayIndex, msgs []provider.Message, startIndex int, offset int64, turn int) (int64, int, error) { |
| 111 | return encodeDisplayIndexEntriesContext(context.Background(), idx, msgs, startIndex, offset, turn) |
| 112 | } |
| 113 | |
| 114 | func encodeDisplayIndexEntriesContext(ctx context.Context, idx *SessionDisplayIndex, msgs []provider.Message, startIndex int, offset int64, turn int) (int64, int, error) { |
| 115 | for i := startIndex; i < len(msgs); i++ { |
| 116 | b, err := marshalJSONContext(ctx, msgs[i]) |
| 117 | if err != nil { |
| 118 | return 0, 0, fmt.Errorf("encode message %d: %w", i, err) |
| 119 | } |
| 120 | entry, nextTurn := classifyDisplayIndexMessage(msgs[i], i, offset, int64(len(b))+1, turn) |
| 121 | turn = nextTurn |
| 122 | idx.Entries = append(idx.Entries, entry) |
| 123 | offset += int64(len(b)) + 1 |
| 124 | } |
| 125 | idx.AuthoredTurns = turn |
| 126 | idx.TranscriptSize = offset |
| 127 | return offset, turn, nil |
| 128 | } |
| 129 | |
| 130 | // classifyDisplayIndexMessage fills one entry's metadata from the message |
| 131 | // alone — no body retention, no cross-message state beyond the running turn |
| 132 | // counter. |
| 133 | func classifyDisplayIndexMessage(m provider.Message, index int, offset, length int64, turn int) (DisplayIndexEntry, int) { |
| 134 | entry := DisplayIndexEntry{ |
| 135 | Index: index, |
| 136 | Offset: offset, |
| 137 | Length: length, |
| 138 | Role: m.Role, |
| 139 | AuthoredTurn: turn, |
| 140 | HasImages: m.HasImagePayload(), |
| 141 | HasToolCalls: len(m.ToolCalls) > 0, |
| 142 | LocalOnly: m.LocalOnly, |
| 143 | ToolResult: m.Role == provider.RoleTool, |
| 144 | PinnedContextRevision: IsPinnedContextRevision(m), |
| 145 | } |
| 146 | if m.Role == provider.RoleUser { |
| 147 | switch { |
| 148 | case IsUserAuthoredTurnMessage(m): |
| 149 | turn++ |
| 150 | entry.AuthoredTurn = turn |
| 151 | entry.StartsTurn = true |
| 152 | case IsHostGeneratedUserMessage(m): |
| 153 | entry.Synthetic = true |
| 154 | default: |
| 155 | if _, isSteer := SteerText(m.Content); isSteer { |
| 156 | entry.Steer = true |
| 157 | } |
| 158 | } |
| 159 | } |
| 160 | return entry, turn |
| 161 | } |
| 162 | |
| 163 | // extendSessionDisplayIndex incrementally extends the previous index when the |
| 164 | // save was append-only: the on-disk transcript was verified to be a prefix of |
| 165 | // msgs, so when the previous index describes exactly that prefix (its revision |
| 166 | // is the base revision this save built on and its entry count matches the |
| 167 | // append boundary), its entries stay valid — the canonical encoding is |
| 168 | // prefix-stable — and only the tail needs encoding. Any doubt returns nil and |
| 169 | // the caller rebuilds from the full slice. |
| 170 | func extendSessionDisplayIndex(indexPath string, msgs []provider.Message, digest [sha256.Size]byte, revision int64, appendFrom int) *SessionDisplayIndex { |
| 171 | prev, err := LoadSessionDisplayIndex(indexPath) |
| 172 | if err != nil || prev == nil { |
| 173 | return nil |
| 174 | } |
| 175 | if prev.MessageCount != appendFrom || !prev.RevisionKnown || prev.Revision != revision-1 { |
| 176 | return nil |
| 177 | } |
| 178 | preview, _ := SessionPreviewFromMessages(msgs) |
| 179 | idx := &SessionDisplayIndex{ |
| 180 | SchemaVersion: SessionDisplayIndexSchemaVersion, |
| 181 | Revision: revision, |
| 182 | RevisionKnown: true, |
| 183 | ContentDigest: digestString(digest), |
| 184 | MessageCount: len(msgs), |
| 185 | ListingPreview: preview, |
| 186 | ListingPreviewKnown: true, |
| 187 | Entries: make([]DisplayIndexEntry, 0, len(msgs)), |
| 188 | UpdatedAt: time.Now().UTC(), |
| 189 | } |
| 190 | idx.Entries = append(idx.Entries, prev.Entries...) |
| 191 | if _, _, err := encodeDisplayIndexEntries(idx, msgs, appendFrom, prev.TranscriptSize, prev.AuthoredTurns); err != nil { |
| 192 | return nil |
| 193 | } |
| 194 | return idx |
| 195 | } |
| 196 | |
| 197 | // refreshSessionDisplayIndex republishes the display index after a successful |
| 198 | // save. appendFrom >= 0 hints that the previous on-disk revision is a strict |
| 199 | // prefix of msgs (an append-only save), allowing an incremental extension; any |
| 200 | // other save shape rebuilds from the full slice. Rewind, compaction, and other |
| 201 | // rewrites change revision+digest, so they land here as rebuilds naturally. |
| 202 | func refreshSessionDisplayIndex(path string, msgs []provider.Message, digest [sha256.Size]byte, revision int64, appendFrom int) error { |
| 203 | indexPath := store.SessionDisplayIndex(path) |
| 204 | if indexPath == "" { |
| 205 | return nil |
| 206 | } |
| 207 | var idx *SessionDisplayIndex |
| 208 | if appendFrom > 0 { |
| 209 | idx = extendSessionDisplayIndex(indexPath, msgs, digest, revision, appendFrom) |
| 210 | } |
| 211 | if idx == nil { |
| 212 | idx = BuildSessionDisplayIndex(msgs, revision, true, digest) |
| 213 | } |
| 214 | if idx == nil { |
| 215 | return fmt.Errorf("encode session display index") |
| 216 | } |
| 217 | return WriteSessionDisplayIndex(indexPath, idx) |
| 218 | } |
| 219 | |
| 220 | // WriteSessionDisplayIndex publishes the index atomically (tmp + fsync + |
| 221 | // rename) with 0600 permissions, matching the other session sidecars. |
| 222 | func WriteSessionDisplayIndex(path string, idx *SessionDisplayIndex) error { |
| 223 | return WriteSessionDisplayIndexContext(context.Background(), path, idx) |
| 224 | } |
| 225 | |
| 226 | func WriteSessionDisplayIndexContext(ctx context.Context, path string, idx *SessionDisplayIndex) error { |
| 227 | if path == "" { |
| 228 | return fmt.Errorf("empty session display index path") |
| 229 | } |
| 230 | b, err := marshalJSONIndentContext(ctx, idx) |
| 231 | if err != nil { |
| 232 | return fmt.Errorf("encode session display index: %w", err) |
| 233 | } |
| 234 | b = append(b, '\n') |
| 235 | if err := atomicWriteFileContext(ctx, path, ".session-display-index.*.tmp", "atomic-write", b, 0o600, true); err != nil { |
| 236 | return fmt.Errorf("write session display index: %w", err) |
| 237 | } |
| 238 | return nil |
| 239 | } |
| 240 | |
| 241 | // LoadSessionDisplayIndex reads the sidecar, rejecting truncated JSON, |
| 242 | // unsupported schema versions, and header/entry-count disagreements so a |
| 243 | // corrupt index fails closed into the rescan fallback. |
| 244 | func LoadSessionDisplayIndex(path string) (*SessionDisplayIndex, error) { |
| 245 | if path == "" { |
| 246 | return nil, fmt.Errorf("empty session display index path") |
| 247 | } |
| 248 | b, err := fileencoding.ReadFileUTF8(path) |
| 249 | if err != nil { |
| 250 | return nil, err |
| 251 | } |
| 252 | var idx SessionDisplayIndex |
| 253 | if err := json.Unmarshal(b, &idx); err != nil { |
| 254 | return nil, fmt.Errorf("decode session display index: %w", err) |
| 255 | } |
| 256 | if idx.SchemaVersion != SessionDisplayIndexSchemaVersion { |
| 257 | return nil, fmt.Errorf("unsupported session display index schema %d", idx.SchemaVersion) |
| 258 | } |
| 259 | if idx.MessageCount != len(idx.Entries) { |
| 260 | return nil, fmt.Errorf("session display index message_count %d does not match %d entries", idx.MessageCount, len(idx.Entries)) |
| 261 | } |
| 262 | expectedOffset := int64(0) |
| 263 | for i, entry := range idx.Entries { |
| 264 | if entry.Index != i { |
| 265 | return nil, fmt.Errorf("session display index entry %d has index %d", i, entry.Index) |
| 266 | } |
| 267 | if entry.Offset != expectedOffset || entry.Length <= 0 || entry.Length > idx.TranscriptSize-entry.Offset { |
| 268 | return nil, fmt.Errorf("session display index entry %d has invalid range %d+%d", i, entry.Offset, entry.Length) |
| 269 | } |
| 270 | expectedOffset += entry.Length |
| 271 | } |
| 272 | if expectedOffset != idx.TranscriptSize { |
| 273 | return nil, fmt.Errorf("session display index covers %d bytes, transcript_size is %d", expectedOffset, idx.TranscriptSize) |
| 274 | } |
| 275 | return &idx, nil |
| 276 | } |
| 277 | |
| 278 | // ValidateSessionDisplayIndex reports whether the index still describes the |
| 279 | // transcript identified by revision/digest/transcriptSize. The caller picks |
| 280 | // transcriptSize: the canonical encoding size when checking in-memory state, |
| 281 | // the anchor's actual file size when checking the on-disk .jsonl. |
| 282 | func ValidateSessionDisplayIndex(idx *SessionDisplayIndex, revision int64, revisionKnown bool, digest [sha256.Size]byte, transcriptSize int64) bool { |
| 283 | if idx == nil || idx.SchemaVersion != SessionDisplayIndexSchemaVersion { |
| 284 | return false |
| 285 | } |
| 286 | if idx.RevisionKnown != revisionKnown || (revisionKnown && idx.Revision != revision) { |
| 287 | return false |
| 288 | } |
| 289 | if idx.ContentDigest != digestString(digest) { |
| 290 | return false |
| 291 | } |
| 292 | if idx.TranscriptSize != transcriptSize { |
| 293 | return false |
| 294 | } |
| 295 | return idx.MessageCount == len(idx.Entries) |
| 296 | } |
| 297 | |
| 298 | // ScanSessionDisplayIndex is the recovery path for a missing, corrupt, or |
| 299 | // stale index: it streams the .jsonl transcript line by line (lines can be |
| 300 | // megabytes when a message carries Images, so the file is never loaded whole), |
| 301 | // decoding each line only as far as classification requires and recording the |
| 302 | // real byte offsets. The content digest is rebuilt alongside so the scanned |
| 303 | // index validates exactly like a built one; the revision is not recoverable |
| 304 | // from the transcript alone and stays unknown. A line that does not decode |
| 305 | // fails the scan — the caller falls back to a full parse. |
| 306 | func ScanSessionDisplayIndex(transcriptPath string) (*SessionDisplayIndex, error) { |
| 307 | f, err := os.Open(transcriptPath) |
| 308 | if err != nil { |
| 309 | return nil, err |
| 310 | } |
| 311 | defer f.Close() |
| 312 | idx := &SessionDisplayIndex{ |
| 313 | SchemaVersion: SessionDisplayIndexSchemaVersion, |
| 314 | Entries: []DisplayIndexEntry{}, |
| 315 | UpdatedAt: time.Now().UTC(), |
| 316 | } |
| 317 | h := sha256.New() |
| 318 | reader := bufio.NewReaderSize(f, 1<<20) |
| 319 | offset := int64(0) |
| 320 | turn := 0 |
| 321 | for { |
| 322 | line, readErr := readSessionDisplayIndexLine(reader) |
| 323 | if len(line) > 0 { |
| 324 | var m provider.Message |
| 325 | if err := json.Unmarshal(line, &m); err != nil { |
| 326 | return nil, fmt.Errorf("decode session transcript line %d: %w", len(idx.Entries), err) |
| 327 | } |
| 328 | identity, err := json.Marshal(messageForSessionIdentity(m)) |
| 329 | if err != nil { |
| 330 | return nil, fmt.Errorf("re-encode session transcript line %d: %w", len(idx.Entries), err) |
| 331 | } |
| 332 | h.Write(identity) |
| 333 | h.Write([]byte{'\n'}) |
| 334 | var entry DisplayIndexEntry |
| 335 | entry, turn = classifyDisplayIndexMessage(m, len(idx.Entries), offset, int64(len(line)), turn) |
| 336 | if entry.StartsTurn && !idx.ListingPreviewKnown { |
| 337 | preview := truncatePreview(previewProse(UserMessageText(m))) |
| 338 | if preview != "" { |
| 339 | idx.ListingPreview = preview |
| 340 | idx.ListingPreviewKnown = true |
| 341 | } |
| 342 | } |
| 343 | idx.Entries = append(idx.Entries, entry) |
| 344 | offset += int64(len(line)) |
| 345 | } |
| 346 | if errors.Is(readErr, io.EOF) { |
| 347 | break |
| 348 | } |
| 349 | if readErr != nil { |
| 350 | return nil, fmt.Errorf("read session transcript: %w", readErr) |
| 351 | } |
| 352 | } |
| 353 | idx.MessageCount = len(idx.Entries) |
| 354 | idx.AuthoredTurns = turn |
| 355 | if !idx.ListingPreviewKnown { |
| 356 | idx.ListingPreviewKnown = true |
| 357 | } |
| 358 | idx.TranscriptSize = offset |
| 359 | var digest [sha256.Size]byte |
| 360 | copy(digest[:], h.Sum(nil)) |
| 361 | idx.ContentDigest = digestString(digest) |
| 362 | return idx, nil |
| 363 | } |
| 364 | |
| 365 | // readSessionDisplayIndexLine preserves the exact byte range of one JSONL |
| 366 | // record while enforcing a hard per-record allocation cap. bufio.Reader's |
| 367 | // ReadBytes grows until it finds a delimiter, which turns a malformed giant |
| 368 | // line into an unbounded allocation before ScanSessionDisplayIndex can reject |
| 369 | // it. |
| 370 | func readSessionDisplayIndexLine(reader *bufio.Reader) ([]byte, error) { |
| 371 | var line []byte |
| 372 | for { |
| 373 | fragment, err := reader.ReadSlice('\n') |
| 374 | if len(fragment) > sessionDisplayIndexMaxLineBytes-len(line) { |
| 375 | return nil, fmt.Errorf("session transcript line exceeds %d bytes", sessionDisplayIndexMaxLineBytes) |
| 376 | } |
| 377 | line = append(line, fragment...) |
| 378 | if errors.Is(err, bufio.ErrBufferFull) { |
| 379 | continue |
| 380 | } |
| 381 | return line, err |
| 382 | } |
| 383 | } |
| 384 |