forked from kenn-io/agentsview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsessions.go
More file actions
2215 lines (2061 loc) · 66.1 KB
/
Copy pathsessions.go
File metadata and controls
2215 lines (2061 loc) · 66.1 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/hmac"
"crypto/sha256"
"database/sql"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
)
// ErrInvalidCursor is returned when a cursor cannot be decoded or verified.
var ErrInvalidCursor = errors.New("invalid cursor")
// ErrSessionExcluded is returned by UpsertSession when the
// session was permanently deleted by the user. Callers should
// skip any follow-up writes (messages, tool_calls) for this session.
var ErrSessionExcluded = errors.New("session excluded")
// ErrSessionTrashed is returned by UpsertSession when the
// session currently exists in the trash. Upload/import callers
// should surface a conflict instead of silently overwriting it.
var ErrSessionTrashed = errors.New("session trashed")
// sessionBaseCols is the column list for standard session queries
// (list, get). Keep in sync with scanSessionRow.
const sessionBaseCols = `id, project, machine, agent,
first_message, COALESCE(display_name, session_name) AS display_name, started_at, ended_at,
message_count, user_message_count,
parent_session_id, relationship_type,
total_output_tokens, peak_context_tokens,
has_total_output_tokens, has_peak_context_tokens,
is_automated,
tool_failure_signal_count, tool_retry_count,
edit_churn_count, consecutive_failure_max,
outcome, outcome_confidence,
ended_with_role, final_failure_streak,
signals_pending_since,
compaction_count, mid_task_compaction_count,
context_pressure_max,
health_score, health_grade,
has_tool_calls, has_context_data,
secret_leak_count, secrets_rules_version,
data_version,
cwd, git_branch, source_session_id, source_version,
parser_malformed_lines, is_truncated,
deleted_at, termination_status, created_at`
// sessionPruneCols extends sessionBaseCols with file metadata
// needed by FindPruneCandidates.
const sessionPruneCols = `id, project, machine, agent,
first_message, COALESCE(display_name, session_name) AS display_name, started_at, ended_at,
message_count, user_message_count,
parent_session_id, relationship_type,
total_output_tokens, peak_context_tokens,
has_total_output_tokens, has_peak_context_tokens,
is_automated,
tool_failure_signal_count, tool_retry_count,
edit_churn_count, consecutive_failure_max,
outcome, outcome_confidence,
ended_with_role, final_failure_streak,
signals_pending_since,
compaction_count, mid_task_compaction_count,
context_pressure_max,
health_score, health_grade,
has_tool_calls, has_context_data,
secret_leak_count, secrets_rules_version,
data_version,
cwd, git_branch, source_session_id, source_version,
parser_malformed_lines, is_truncated,
deleted_at, termination_status, file_path, file_size, created_at`
// sessionFullCols includes all columns for a complete session record.
const sessionFullCols = `id, project, machine, agent,
first_message, display_name, session_name, started_at, ended_at,
message_count, user_message_count,
parent_session_id, relationship_type,
total_output_tokens, peak_context_tokens,
has_total_output_tokens, has_peak_context_tokens,
is_automated,
tool_failure_signal_count, tool_retry_count,
edit_churn_count, consecutive_failure_max,
outcome, outcome_confidence,
ended_with_role, final_failure_streak,
signals_pending_since,
compaction_count, mid_task_compaction_count,
context_pressure_max,
health_score, health_grade,
has_tool_calls, has_context_data,
secret_leak_count, secrets_rules_version,
data_version,
cwd, git_branch, source_session_id, source_version,
parser_malformed_lines, is_truncated,
deleted_at, termination_status, file_path, file_size, file_mtime,
file_inode, file_device,
file_hash, local_modified_at, created_at`
const (
// DefaultSessionLimit is the default number of sessions returned.
DefaultSessionLimit = 200
// MaxSessionLimit is the maximum number of sessions returned.
MaxSessionLimit = 500
)
// rowScanner is satisfied by both *sql.Row and *sql.Rows,
// allowing a single scan helper for both.
type rowScanner interface {
Scan(dest ...any) error
}
// scanSessionRow scans sessionBaseCols into a Session.
func scanSessionRow(rs rowScanner) (Session, error) {
var s Session
err := rs.Scan(
&s.ID, &s.Project, &s.Machine, &s.Agent,
&s.FirstMessage, &s.DisplayName, &s.StartedAt, &s.EndedAt,
&s.MessageCount, &s.UserMessageCount,
&s.ParentSessionID, &s.RelationshipType,
&s.TotalOutputTokens, &s.PeakContextTokens,
&s.HasTotalOutputTokens, &s.HasPeakContextTokens,
&s.IsAutomated,
&s.ToolFailureSignalCount, &s.ToolRetryCount,
&s.EditChurnCount, &s.ConsecutiveFailureMax,
&s.Outcome, &s.OutcomeConfidence,
&s.EndedWithRole, &s.FinalFailureStreak,
&s.SignalsPendingSince,
&s.CompactionCount, &s.MidTaskCompactionCount,
&s.ContextPressureMax,
&s.HealthScore, &s.HealthGrade,
&s.HasToolCalls, &s.HasContextData,
&s.SecretLeakCount, &s.SecretsRulesVersion,
&s.DataVersion,
&s.Cwd, &s.GitBranch,
&s.SourceSessionID, &s.SourceVersion,
&s.ParserMalformedLines, &s.IsTruncated,
&s.DeletedAt, &s.TerminationStatus, &s.CreatedAt,
)
return s, err
}
// Session represents a row in the sessions table.
type Session struct {
ID string `json:"id"`
Project string `json:"project"`
Machine string `json:"machine"`
Agent string `json:"agent"`
FirstMessage *string `json:"first_message"`
DisplayName *string `json:"display_name,omitempty"`
SessionName *string `json:"-"`
StartedAt *string `json:"started_at"`
EndedAt *string `json:"ended_at"`
MessageCount int `json:"message_count"`
UserMessageCount int `json:"user_message_count"`
ParentSessionID *string `json:"parent_session_id,omitempty"`
RelationshipType string `json:"relationship_type,omitempty"`
TotalOutputTokens int `json:"total_output_tokens"`
PeakContextTokens int `json:"peak_context_tokens"`
HasTotalOutputTokens bool `json:"has_total_output_tokens"`
HasPeakContextTokens bool `json:"has_peak_context_tokens"`
IsAutomated bool `json:"is_automated"`
// Session signals (computed from messages/tool_calls).
ToolFailureSignalCount int `json:"tool_failure_signal_count"`
ToolRetryCount int `json:"tool_retry_count"`
EditChurnCount int `json:"edit_churn_count"`
ConsecutiveFailureMax int `json:"consecutive_failure_max"`
Outcome string `json:"outcome"`
OutcomeConfidence string `json:"outcome_confidence"`
EndedWithRole string `json:"ended_with_role"`
FinalFailureStreak int `json:"final_failure_streak"`
SignalsPendingSince *string `json:"signals_pending_since,omitempty"`
CompactionCount int `json:"compaction_count"`
MidTaskCompactionCount int `json:"mid_task_compaction_count"`
ContextPressureMax *float64 `json:"context_pressure_max,omitempty"`
HealthScore *int `json:"health_score,omitempty"`
HealthGrade *string `json:"health_grade,omitempty"`
HasToolCalls bool `json:"-"`
HasContextData bool `json:"-"`
SecretLeakCount int `json:"secret_leak_count"`
SecretsRulesVersion string `json:"-"`
DataVersion int `json:"-"`
Cwd string `json:"cwd,omitempty"`
GitBranch string `json:"git_branch,omitempty"`
SourceSessionID string `json:"source_session_id,omitempty"`
SourceVersion string `json:"source_version,omitempty"`
ParserMalformedLines int `json:"parser_malformed_lines,omitempty"`
IsTruncated bool `json:"is_truncated,omitempty"`
DeletedAt *string `json:"deleted_at,omitempty"`
TerminationStatus *string `json:"termination_status,omitempty"`
FilePath *string `json:"file_path,omitempty"`
FileSize *int64 `json:"file_size,omitempty"`
FileMtime *int64 `json:"file_mtime,omitempty"`
FileInode *int64 `json:"file_inode,omitempty"`
FileDevice *int64 `json:"file_device,omitempty"`
FileHash *string `json:"file_hash,omitempty"`
LocalModifiedAt *string `json:"local_modified_at,omitempty"`
CreatedAt string `json:"created_at"`
}
// SessionCursor is the opaque pagination token.
type SessionCursor struct {
EndedAt string `json:"e"`
ID string `json:"i"`
Total int `json:"t,omitempty"`
}
// EncodeCursor returns a base64-encoded cursor string.
func (db *DB) EncodeCursor(endedAt, id string, total ...int) string {
t := 0
if len(total) > 0 {
t = total[0]
}
c := SessionCursor{EndedAt: endedAt, ID: id, Total: t}
data, _ := json.Marshal(c)
db.cursorMu.RLock()
mac := hmac.New(sha256.New, db.cursorSecret)
db.cursorMu.RUnlock()
mac.Write(data)
sig := mac.Sum(nil)
return base64.RawURLEncoding.EncodeToString(data) + "." +
base64.RawURLEncoding.EncodeToString(sig)
}
// DecodeCursor parses a base64-encoded cursor string.
func (db *DB) DecodeCursor(s string) (SessionCursor, error) {
parts := strings.Split(s, ".")
if len(parts) == 1 {
// Legacy cursor (unsigned). Trust nothing about the Total.
data, err := base64.RawURLEncoding.DecodeString(parts[0])
if err != nil {
return SessionCursor{}, fmt.Errorf("%w: %v", ErrInvalidCursor, err)
}
var c SessionCursor
if err := json.Unmarshal(data, &c); err != nil {
return SessionCursor{}, fmt.Errorf("%w: %v", ErrInvalidCursor, err)
}
c.Total = 0 // Force re-computation
return c, nil
} else if len(parts) != 2 {
return SessionCursor{}, fmt.Errorf("%w: invalid format", ErrInvalidCursor)
}
payload := parts[0]
sigStr := parts[1]
data, err := base64.RawURLEncoding.DecodeString(payload)
if err != nil {
return SessionCursor{}, fmt.Errorf("%w: invalid payload: %v", ErrInvalidCursor, err)
}
sig, err := base64.RawURLEncoding.DecodeString(sigStr)
if err != nil {
return SessionCursor{}, fmt.Errorf("%w: invalid signature encoding: %v", ErrInvalidCursor, err)
}
db.cursorMu.RLock()
mac := hmac.New(sha256.New, db.cursorSecret)
db.cursorMu.RUnlock()
mac.Write(data)
expectedSig := mac.Sum(nil)
if !hmac.Equal(sig, expectedSig) {
return SessionCursor{}, fmt.Errorf("%w: signature mismatch", ErrInvalidCursor)
}
var c SessionCursor
if err := json.Unmarshal(data, &c); err != nil {
return SessionCursor{}, fmt.Errorf("%w: invalid json: %v", ErrInvalidCursor, err)
}
return c, nil
}
// SessionFilter specifies how to query sessions.
type SessionFilter struct {
Project string
ExcludeProject string // exclude sessions with this project name
Machine string
Agent string
Date string // exact date YYYY-MM-DD
DateFrom string // range start (inclusive)
DateTo string // range end (inclusive)
ActiveSince string // ISO-8601 timestamp; filters on most recent activity
MinMessages int // message_count >= N (0 = no filter)
MaxMessages int // message_count <= N (0 = no filter)
MinUserMessages int // user_message_count >= N (0 = no filter)
ExcludeOneShot bool // exclude sessions with user_message_count <= 1
ExcludeAutomated bool // exclude sessions where is_automated = 1
IncludeChildren bool // include subagent sessions (for sidebar grouping)
Outcome []string // filter by outcome values
HealthGrade []string // filter by health grade values
MinToolFailures *int // minimum tool_failure_signal_count
HasSecret bool // only sessions with current secret_leak_count > 0
Starred bool // only sessions starred by the user
// SecretsRulesVersions limits HasSecret to sessions scanned by one of these
// current scanner versions. Empty preserves raw DB semantics for tests and
// direct store callers that explicitly want unversioned counts.
SecretsRulesVersions []string
Cursor string // opaque cursor from previous page
Limit int
// Termination filters by termination_status:
// "" or "all" → no filter (default)
// "clean" → only sessions with status = 'clean'
// "unclean" → only sessions with status IN
// ('tool_call_pending', 'truncated')
Termination string
}
// activeWindow is the freshness window for "active" sessions
// (last activity within this duration).
const activeWindow = 10 * time.Minute
// staleWindow is the upper bound for "stale" sessions. Past this
// idle duration with an orphan tool call, the session is "unclean".
const staleWindow = 60 * time.Minute
// activityExprSQLite computes seconds-since-epoch of the most
// recent activity timestamp. Used by both sessions and analytics
// filters when classifying by status.
const activityExprSQLite = "CAST(strftime('%s', " +
"COALESCE(ended_at, started_at, created_at)) AS INTEGER)"
const sidebarActivityExprSQLiteS = "COALESCE(" +
"NULLIF(s.ended_at, ''), NULLIF(s.started_at, ''), s.created_at)"
const sidebarChildRelationshipsSQL = "'subagent', 'fork', 'continuation'"
func sidebarStarredRootCTE(enabled bool) string {
if !enabled {
return ""
}
return `,
eligible_roots(id) AS (
SELECT DISTINCT t.root_id
FROM tree t
JOIN starred_sessions ss ON ss.session_id = t.id
)`
}
func sidebarStarredRootJoin(enabled bool) string {
if !enabled {
return ""
}
return "JOIN eligible_roots e ON e.id = t.root_id"
}
// buildTerminationPredSQLite returns a WHERE fragment and args for
// the multi-state termination filter (active / stale / unclean).
// The status value may be comma-separated to OR multiple states
// (e.g. "stale,unclean"). Returns ("", nil) when empty or "all".
//
// Stale and unclean both require a parser red flag
// (tool_call_pending or truncated). Sessions classified as clean
// or with NULL termination_status never appear under those
// filters — the parser-side classifier is the only positive
// signal that something is wrong. Active is purely time-based:
// any session written to in the last activeWindow qualifies.
func buildTerminationPredSQLite(status string) (string, []any) {
b := NewQueryBuilder(SQLiteQueryDialect(), 0)
pred := terminationPredicate(status, b, func(col string) string {
return col
})
return pred, b.Args()
}
// SessionPage is a page of session results.
type SessionPage struct {
Sessions []Session `json:"sessions"`
NextCursor string `json:"next_cursor,omitempty"`
Total int `json:"total"`
}
type SidebarSessionIndexRow struct {
ID string `json:"id"`
ParentSessionID *string `json:"parent_session_id,omitempty"`
RelationshipType string `json:"relationship_type,omitempty"`
Project string `json:"project"`
Machine string `json:"machine"`
Agent string `json:"agent"`
DisplayName *string `json:"display_name,omitempty"`
StartedAt *string `json:"started_at"`
EndedAt *string `json:"ended_at"`
CreatedAt string `json:"created_at"`
TerminationStatus *string `json:"termination_status,omitempty"`
MessageCount int `json:"message_count"`
UserMessageCount int `json:"user_message_count"`
IsAutomated bool `json:"is_automated"`
IsTeammate bool `json:"is_teammate"`
}
type SidebarSessionIndex struct {
Sessions []SidebarSessionIndexRow `json:"sessions"`
NextCursor string `json:"next_cursor,omitempty"`
Total int `json:"total"`
}
// buildSessionFilter returns a WHERE clause and args for the
// non-cursor predicates in SessionFilter.
func buildSessionFilter(f SessionFilter) (string, []any) {
return BuildSessionFilterSQL(f, SQLiteQueryDialect())
}
// ListSessions returns a cursor-paginated list of sessions.
func (db *DB) ListSessions(
ctx context.Context, f SessionFilter,
) (SessionPage, error) {
if f.Limit <= 0 || f.Limit > MaxSessionLimit {
f.Limit = DefaultSessionLimit
}
where, args := buildSessionFilter(f)
var total int
var cur SessionCursor
if f.Cursor != "" {
var err error
cur, err = db.DecodeCursor(f.Cursor)
if err != nil {
return SessionPage{}, err
}
total = cur.Total
}
// Total count applies filters but not cursor. To avoid
// re-counting on every pagination request, newer cursors carry
// the first-page total and we reuse it here.
if total <= 0 {
countQuery := "SELECT COUNT(*) FROM sessions WHERE " + where
if err := db.getReader().QueryRowContext(
ctx, countQuery, args...,
).Scan(&total); err != nil {
return SessionPage{},
fmt.Errorf("counting sessions: %w", err)
}
}
// Paginated results
cursorArgs := append([]any{}, args...)
pageBuilder := NewQueryBuilder(SQLiteQueryDialect(), len(args))
cursorWhere := where
if f.Cursor != "" {
cursorWhere += " AND " +
pageBuilder.CursorBeforePredicate(cur)
}
query := "SELECT " + sessionBaseCols +
" FROM sessions WHERE " + cursorWhere + `
ORDER BY COALESCE(
NULLIF(ended_at, ''),
NULLIF(started_at, ''),
created_at
) DESC, id DESC
` + pageBuilder.Limit(f.Limit+1)
cursorArgs = append(cursorArgs, pageBuilder.Args()...)
rows, err := db.getReader().QueryContext(ctx, query, cursorArgs...)
if err != nil {
return SessionPage{},
fmt.Errorf("querying sessions: %w", err)
}
defer rows.Close()
sessions, err := scanSessionRows(rows)
if err != nil {
return SessionPage{}, err
}
page := SessionPage{Sessions: sessions, Total: total}
if len(sessions) > f.Limit {
page.Sessions = sessions[:f.Limit]
last := page.Sessions[f.Limit-1]
ea := last.CreatedAt
if last.StartedAt != nil && *last.StartedAt != "" {
ea = *last.StartedAt
}
if last.EndedAt != nil && *last.EndedAt != "" {
ea = *last.EndedAt
}
page.NextCursor = db.EncodeCursor(ea, last.ID, total)
}
return page, nil
}
// GetSidebarSessionIndex returns the skinny session rows needed by
// the sidebar grouper. Paginated calls page root sessions and include
// each root's descendants so grouped sidebar trees stay complete.
func (db *DB) GetSidebarSessionIndex(
ctx context.Context, f SessionFilter,
) (SidebarSessionIndex, error) {
f.IncludeChildren = true
if f.Limit > 0 || f.Cursor != "" || f.Starred {
return db.getSidebarSessionIndexPage(ctx, f)
}
f.Cursor = ""
where, args := buildSessionFilter(f)
query := `
SELECT
id,
parent_session_id,
relationship_type,
project,
machine,
agent,
COALESCE(display_name, session_name) AS display_name,
started_at,
ended_at,
created_at,
termination_status,
message_count,
user_message_count,
is_automated,
INSTR(COALESCE(first_message, ''), '<teammate-message') > 0
FROM sessions
WHERE ` + where + `
ORDER BY COALESCE(
NULLIF(ended_at, ''),
NULLIF(started_at, ''),
created_at
) DESC, id DESC`
rows, err := db.getReader().QueryContext(ctx, query, args...)
if err != nil {
return SidebarSessionIndex{},
fmt.Errorf("querying sidebar session index: %w", err)
}
defer rows.Close()
index := SidebarSessionIndex{
Sessions: []SidebarSessionIndexRow{},
}
for rows.Next() {
var row SidebarSessionIndexRow
if err := rows.Scan(
&row.ID,
&row.ParentSessionID,
&row.RelationshipType,
&row.Project,
&row.Machine,
&row.Agent,
&row.DisplayName,
&row.StartedAt,
&row.EndedAt,
&row.CreatedAt,
&row.TerminationStatus,
&row.MessageCount,
&row.UserMessageCount,
&row.IsAutomated,
&row.IsTeammate,
); err != nil {
return SidebarSessionIndex{},
fmt.Errorf("scanning sidebar session index: %w", err)
}
index.Sessions = append(index.Sessions, row)
}
if err := rows.Err(); err != nil {
return SidebarSessionIndex{},
fmt.Errorf("iterating sidebar session index: %w", err)
}
index.Total = len(index.Sessions)
return index, nil
}
func (db *DB) getSidebarSessionIndexPage(
ctx context.Context, f SessionFilter,
) (SidebarSessionIndex, error) {
if f.Limit <= 0 || f.Limit > MaxSessionLimit {
f.Limit = DefaultSessionLimit
}
rootFilter := f
rootFilter.IncludeChildren = false
rootFilter.Cursor = ""
rootFilter.Starred = false
rootWhere, rootArgs := buildSessionFilter(rootFilter)
canonicalRootWhere := `
NOT EXISTS (
SELECT 1
FROM sessions parent
WHERE parent.id = sessions.parent_session_id
AND parent.deleted_at IS NULL
AND sessions.relationship_type IN (` + sidebarChildRelationshipsSQL + `)
)`
var total int
var cur SessionCursor
if f.Cursor != "" {
var err error
cur, err = db.DecodeCursor(f.Cursor)
if err != nil {
return SidebarSessionIndex{}, err
}
total = cur.Total
}
if total <= 0 {
if f.Starred {
countQuery := `
WITH RECURSIVE root_candidates(id) AS (
SELECT id
FROM sessions
WHERE ` + rootWhere + `
AND ` + canonicalRootWhere + `
),
tree(root_id, id) AS (
SELECT id, id FROM root_candidates
UNION
SELECT t.root_id, s.id
FROM sessions s
JOIN tree t ON s.parent_session_id = t.id
WHERE s.message_count > 0
AND s.deleted_at IS NULL
),
eligible_roots(id) AS (
SELECT DISTINCT t.root_id
FROM tree t
JOIN starred_sessions ss ON ss.session_id = t.id
)
SELECT COUNT(*) FROM eligible_roots`
if err := db.getReader().QueryRowContext(
ctx, countQuery, rootArgs...,
).Scan(&total); err != nil {
return SidebarSessionIndex{},
fmt.Errorf("counting sidebar roots: %w", err)
}
} else {
countQuery := "SELECT COUNT(*) FROM sessions WHERE " +
rootWhere + " AND " + canonicalRootWhere
if err := db.getReader().QueryRowContext(
ctx, countQuery, rootArgs...,
).Scan(&total); err != nil {
return SidebarSessionIndex{},
fmt.Errorf("counting sidebar roots: %w", err)
}
}
}
pageBuilder := NewQueryBuilder(SQLiteQueryDialect(), len(rootArgs))
cursorWhere := ""
if f.Cursor != "" {
cursorWhere = "WHERE (activity, id) < (" +
pageBuilder.Add(cur.EndedAt) + ", " +
pageBuilder.Add(cur.ID) + ")"
}
rootQuery := `
WITH RECURSIVE root_candidates(id) AS (
SELECT id
FROM sessions
WHERE ` + rootWhere + `
AND ` + canonicalRootWhere + `
),
tree(root_id, id) AS (
SELECT id, id FROM root_candidates
UNION
SELECT t.root_id, s.id
FROM sessions s
JOIN tree t ON s.parent_session_id = t.id
WHERE s.message_count > 0
AND s.deleted_at IS NULL
)
` + sidebarStarredRootCTE(f.Starred) + `,
root_activity(id, activity) AS (
SELECT t.root_id AS id, MAX(` + sidebarActivityExprSQLiteS + `) AS activity
FROM tree t
` + sidebarStarredRootJoin(f.Starred) + `
JOIN sessions s ON s.id = t.id
GROUP BY t.root_id
)
SELECT id, activity
FROM root_activity
` + cursorWhere + `
ORDER BY activity DESC, id DESC
` + pageBuilder.Limit(f.Limit+1)
rootQueryArgs := append([]any{}, rootArgs...)
rootQueryArgs = append(rootQueryArgs, pageBuilder.Args()...)
rows, err := db.getReader().QueryContext(ctx, rootQuery, rootQueryArgs...)
if err != nil {
return SidebarSessionIndex{},
fmt.Errorf("querying sidebar root page: %w", err)
}
defer rows.Close()
type rootRow struct {
id string
activity string
}
roots := []rootRow{}
for rows.Next() {
var row rootRow
if err := rows.Scan(&row.id, &row.activity); err != nil {
return SidebarSessionIndex{},
fmt.Errorf("scanning sidebar root page: %w", err)
}
roots = append(roots, row)
}
if err := rows.Err(); err != nil {
return SidebarSessionIndex{},
fmt.Errorf("iterating sidebar root page: %w", err)
}
index := SidebarSessionIndex{
Sessions: []SidebarSessionIndexRow{},
Total: total,
}
if len(roots) == 0 {
return index, nil
}
selected := roots
if len(roots) > f.Limit {
selected = roots[:f.Limit]
last := selected[f.Limit-1]
index.NextCursor = db.EncodeCursor(last.activity, last.id, total)
}
cteParts := make([]string, 0, len(selected))
treeArgs := make([]any, 0, len(selected)*2)
for i, root := range selected {
if i == 0 {
cteParts = append(cteParts, "SELECT ? AS id, ? AS ord")
} else {
cteParts = append(cteParts, "UNION ALL SELECT ?, ?")
}
treeArgs = append(treeArgs, root.id, i)
}
treeQuery := `
WITH RECURSIVE root_page(id, ord) AS (
` + strings.Join(cteParts, "\n") + `
),
tree(id, ord) AS (
SELECT id, ord FROM root_page
UNION
SELECT s.id, t.ord
FROM sessions s
JOIN tree t ON s.parent_session_id = t.id
WHERE s.message_count > 0
AND s.deleted_at IS NULL
),
ranked_tree(id, ord) AS (
SELECT id, MIN(ord) AS ord
FROM tree
GROUP BY id
)
SELECT
s.id,
s.parent_session_id,
s.relationship_type,
s.project,
s.machine,
s.agent,
COALESCE(s.display_name, s.session_name) AS display_name,
s.started_at,
s.ended_at,
s.created_at,
s.termination_status,
s.message_count,
s.user_message_count,
s.is_automated,
INSTR(COALESCE(s.first_message, ''), '<teammate-message') > 0
FROM sessions s
JOIN ranked_tree t ON s.id = t.id
ORDER BY
t.ord ASC,
` + sidebarActivityExprSQLiteS + ` DESC,
s.id DESC`
rows, err = db.getReader().QueryContext(ctx, treeQuery, treeArgs...)
if err != nil {
return SidebarSessionIndex{},
fmt.Errorf("querying sidebar tree page: %w", err)
}
defer rows.Close()
for rows.Next() {
var row SidebarSessionIndexRow
if err := rows.Scan(
&row.ID,
&row.ParentSessionID,
&row.RelationshipType,
&row.Project,
&row.Machine,
&row.Agent,
&row.DisplayName,
&row.StartedAt,
&row.EndedAt,
&row.CreatedAt,
&row.TerminationStatus,
&row.MessageCount,
&row.UserMessageCount,
&row.IsAutomated,
&row.IsTeammate,
); err != nil {
return SidebarSessionIndex{},
fmt.Errorf("scanning sidebar tree page: %w", err)
}
index.Sessions = append(index.Sessions, row)
}
if err := rows.Err(); err != nil {
return SidebarSessionIndex{},
fmt.Errorf("iterating sidebar tree page: %w", err)
}
return index, nil
}
// GetSession returns a single session by ID, excluding
// soft-deleted (trashed) sessions.
func (db *DB) GetSession(
ctx context.Context, id string,
) (*Session, error) {
row := db.getReader().QueryRowContext(
ctx,
"SELECT "+sessionBaseCols+" FROM sessions WHERE id = ? AND deleted_at IS NULL",
id,
)
s, err := scanSessionRow(row)
if err == sql.ErrNoRows {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("getting session %s: %w", id, err)
}
return &s, nil
}
// GetSessionFull returns a single session by ID with all file metadata.
func (db *DB) GetSessionFull(
ctx context.Context, id string,
) (*Session, error) {
row := db.getReader().QueryRowContext(
ctx,
"SELECT "+sessionFullCols+" FROM sessions WHERE id = ?",
id,
)
var s Session
err := row.Scan(
&s.ID, &s.Project, &s.Machine, &s.Agent,
&s.FirstMessage, &s.DisplayName, &s.SessionName, &s.StartedAt, &s.EndedAt,
&s.MessageCount, &s.UserMessageCount,
&s.ParentSessionID, &s.RelationshipType,
&s.TotalOutputTokens, &s.PeakContextTokens,
&s.HasTotalOutputTokens, &s.HasPeakContextTokens,
&s.IsAutomated,
&s.ToolFailureSignalCount, &s.ToolRetryCount,
&s.EditChurnCount, &s.ConsecutiveFailureMax,
&s.Outcome, &s.OutcomeConfidence,
&s.EndedWithRole, &s.FinalFailureStreak,
&s.SignalsPendingSince,
&s.CompactionCount, &s.MidTaskCompactionCount,
&s.ContextPressureMax,
&s.HealthScore, &s.HealthGrade,
&s.HasToolCalls, &s.HasContextData,
&s.SecretLeakCount, &s.SecretsRulesVersion,
&s.DataVersion,
&s.Cwd, &s.GitBranch,
&s.SourceSessionID, &s.SourceVersion,
&s.ParserMalformedLines, &s.IsTruncated,
&s.DeletedAt, &s.TerminationStatus, &s.FilePath, &s.FileSize,
&s.FileMtime, &s.FileInode, &s.FileDevice,
&s.FileHash, &s.LocalModifiedAt, &s.CreatedAt,
)
if err == sql.ErrNoRows {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("getting session full %s: %w", id, err)
}
// Expose the visible name (user rename, else agent session name)
// like the PG and DuckDB GetSessionFull and the sqlite base reads.
// The coalesce happens post-scan because sessionFullCols is shared
// with ListSessionsModifiedBetween, whose push consumers must see
// display_name and session_name unmerged.
if s.DisplayName == nil {
s.DisplayName = s.SessionName
}
return &s, nil
}
// IsSessionExcluded returns true if the session ID was
// permanently deleted by the user.
func (db *DB) IsSessionExcluded(id string) bool {
var n int
_ = db.getReader().QueryRow(
"SELECT 1 FROM excluded_sessions WHERE id = ?", id,
).Scan(&n)
return n == 1
}
// PurgeExcludedSessions removes any session rows whose IDs
// appear in excluded_sessions. Used after a resync to clean
// up sessions that were synced before their exclusion was
// recorded.
func (db *DB) PurgeExcludedSessions() error {
db.mu.Lock()
defer db.mu.Unlock()
_, err := db.getWriter().Exec(
"DELETE FROM sessions WHERE id IN (SELECT id FROM excluded_sessions)",
)
return err
}
// DeleteParserExcludedSessions removes rows that the current parser
// deliberately excludes, without recording a permanent user deletion
// in excluded_sessions. If the source file later becomes a real
// conversation, sync may import it again.
func (db *DB) DeleteParserExcludedSessions(ids []string) (int, error) {
if len(ids) == 0 {
return 0, nil
}
db.mu.Lock()
defer db.mu.Unlock()
tx, err := db.getWriter().Begin()
if err != nil {
return 0, fmt.Errorf("begin parser-excluded delete: %w", err)
}
defer func() { _ = tx.Rollback() }()
deleted := int64(0)
for _, id := range ids {
if id == "" {
continue
}
res, err := tx.Exec(
"DELETE FROM sessions WHERE id = ?", id,
)
if err != nil {
return 0, fmt.Errorf(
"deleting parser-excluded session %s: %w",
id, err,
)
}
n, _ := res.RowsAffected()
deleted += n
}
if err := tx.Commit(); err != nil {
return 0, fmt.Errorf("commit parser-excluded delete: %w", err)
}
return int(deleted), nil
}
const upsertSessionSQL = `
INSERT INTO sessions (
id, project, machine, agent, first_message, session_name,
started_at, ended_at, message_count,
user_message_count, parent_session_id,
relationship_type,
total_output_tokens, peak_context_tokens,
has_total_output_tokens, has_peak_context_tokens,
is_automated,
termination_status,
cwd, git_branch, source_session_id,
source_version, parser_malformed_lines,
is_truncated,
file_path, file_size, file_mtime,
file_inode, file_device, file_hash
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
project = excluded.project,
machine = excluded.machine,
agent = excluded.agent,
first_message = excluded.first_message,
-- session_name is always overwritten by re-parse; display_name
-- is the user override and is only touched by RenameSession.
session_name = excluded.session_name,
started_at = excluded.started_at,
ended_at = excluded.ended_at,
message_count = excluded.message_count,
user_message_count = excluded.user_message_count,
parent_session_id = excluded.parent_session_id,
relationship_type = excluded.relationship_type,
total_output_tokens = excluded.total_output_tokens,
peak_context_tokens = excluded.peak_context_tokens,
has_total_output_tokens = excluded.has_total_output_tokens,
has_peak_context_tokens = excluded.has_peak_context_tokens,
is_automated = excluded.is_automated,
termination_status = excluded.termination_status,
cwd = excluded.cwd,
git_branch = excluded.git_branch,
source_session_id = excluded.source_session_id,
source_version = excluded.source_version,
parser_malformed_lines = excluded.parser_malformed_lines,
is_truncated = excluded.is_truncated,
file_path = excluded.file_path,
file_size = excluded.file_size,
file_mtime = excluded.file_mtime,
file_inode = excluded.file_inode,
file_device = excluded.file_device,