forked from kenn-io/agentsview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmessages.go
More file actions
1580 lines (1482 loc) · 45.7 KB
/
Copy pathmessages.go
File metadata and controls
1580 lines (1482 loc) · 45.7 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
package db
import (
"context"
"crypto/sha256"
"database/sql"
"encoding/json"
"errors"
"fmt"
"log"
"strings"
"time"
"go.kenn.io/agentsview/internal/parser"
)
const (
selectMessageCols = `id, session_id, ordinal, role, content,
thinking_text,
COALESCE(timestamp, '') AS timestamp,
has_thinking, has_tool_use, content_length,
is_system,
model, token_usage, context_tokens, output_tokens,
has_context_tokens, has_output_tokens,
claude_message_id, claude_request_id,
source_type, source_subtype, source_uuid,
source_parent_uuid, is_sidechain, is_compact_boundary`
insertMessageCols = `session_id, ordinal, role, content,
thinking_text,
timestamp, has_thinking, has_tool_use, content_length,
is_system,
model, token_usage, context_tokens, output_tokens,
has_context_tokens, has_output_tokens,
claude_message_id, claude_request_id,
source_type, source_subtype, source_uuid,
source_parent_uuid, is_sidechain, is_compact_boundary`
// DefaultMessageLimit is the default number of messages returned.
DefaultMessageLimit = 100
// MaxMessageLimit is the maximum number of messages returned.
MaxMessageLimit = 1000
// Keep query parameter counts conservative so large sessions
// do not exceed SQLite variable limits when hydrating tool calls.
attachToolCallBatchSize = 500
// Keep multi-row INSERT statements below SQLite's historic
// 999-variable limit so binaries built against older SQLite
// versions still work.
messageInsertRowsPerStmt = 39 // 25 params per row
toolCallInsertRowsPerStmt = 90 // 10 params per row
toolResultEventInsertRowsPerStmt = 80 // 12 params per row
)
// ToolCall represents a single tool invocation stored in
// the tool_calls table.
type ToolCall struct {
MessageID int64 `json:"-"`
SessionID string `json:"-"`
ToolName string `json:"tool_name"`
Category string `json:"category"`
ToolUseID string `json:"tool_use_id,omitempty"`
InputJSON string `json:"input_json,omitempty"`
SkillName string `json:"skill_name,omitempty"`
ResultContentLength int `json:"result_content_length,omitempty"`
ResultContent string `json:"result_content,omitempty"`
SubagentSessionID string `json:"subagent_session_id,omitempty"`
ResultEvents []ToolResultEvent `json:"result_events,omitempty"`
}
// ToolResult holds a tool_result content block for pairing.
type ToolResult struct {
ToolUseID string
ContentLength int
ContentRaw string // raw JSON of the content field; decode lazily
}
// ToolResultEvent represents a canonical chronological result update.
type ToolResultEvent struct {
ToolUseID string `json:"tool_use_id,omitempty"`
AgentID string `json:"agent_id,omitempty"`
SubagentSessionID string `json:"subagent_session_id,omitempty"`
Source string `json:"source"`
Status string `json:"status"`
Content string `json:"content"`
ContentLength int `json:"content_length"`
Timestamp string `json:"timestamp,omitempty"`
EventIndex int `json:"event_index"`
}
// Message represents a row in the messages table.
type Message struct {
ID int64 `json:"id"`
SessionID string `json:"session_id"`
Ordinal int `json:"ordinal"`
Role string `json:"role"`
Content string `json:"content"`
// ThinkingText holds the concatenated text of all thinking
// blocks for this message; "" if none.
ThinkingText string `json:"thinking_text"`
Timestamp string `json:"timestamp"`
HasThinking bool `json:"has_thinking"`
HasToolUse bool `json:"has_tool_use"`
ContentLength int `json:"content_length"`
Model string `json:"model"`
TokenUsage json.RawMessage `json:"token_usage,omitempty"`
ContextTokens int `json:"context_tokens"`
OutputTokens int `json:"output_tokens"`
HasContextTokens bool `json:"has_context_tokens"`
HasOutputTokens bool `json:"has_output_tokens"`
ClaudeMessageID string `json:"claude_message_id,omitempty"`
ClaudeRequestID string `json:"claude_request_id,omitempty"`
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
ToolResults []ToolResult `json:"-"` // transient, for pairing
IsSystem bool `json:"is_system"` // persisted, filters search/analytics
SourceType string `json:"source_type,omitempty"`
SourceSubtype string `json:"source_subtype,omitempty"`
SourceUUID string `json:"source_uuid,omitempty"`
SourceParentUUID string `json:"source_parent_uuid,omitempty"`
IsSidechain bool `json:"is_sidechain,omitempty"`
IsCompactBoundary bool `json:"is_compact_boundary,omitempty"`
}
// TokenPresence reports whether context/output token fields were
// present in stored message metadata. It preserves explicit flags,
// falls back to non-zero numeric values for legacy rows, and inspects
// raw token_usage payload keys to preserve zero-valued coverage.
func (m Message) TokenPresence() (bool, bool) {
return parser.InferTokenPresence(
m.TokenUsage, m.ContextTokens, m.OutputTokens,
m.HasContextTokens, m.HasOutputTokens,
)
}
// GetMessages returns paginated messages for a session.
// from: starting ordinal (inclusive)
// limit: max messages to return
// asc: true for ascending ordinal order, false for descending
func (db *DB) GetMessages(
ctx context.Context,
sessionID string, from, limit int, asc bool,
) ([]Message, error) {
if limit <= 0 || limit > MaxMessageLimit {
limit = DefaultMessageLimit
}
dir := "ASC"
op := ">="
if !asc {
dir = "DESC"
op = "<="
}
query := fmt.Sprintf(`
SELECT %s
FROM messages
WHERE session_id = ? AND ordinal %s ?
ORDER BY ordinal %s
LIMIT ?`, selectMessageCols, op, dir)
rows, err := db.getReader().QueryContext(
ctx, query, sessionID, from, limit,
)
if err != nil {
return nil, fmt.Errorf("querying messages: %w", err)
}
defer rows.Close()
msgs, err := scanMessages(rows)
if err != nil {
return nil, err
}
if err := db.attachToolCalls(ctx, msgs); err != nil {
return nil, err
}
return msgs, nil
}
// GetAllMessages returns all messages for a session ordered by ordinal.
func (db *DB) GetAllMessages(
ctx context.Context, sessionID string,
) ([]Message, error) {
rows, err := db.getReader().QueryContext(ctx, fmt.Sprintf(`
SELECT %s
FROM messages
WHERE session_id = ?
ORDER BY ordinal ASC`, selectMessageCols), sessionID)
if err != nil {
return nil, fmt.Errorf("querying all messages: %w", err)
}
defer rows.Close()
msgs, err := scanMessages(rows)
if err != nil {
return nil, err
}
if err := db.attachToolCalls(ctx, msgs); err != nil {
return nil, err
}
return msgs, nil
}
// insertMessagesTx batch-inserts messages within an existing
// transaction. Returns a slice of message IDs parallel to the
// input msgs slice. The caller must hold db.mu.
func insertMessagesTx(
tx *sql.Tx, msgs []Message,
) ([]int64, error) {
ids := make([]int64, len(msgs))
nextID, err := nextMessageIDTx(tx)
if err != nil {
return nil, err
}
for start := 0; start < len(msgs); start += messageInsertRowsPerStmt {
end := min(start+messageInsertRowsPerStmt, len(msgs))
batch := msgs[start:end]
args := make([]any, 0, len(batch)*25)
for i, m := range batch {
id := nextID + int64(start+i)
ids[start+i] = id
args = append(args,
id,
m.SessionID, m.Ordinal, m.Role, m.Content,
m.ThinkingText,
m.Timestamp, m.HasThinking, m.HasToolUse,
m.ContentLength, m.IsSystem,
m.Model, string(m.TokenUsage),
m.ContextTokens, m.OutputTokens,
m.HasContextTokens, m.HasOutputTokens,
m.ClaudeMessageID, m.ClaudeRequestID,
m.SourceType, m.SourceSubtype, m.SourceUUID,
m.SourceParentUUID, m.IsSidechain, m.IsCompactBoundary,
)
}
query := fmt.Sprintf(
"INSERT INTO messages (id, %s) VALUES %s",
insertMessageCols,
multiRowPlaceholders(len(batch), 25),
)
if _, err := tx.Exec(query, args...); err != nil {
first := batch[0].Ordinal
last := batch[len(batch)-1].Ordinal
return nil, fmt.Errorf(
"inserting messages ord=%d..%d: %w",
first, last, err,
)
}
}
return ids, nil
}
func nextMessageIDTx(tx *sql.Tx) (int64, error) {
var n sql.NullInt64
if err := tx.QueryRow("SELECT MAX(id) FROM messages").Scan(&n); err != nil {
return 0, fmt.Errorf("reading next message id: %w", err)
}
if !n.Valid {
return 1, nil
}
return n.Int64 + 1, nil
}
func multiRowPlaceholders(rows, cols int) string {
var b strings.Builder
for i := range rows {
if i > 0 {
b.WriteByte(',')
}
b.WriteByte('(')
for j := range cols {
if j > 0 {
b.WriteByte(',')
}
b.WriteByte('?')
}
b.WriteByte(')')
}
return b.String()
}
func insertToolCallsChunkTx(
tx *sql.Tx, calls []ToolCall,
) error {
args := make([]any, 0, len(calls)*10)
for _, tc := range calls {
args = append(args,
tc.MessageID, tc.SessionID,
tc.ToolName, tc.Category,
nilIfEmpty(tc.ToolUseID),
nilIfEmpty(tc.InputJSON),
nilIfEmpty(tc.SkillName),
nilIfZero(tc.ResultContentLength),
nilIfEmpty(tc.ResultContent),
nilIfEmpty(tc.SubagentSessionID),
)
}
query := `
INSERT INTO tool_calls
(message_id, session_id, tool_name, category,
tool_use_id, input_json, skill_name,
result_content_length, result_content, subagent_session_id)
VALUES ` + multiRowPlaceholders(len(calls), 10)
if _, err := tx.Exec(query, args...); err != nil {
return fmt.Errorf(
"inserting tool_calls batch (%d rows): %w",
len(calls), err,
)
}
return nil
}
func insertToolResultEventsChunkTx(
tx *sql.Tx, rows []toolResultEventRow,
) error {
args := make([]any, 0, len(rows)*12)
for _, r := range rows {
args = append(args,
r.SessionID, r.MessageOrdinal, r.CallIndex,
nilIfEmpty(r.Event.ToolUseID),
nilIfEmpty(r.Event.AgentID),
nilIfEmpty(r.Event.SubagentSessionID),
r.Event.Source, r.Event.Status,
r.Event.Content,
r.Event.ContentLength,
nilIfEmpty(r.Event.Timestamp),
r.Event.EventIndex,
)
}
query := `
INSERT INTO tool_result_events
(session_id, tool_call_message_ordinal, call_index,
tool_use_id, agent_id, subagent_session_id,
source, status, content, content_length,
timestamp, event_index)
VALUES ` + multiRowPlaceholders(len(rows), 12)
if _, err := tx.Exec(query, args...); err != nil {
return fmt.Errorf(
"inserting tool_result_events batch (%d rows): %w",
len(rows), err,
)
}
return nil
}
func nilIfEmpty(s string) any {
if s == "" {
return nil
}
return s
}
func nilIfZero(n int) any {
if n == 0 {
return nil
}
return n
}
// insertToolCallsTx batch-inserts tool calls within an
// existing transaction.
func insertToolCallsTx(
tx *sql.Tx, calls []ToolCall,
) error {
for start := 0; start < len(calls); start += toolCallInsertRowsPerStmt {
end := min(start+toolCallInsertRowsPerStmt, len(calls))
if err := insertToolCallsChunkTx(tx, calls[start:end]); err != nil {
return err
}
}
return nil
}
func insertToolResultEventsTx(
tx *sql.Tx, rows []toolResultEventRow,
) error {
for start := 0; start < len(rows); start += toolResultEventInsertRowsPerStmt {
end := min(start+toolResultEventInsertRowsPerStmt, len(rows))
if err := insertToolResultEventsChunkTx(tx, rows[start:end]); err != nil {
return err
}
}
return nil
}
const slowOpThreshold = 100 * time.Millisecond
// InsertMessages batch-inserts messages for a session.
func (db *DB) InsertMessages(msgs []Message) error {
if len(msgs) == 0 {
return nil
}
t := time.Now()
defer func() {
if d := time.Since(t); d > slowOpThreshold {
log.Printf(
"db: InsertMessages (%d msgs): %s",
len(msgs), d.Round(time.Millisecond),
)
}
}()
db.mu.Lock()
defer db.mu.Unlock()
tx, err := db.getWriter().Begin()
if err != nil {
return fmt.Errorf("beginning tx: %w", err)
}
defer func() { _ = tx.Rollback() }()
ids, err := insertMessagesTx(tx, msgs)
if err != nil {
return err
}
toolCalls := resolveToolCalls(msgs, ids)
if err := insertToolCallsTx(tx, toolCalls); err != nil {
return err
}
events := resolveToolResultEvents(msgs)
if err := insertToolResultEventsTx(tx, events); err != nil {
return err
}
for _, sessionID := range messageSessionIDs(msgs) {
if err := setSessionAutomationFromMessagesTx(
tx, sessionID,
); err != nil {
return err
}
}
return tx.Commit()
}
func messageSessionIDs(msgs []Message) []string {
seen := make(map[string]struct{})
ids := make([]string, 0, 1)
for _, m := range msgs {
if m.SessionID == "" {
continue
}
if _, ok := seen[m.SessionID]; ok {
continue
}
seen[m.SessionID] = struct{}{}
ids = append(ids, m.SessionID)
}
return ids
}
// MaxOrdinal returns the highest ordinal for a session,
// or -1 if the session has no messages.
func (db *DB) MaxOrdinal(sessionID string) int {
var n sql.NullInt64
err := db.getReader().QueryRow(
"SELECT MAX(ordinal) FROM messages"+
" WHERE session_id = ?",
sessionID,
).Scan(&n)
if err != nil || !n.Valid {
return -1
}
return int(n.Int64)
}
// LastClaudeMessageID returns the claude_message_id of the
// highest-ordinal assistant message in a session whose
// claude_message_id is non-empty, or "" if none exists. The sync
// engine uses this to detect cross-sync splits of a single
// streaming response (next sync's first appended assistant entry
// shares the message.id of the previously-stored last assistant).
func (db *DB) LastClaudeMessageID(sessionID string) string {
var s sql.NullString
err := db.getReader().QueryRow(
`SELECT claude_message_id FROM messages
WHERE session_id = ?
AND role = 'assistant'
AND claude_message_id != ''
ORDER BY ordinal DESC
LIMIT 1`,
sessionID,
).Scan(&s)
if err != nil || !s.Valid {
return ""
}
return s.String
}
// savedPin captures the minimal pin state needed to re-attach a pin
// after a full message replacement. source_uuid is the preferred
// identifier because it survives rewrites where the ordinal stream
// shifts (e.g. when newly-emitted compact-boundary messages are
// inserted between previously-seen rows). The ordinal is kept as a
// fallback for legacy pins on rows that lack a source_uuid.
type savedPin struct {
sourceUUID string
ordinal int
note *string
createdAt string
}
// ReplaceSessionMessages deletes existing and inserts new messages
// in a single transaction. Any existing pins are preserved by
// re-attaching them to the new message rows that share the same
// ordinal (pins for ordinals that no longer exist are dropped).
func (db *DB) ReplaceSessionMessages(
sessionID string, msgs []Message,
) error {
t := time.Now()
defer func() {
if d := time.Since(t); d > slowOpThreshold {
log.Printf(
"db: ReplaceSessionMessages %s (%d msgs): %s",
sessionID, len(msgs),
d.Round(time.Millisecond),
)
}
}()
db.mu.Lock()
defer db.mu.Unlock()
tx, err := db.getWriter().Begin()
if err != nil {
return fmt.Errorf("beginning tx: %w", err)
}
defer func() { _ = tx.Rollback() }()
if err := replaceSessionMessagesTx(tx, sessionID, msgs); err != nil {
return err
}
if err := updateSessionAutomationFromMessagesTx(tx, sessionID); err != nil {
return err
}
// The new messages invalidate any findings scanned from the old content, so
// clear them and reset the scan state (empty version => secrets scan
// --backfill re-scans). ReplaceSessionContent does not call this method; it
// supplies fresh findings via replaceSecretFindingsTx directly.
if err := replaceSecretFindingsTx(tx, sessionID, nil, 0, ""); err != nil {
return err
}
return tx.Commit()
}
// replaceSessionMessagesTx performs the full message-replace sequence within
// an existing transaction: saves pins, deletes old tool_calls /
// tool_result_events / messages (with FTS optimisation), inserts new messages
// + tool_calls + tool_result_events, then restores pins. Caller owns the lock
// and transaction lifecycle.
func replaceSessionMessagesTx(
tx *sql.Tx, sessionID string, msgs []Message,
) error {
pins, err := savePinsTx(tx, sessionID)
if err != nil {
return err
}
if _, err := tx.Exec(
"DELETE FROM tool_calls WHERE session_id = ?",
sessionID,
); err != nil {
return fmt.Errorf("deleting old tool_calls: %w", err)
}
if _, err := tx.Exec(
"DELETE FROM tool_result_events WHERE session_id = ?",
sessionID,
); err != nil {
return fmt.Errorf(
"deleting old tool_result_events: %w", err,
)
}
// FTS5 is optional (the module may be missing in the runtime).
// Probe sqlite_master so the bulk-delete + trigger-swap dance
// only runs when there's actually an FTS table to maintain.
var ftsCount int
if err := tx.QueryRow(
`SELECT count(*) FROM sqlite_master
WHERE type='table' AND name='messages_fts'`,
).Scan(&ftsCount); err != nil {
return fmt.Errorf("probing fts table: %w", err)
}
hasFTS := ftsCount > 0
if hasFTS {
// Bulk-delete the FTS index entries up-front in a single SQL
// statement, then drop the per-row messages_ad trigger so the
// upcoming DELETE FROM messages doesn't re-fire the FTS5
// 'delete' command for every row. With large sessions
// (thousands of rows where a single content blob can be many
// MB) the per-row trigger path is dominated by FTS
// tokenization and stalls the writer for minutes; the bulk
// INSERT...SELECT path is effectively flat. The trigger is
// restored before the transaction is allowed to commit.
if _, err := tx.Exec(
`INSERT INTO messages_fts(messages_fts, rowid, content)
SELECT 'delete', id, content
FROM messages WHERE session_id = ?`,
sessionID,
); err != nil {
return fmt.Errorf("bulk-deleting fts entries: %w", err)
}
if _, err := tx.Exec(
"DROP TRIGGER IF EXISTS messages_ad",
); err != nil {
return fmt.Errorf("dropping messages_ad trigger: %w", err)
}
}
if _, err := tx.Exec(
"DELETE FROM messages WHERE session_id = ?", sessionID,
); err != nil {
return fmt.Errorf("deleting old messages: %w", err)
}
if hasFTS {
if _, err := tx.Exec(messagesADTriggerDDL); err != nil {
return fmt.Errorf("restoring messages_ad trigger: %w", err)
}
}
if len(msgs) > 0 {
ids, err := insertMessagesTx(tx, msgs)
if err != nil {
return err
}
toolCalls := resolveToolCalls(msgs, ids)
if err := insertToolCallsTx(tx, toolCalls); err != nil {
return err
}
events := resolveToolResultEvents(msgs)
if err := insertToolResultEventsTx(tx, events); err != nil {
return err
}
}
return restorePinsTx(tx, sessionID, pins)
}
// ReplaceSessionContent atomically replaces a session's messages, signal
// columns, and secret findings in one transaction, so the derived data can
// never diverge from the messages it was computed from.
func (db *DB) ReplaceSessionContent(
sessionID string, msgs []Message,
signals SessionSignalUpdate, findings []SecretFinding,
) error {
db.mu.Lock()
defer db.mu.Unlock()
tx, err := db.getWriter().Begin()
if err != nil {
return fmt.Errorf("beginning tx: %w", err)
}
defer func() { _ = tx.Rollback() }()
if err := replaceSessionMessagesTx(tx, sessionID, msgs); err != nil {
return err
}
if err := updateSessionAutomationFromMessagesTx(tx, sessionID); err != nil {
return err
}
if err := updateSessionSignalsTx(tx, sessionID, signals); err != nil {
return err
}
// replaceSecretFindingsTx is the sole writer of secret_leak_count/
// secrets_rules_version (updateSessionSignalsTx leaves them untouched), so
// the count cannot diverge from the findings it summarizes.
if err := replaceSecretFindingsTx(tx, sessionID, findings,
signals.SecretLeakCount, signals.SecretsRulesVersion); err != nil {
return err
}
return tx.Commit()
}
func updateSessionAutomationFromMessagesTx(
tx *sql.Tx, sessionID string,
) error {
want, rowAutomated, ok, err := sessionAutomationStateTx(
tx, sessionID,
)
if err != nil || !ok {
return err
}
if want == rowAutomated {
return nil
}
return setSessionAutomationTx(tx, sessionID, want)
}
func setSessionAutomationFromMessagesTx(
tx *sql.Tx, sessionID string,
) error {
want, rowAutomated, ok, err := sessionAutomationStateTx(
tx, sessionID,
)
if err != nil || !ok || !want || rowAutomated {
return err
}
return setSessionAutomationTx(tx, sessionID, true)
}
func sessionAutomationStateTx(
tx *sql.Tx, sessionID string,
) (want, rowAutomated, ok bool, err error) {
var (
firstMessage sql.NullString
firstUserMessage sql.NullString
userMsgCount int
)
err = tx.QueryRow(`
SELECT
s.first_message,
s.user_message_count,
s.is_automated,
(
SELECT m.content
FROM messages m
WHERE m.session_id = s.id
AND m.role = 'user'
AND m.is_system = 0
AND TRIM(m.content) <> ''
ORDER BY m.ordinal
LIMIT 1
) AS first_user_message
FROM sessions s
WHERE s.id = ?`,
sessionID,
).Scan(
&firstMessage, &userMsgCount,
&rowAutomated, &firstUserMessage,
)
if errors.Is(err, sql.ErrNoRows) {
return false, false, false, nil
}
if err != nil {
return false, false, false, fmt.Errorf(
"reading automation candidate for %s: %w",
sessionID, err,
)
}
want = isAutomatedFromTextCandidates(
userMsgCount, firstUserMessage, firstMessage,
)
return want, rowAutomated, true, nil
}
func setSessionAutomationTx(
tx *sql.Tx, sessionID string, isAutomated bool,
) error {
if _, err := tx.Exec(`
UPDATE sessions
SET is_automated = ?,
local_modified_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')
WHERE id = ?`,
isAutomated, sessionID,
); err != nil {
return fmt.Errorf(
"updating is_automated from messages for %s: %w",
sessionID, err,
)
}
return nil
}
func savePinsTx(tx *sql.Tx, sessionID string) ([]savedPin, error) {
// Save existing pins before deletion. The ON DELETE CASCADE on
// pinned_messages.message_id would otherwise wipe them when
// messages are deleted below. source_uuid comes from the joined
// message row; LEFT JOIN keeps pins on legacy rows whose
// message_id no longer resolves cleanly.
pinRows, err := tx.Query(`
SELECT p.ordinal, COALESCE(m.source_uuid, ''),
p.note, p.created_at
FROM pinned_messages p
LEFT JOIN messages m ON m.id = p.message_id
WHERE p.session_id = ?`,
sessionID,
)
if err != nil {
return nil, fmt.Errorf("saving pins: %w", err)
}
defer pinRows.Close()
var pins []savedPin
for pinRows.Next() {
var sp savedPin
if err := pinRows.Scan(
&sp.ordinal, &sp.sourceUUID, &sp.note, &sp.createdAt,
); err != nil {
return nil, fmt.Errorf("scanning pin: %w", err)
}
pins = append(pins, sp)
}
if err := pinRows.Err(); err != nil {
return nil, fmt.Errorf("iterating pins: %w", err)
}
return pins, nil
}
func restorePinsTx(
tx *sql.Tx, sessionID string, pins []savedPin,
) error {
// Re-attach saved pins. Prefer source_uuid (stable across
// ordinal-shifting rewrites) and fall back to ordinal for
// legacy pins whose source row predates the source_uuid column.
// Pins whose row no longer exists by either key are silently
// dropped.
for _, sp := range pins {
if sp.sourceUUID != "" {
res, err := tx.Exec(`
INSERT OR IGNORE INTO pinned_messages
(session_id, message_id, ordinal, note, created_at)
SELECT ?, m.id, m.ordinal, ?, ?
FROM messages m
WHERE m.session_id = ? AND m.source_uuid = ?`,
sessionID, sp.note, sp.createdAt, sessionID, sp.sourceUUID,
)
if err != nil {
return fmt.Errorf(
"restoring pin uuid=%s: %w", sp.sourceUUID, err,
)
}
if n, _ := res.RowsAffected(); n > 0 {
continue
}
}
if _, err := tx.Exec(`
INSERT OR IGNORE INTO pinned_messages
(session_id, message_id, ordinal, note, created_at)
SELECT ?, m.id, m.ordinal, ?, ?
FROM messages m
WHERE m.session_id = ? AND m.ordinal = ?`,
sessionID, sp.note, sp.createdAt, sessionID, sp.ordinal,
); err != nil {
return fmt.Errorf("restoring pin ord=%d: %w", sp.ordinal, err)
}
}
return nil
}
// attachToolCalls loads tool_calls for the given messages
// and attaches them to each message's ToolCalls field.
func (db *DB) attachToolCalls(
ctx context.Context, msgs []Message,
) error {
if len(msgs) == 0 {
return nil
}
idToIdx := make(map[int64]int, len(msgs))
ids := make([]int64, len(msgs))
for i, m := range msgs {
ids[i] = m.ID
idToIdx[m.ID] = i
}
for i := 0; i < len(ids); i += attachToolCallBatchSize {
end := min(i+attachToolCallBatchSize, len(ids))
if err := db.attachToolCallsBatch(
ctx, msgs, idToIdx, ids[i:end],
); err != nil {
return err
}
}
if err := db.attachToolResultEvents(ctx, msgs); err != nil {
return err
}
return nil
}
func (db *DB) attachToolCallsBatch(
ctx context.Context,
msgs []Message,
idToIdx map[int64]int,
batch []int64,
) error {
if len(batch) == 0 {
return nil
}
args := make([]any, len(batch))
placeholders := make([]string, len(batch))
for i, id := range batch {
args[i] = id
placeholders[i] = "?"
}
query := fmt.Sprintf(`
SELECT message_id, session_id, tool_name, category,
tool_use_id, input_json, skill_name,
result_content_length, result_content, subagent_session_id
FROM tool_calls
WHERE message_id IN (%s)
ORDER BY id`,
strings.Join(placeholders, ","))
rows, err := db.getReader().QueryContext(ctx, query, args...)
if err != nil {
return fmt.Errorf("querying tool_calls: %w", err)
}
defer rows.Close()
for rows.Next() {
var tc ToolCall
var toolUseID, inputJSON, skillName sql.NullString
var subagentSessionID, resultContent sql.NullString
var resultLen sql.NullInt64
if err := rows.Scan(
&tc.MessageID, &tc.SessionID,
&tc.ToolName, &tc.Category,
&toolUseID, &inputJSON, &skillName,
&resultLen, &resultContent, &subagentSessionID,
); err != nil {
return fmt.Errorf("scanning tool_call: %w", err)
}
if toolUseID.Valid {
tc.ToolUseID = toolUseID.String
}
if inputJSON.Valid {
tc.InputJSON = inputJSON.String
}
if skillName.Valid {
tc.SkillName = skillName.String
}
if resultLen.Valid {
tc.ResultContentLength = int(resultLen.Int64)
}
if resultContent.Valid {
tc.ResultContent = resultContent.String
}
if subagentSessionID.Valid {
tc.SubagentSessionID = subagentSessionID.String
}
if idx, ok := idToIdx[tc.MessageID]; ok {
msgs[idx].ToolCalls = append(
msgs[idx].ToolCalls, tc,
)
}
}
return rows.Err()
}
func (db *DB) attachToolResultEvents(
ctx context.Context, msgs []Message,
) error {
if len(msgs) == 0 {
return nil
}
sessionID := msgs[0].SessionID
ordToIdx := make(map[int]int, len(msgs))
ordinals := make([]int, 0, len(msgs))
for i, m := range msgs {
ordToIdx[m.Ordinal] = i
ordinals = append(ordinals, m.Ordinal)
}
for i := 0; i < len(ordinals); i += attachToolCallBatchSize {
end := min(i+attachToolCallBatchSize, len(ordinals))
if err := db.attachToolResultEventsBatch(
ctx, msgs, ordToIdx, sessionID, ordinals[i:end],
); err != nil {
return err
}
}
return nil
}
func (db *DB) attachToolResultEventsBatch(
ctx context.Context,
msgs []Message,
ordToIdx map[int]int,
sessionID string,
ordinals []int,
) error {
if len(ordinals) == 0 {
return nil
}
args := []any{sessionID}
placeholders := make([]string, len(ordinals))
for i, ord := range ordinals {
args = append(args, ord)
placeholders[i] = "?"
}
query := fmt.Sprintf(`
SELECT tool_call_message_ordinal, call_index,
tool_use_id, agent_id, subagent_session_id,
source, status, content, content_length,
timestamp, event_index
FROM tool_result_events
WHERE session_id = ? AND tool_call_message_ordinal IN (%s)
ORDER BY tool_call_message_ordinal, call_index, event_index`,
strings.Join(placeholders, ","))
rows, err := db.getReader().QueryContext(ctx, query, args...)
if err != nil {
return fmt.Errorf("querying tool_result_events: %w", err)
}
defer rows.Close()
for rows.Next() {