~bigbes/lethe

ref: 3ae44b2876001b8a2b0e4d8abfd7a35d4a8fa977 lethe/internal/domain/project/repository_test.go -rw-r--r-- 10.8 KiB
3ae44b28 — Eugene Blikh tooling: adopt go tool directives; rename air→dev; bundle fmt drift a month ago
                                                                                
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
package project_test

import (
	"context"
	"testing"
	"time"

	"github.com/jmoiron/sqlx"
	_ "modernc.org/sqlite"

	"sourcecraft.dev/bigbes/lethe/internal/config"
	"sourcecraft.dev/bigbes/lethe/internal/domain/project"
	"sourcecraft.dev/bigbes/lethe/internal/domain/session"
	"sourcecraft.dev/bigbes/lethe/internal/platform/database"
)

// newTestDatabase builds a Database steward against :memory: (one DB per
// test, isolated). Cleanup runs Destroy.
func newTestDatabase(t *testing.T) *database.Database {
	t.Helper()
	d := &database.Database{
		Cfg: config.DatabaseConfig{
			Path:        ":memory:",
			BusyTimeout: 5 * time.Second,
		},
	}
	if err := d.Init(context.Background()); err != nil {
		t.Fatalf("database.Init: %v", err)
	}
	t.Cleanup(func() { _ = d.Destroy(context.Background()) })
	return d
}

// newRepo wires a project.Repository against a fresh in-memory database.
func newRepo(t *testing.T) (*project.Repository, *sqlx.DB) {
	t.Helper()
	d := newTestDatabase(t)
	repo := &project.Repository{Database: d}
	if err := repo.Init(context.Background()); err != nil {
		t.Fatalf("repo.Init: %v", err)
	}
	return repo, d.DB
}

// seedSession inserts a session row. working_dir may be empty string (treated
// as non-NULL) or use seedSessionNullCwd for a NULL working_dir row.
func seedSessionWithCwd(t *testing.T, db *sqlx.DB, owner, tool, host, sid string, startedAt, endedAt int64, cwd string) {
	t.Helper()
	_, err := db.Exec(`
		INSERT INTO sessions (owner, tool, host, session_id, started_at, ended_at, working_dir, source_file, metadata)
		VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL)`,
		owner, tool, host, sid, startedAt, endedAt, cwd, "/tmp/x.jsonl",
	)
	if err != nil {
		t.Fatalf("seed session %s/%s/%s/%s (cwd=%s): %v", owner, tool, host, sid, cwd, err)
	}
}

// seedSessionNullCwd inserts a session row with a NULL working_dir.
func seedSessionNullCwd(t *testing.T, db *sqlx.DB, owner, tool, host, sid string, startedAt, endedAt int64) {
	t.Helper()
	_, err := db.Exec(`
		INSERT INTO sessions (owner, tool, host, session_id, started_at, ended_at, working_dir, source_file, metadata)
		VALUES (?, ?, ?, ?, ?, ?, NULL, ?, NULL)`,
		owner, tool, host, sid, startedAt, endedAt, "/tmp/x.jsonl",
	)
	if err != nil {
		t.Fatalf("seed session null cwd %s/%s/%s/%s: %v", owner, tool, host, sid, err)
	}
}

// seedTurn inserts a turn row with the specified tool value.
func seedTurn(t *testing.T, db *sqlx.DB, owner, tool, host, sid, tid string, seq, ts int64) {
	t.Helper()
	_, err := db.Exec(`
		INSERT INTO turns (owner, tool, host, session_id, turn_id, seq, role, timestamp, content,
		                   model, tokens_in, tokens_out, cost_usd, tool_calls, metadata)
		VALUES (?, ?, ?, ?, ?, ?, 'user', ?, 'hello', NULL, NULL, NULL, NULL, NULL, NULL)`,
		owner, tool, host, sid, tid, seq, ts,
	)
	if err != nil {
		t.Fatalf("seed turn %s/%s: %v", sid, tid, err)
	}
}

// seedTurnFull inserts a turn row with tokens_in, tokens_out, and a model set.
func seedTurnFull(t *testing.T, db *sqlx.DB, owner, tool, host, sid, tid string, seq, ts, tokensIn, tokensOut int64, model string) {
	t.Helper()
	_, err := db.Exec(`
		INSERT INTO turns (owner, tool, host, session_id, turn_id, seq, role, timestamp, content,
		                   model, tokens_in, tokens_out, cost_usd, tool_calls, metadata)
		VALUES (?, ?, ?, ?, ?, ?, 'assistant', ?, 'response', ?, ?, ?, NULL, NULL, NULL)`,
		owner, tool, host, sid, tid, seq, ts, model, tokensIn, tokensOut,
	)
	if err != nil {
		t.Fatalf("seed turn full %s/%s: %v", sid, tid, err)
	}
}

func TestProjectList_EmptyDB(t *testing.T) {
	repo, _ := newRepo(t)
	got, err := repo.List(context.Background(), project.ListFilter{
		Owner: session.OwnerScope{User: "alice"},
		Limit: 50,
	})
	if err != nil {
		t.Fatalf("List: %v", err)
	}
	if got == nil {
		t.Fatal("expected non-nil empty slice; got nil")
	}
	if len(got) != 0 {
		t.Fatalf("expected 0 projects; got %d (%#v)", len(got), got)
	}
}

func TestProjectList_OneCwdTwoSessionsThreeTurns(t *testing.T) {
	repo, db := newRepo(t)
	// Two sessions share /code/x.
	seedSessionWithCwd(t, db, "alice", "cc", "phoebe", "s1", 1700000000, 1700000010, "/code/x")
	seedSessionWithCwd(t, db, "alice", "cc", "phoebe", "s2", 1700000020, 1700000050, "/code/x")
	// Three turns across both sessions.
	seedTurn(t, db, "alice", "cc", "phoebe", "s1", "t1", 1, 1700000005)
	seedTurn(t, db, "alice", "cc", "phoebe", "s2", "t2", 1, 1700000025)
	seedTurn(t, db, "alice", "cc", "phoebe", "s2", "t3", 2, 1700000035)

	got, err := repo.List(context.Background(), project.ListFilter{
		Owner: session.OwnerScope{User: "alice"},
		Limit: 50,
	})
	if err != nil {
		t.Fatalf("List: %v", err)
	}
	if len(got) != 1 {
		t.Fatalf("expected 1 project row; got %d (%#v)", len(got), got)
	}
	p := got[0]
	if p.Cwd != "/code/x" {
		t.Errorf("Cwd: got %q; want /code/x", p.Cwd)
	}
	if p.Sessions != 2 {
		t.Errorf("Sessions: got %d; want 2", p.Sessions)
	}
	if p.TurnCount != 3 {
		t.Errorf("TurnCount: got %d; want 3", p.TurnCount)
	}
	// LastActive = MAX(ended_at) of the two sessions = 1700000050.
	if p.LastActive != 1700000050 {
		t.Errorf("LastActive: got %d; want 1700000050", p.LastActive)
	}
}

func TestProjectList_NullCwdExcluded(t *testing.T) {
	repo, db := newRepo(t)
	// One row with a real cwd, one with NULL.
	seedSessionWithCwd(t, db, "alice", "cc", "phoebe", "s1", 1700000000, 1700000010, "/code/x")
	seedSessionNullCwd(t, db, "alice", "cc", "phoebe", "s2", 1700000020, 1700000030)

	got, err := repo.List(context.Background(), project.ListFilter{
		Owner: session.OwnerScope{User: "alice"},
		Limit: 50,
	})
	if err != nil {
		t.Fatalf("List: %v", err)
	}
	if len(got) != 1 {
		t.Fatalf("expected 1 project (null cwd excluded); got %d (%#v)", len(got), got)
	}
	if got[0].Cwd != "/code/x" {
		t.Errorf("Cwd: got %q; want /code/x", got[0].Cwd)
	}
}

func TestProjectList_TopToolTiesBrokenByAsc(t *testing.T) {
	repo, db := newRepo(t)
	// Two tools each with 1 turn for the same cwd — alphabetically "cc" < "gemini".
	seedSessionWithCwd(t, db, "alice", "cc", "phoebe", "s1", 1700000000, 1700000010, "/code/x")
	seedSessionWithCwd(t, db, "alice", "gemini", "phoebe", "s2", 1700000020, 1700000030, "/code/x")
	seedTurn(t, db, "alice", "cc", "phoebe", "s1", "t1", 1, 1700000005)
	seedTurn(t, db, "alice", "gemini", "phoebe", "s2", "t2", 1, 1700000025)

	got, err := repo.List(context.Background(), project.ListFilter{
		Owner: session.OwnerScope{User: "alice"},
		Limit: 50,
	})
	if err != nil {
		t.Fatalf("List: %v", err)
	}
	if len(got) != 1 {
		t.Fatalf("expected 1 project; got %d", len(got))
	}
	if got[0].TopTool != "cc" {
		t.Errorf("TopTool tie: got %q; want cc (alphabetically first)", got[0].TopTool)
	}
}

func TestProjectList_HostsAndToolsDeduped(t *testing.T) {
	repo, db := newRepo(t)
	// Same tool + host across two sessions → should appear once each.
	seedSessionWithCwd(t, db, "alice", "cc", "phoebe", "s1", 1700000000, 1700000010, "/code/x")
	seedSessionWithCwd(t, db, "alice", "cc", "phoebe", "s2", 1700000020, 1700000030, "/code/x")

	got, err := repo.List(context.Background(), project.ListFilter{
		Owner: session.OwnerScope{User: "alice"},
		Limit: 50,
	})
	if err != nil {
		t.Fatalf("List: %v", err)
	}
	if len(got) != 1 {
		t.Fatalf("expected 1 project; got %d", len(got))
	}
	p := got[0]
	if len(p.Tools) != 1 || p.Tools[0] != "cc" {
		t.Errorf("Tools: got %v; want [cc]", p.Tools)
	}
	if len(p.Hosts) != 1 || p.Hosts[0] != "phoebe" {
		t.Errorf("Hosts: got %v; want [phoebe]", p.Hosts)
	}
}

func TestProjectList_HostsAndToolsSorted(t *testing.T) {
	repo, db := newRepo(t)
	// Two different tools + two different hosts across sessions.
	seedSessionWithCwd(t, db, "alice", "gemini", "rhea", "s1", 1700000000, 1700000010, "/code/x")
	seedSessionWithCwd(t, db, "alice", "cc", "phoebe", "s2", 1700000020, 1700000030, "/code/x")

	got, err := repo.List(context.Background(), project.ListFilter{
		Owner: session.OwnerScope{User: "alice"},
		Limit: 50,
	})
	if err != nil {
		t.Fatalf("List: %v", err)
	}
	if len(got) != 1 {
		t.Fatalf("expected 1 project; got %d", len(got))
	}
	p := got[0]
	// Tools sorted: cc < gemini.
	if len(p.Tools) != 2 || p.Tools[0] != "cc" || p.Tools[1] != "gemini" {
		t.Errorf("Tools sorted: got %v; want [cc gemini]", p.Tools)
	}
	// Hosts sorted: phoebe < rhea.
	if len(p.Hosts) != 2 || p.Hosts[0] != "phoebe" || p.Hosts[1] != "rhea" {
		t.Errorf("Hosts sorted: got %v; want [phoebe rhea]", p.Hosts)
	}
}

func TestProjectList_OwnerScopes(t *testing.T) {
	t.Run("AllOwners returns rows from both owners", func(t *testing.T) {
		repo, db := newRepo(t)
		seedSessionWithCwd(t, db, "alice", "cc", "phoebe", "sA", 1700000000, 1700000010, "/code/x")
		seedSessionWithCwd(t, db, "bob", "cc", "phoebe", "sB", 1700000020, 1700000030, "/code/y")

		got, err := repo.List(context.Background(), project.ListFilter{
			Owner: session.OwnerScope{User: "admin", AllOwners: true},
			Limit: 50,
		})
		if err != nil {
			t.Fatalf("List: %v", err)
		}
		if len(got) != 2 {
			t.Fatalf("AllOwners: expected 2 rows; got %d (%#v)", len(got), got)
		}
	})

	t.Run("SpecificOwner pins to one owner", func(t *testing.T) {
		repo, db := newRepo(t)
		seedSessionWithCwd(t, db, "alice", "cc", "phoebe", "sA", 1700000000, 1700000010, "/code/x")
		seedSessionWithCwd(t, db, "bob", "cc", "phoebe", "sB", 1700000020, 1700000030, "/code/y")

		bob := "bob"
		got, err := repo.List(context.Background(), project.ListFilter{
			Owner: session.OwnerScope{User: "admin", SpecificOwner: &bob},
			Limit: 50,
		})
		if err != nil {
			t.Fatalf("List: %v", err)
		}
		if len(got) != 1 || got[0].Cwd != "/code/y" {
			t.Fatalf("SpecificOwner bob: expected /code/y; got %#v", got)
		}
	})

	t.Run("default scope returns only caller rows", func(t *testing.T) {
		repo, db := newRepo(t)
		seedSessionWithCwd(t, db, "alice", "cc", "phoebe", "sA", 1700000000, 1700000010, "/code/x")
		seedSessionWithCwd(t, db, "bob", "cc", "phoebe", "sB", 1700000020, 1700000030, "/code/y")

		got, err := repo.List(context.Background(), project.ListFilter{
			Owner: session.OwnerScope{User: "alice"},
			Limit: 50,
		})
		if err != nil {
			t.Fatalf("List: %v", err)
		}
		if len(got) != 1 || got[0].Cwd != "/code/x" {
			t.Fatalf("default scope alice: expected /code/x; got %#v", got)
		}
	})
}

func TestProjectList_TokenSums(t *testing.T) {
	repo, db := newRepo(t)
	seedSessionWithCwd(t, db, "alice", "cc", "phoebe", "s1", 1700000000, 1700000100, "/code/x")
	seedTurnFull(t, db, "alice", "cc", "phoebe", "s1", "t1", 1, 1700000010, 100, 200, "gpt-4")
	seedTurnFull(t, db, "alice", "cc", "phoebe", "s1", "t2", 2, 1700000020, 50, 75, "gpt-4")

	got, err := repo.List(context.Background(), project.ListFilter{
		Owner: session.OwnerScope{User: "alice"},
		Limit: 50,
	})
	if err != nil {
		t.Fatalf("List: %v", err)
	}
	if len(got) != 1 {
		t.Fatalf("expected 1; got %d", len(got))
	}
	p := got[0]
	if p.TokensInTotal != 150 {
		t.Errorf("TokensInTotal: got %d; want 150", p.TokensInTotal)
	}
	if p.TokensOutTotal != 275 {
		t.Errorf("TokensOutTotal: got %d; want 275", p.TokensOutTotal)
	}
}