-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent-sessions.test.ts
More file actions
652 lines (558 loc) · 19.9 KB
/
agent-sessions.test.ts
File metadata and controls
652 lines (558 loc) · 19.9 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
import { describe, it, expect, vi, beforeEach } from "vitest";
import { Hono } from "hono";
import {
type SqlDispatcher,
mockDbModule,
postJson,
} from "./test-utils";
// ---- In-memory sessions fixture (simulates FK target) ----
// Pre-seeded IDs that are valid FK targets for session_id.
// Tests that use sessionId: 42 must find it here; others must not.
const VALID_SESSION_IDS = new Set<number>([42]);
// ---- In-memory store simulating agent_sessions table ----
let nextId = 1;
let store: Array<{
id: number;
branch: string;
task: string;
session_type: string;
issue_number: number | null;
checklist_md: string;
session_id: number | null;
status: string;
started_at: Date;
completed_at: Date | null;
created_at: Date;
updated_at: Date;
}>;
function resetStore() {
store = [];
nextId = 1;
}
const dispatch: SqlDispatcher = (query, params) => {
const q = query.toLowerCase();
// ---- entity_ids (for health check) ----
if (q.includes("count(*)") && q.includes("entity_ids")) {
return [{ count: 0 }];
}
if (q.includes("last_value")) {
return [{ last_value: 0, is_called: false }];
}
// ---- INSERT INTO agent_sessions ----
if (q.includes("insert into") && q.includes("agent_sessions")) {
const row = {
id: nextId++,
branch: params[0] as string,
task: params[1] as string,
session_type: params[2] as string,
issue_number: params[3] as number | null,
checklist_md: params[4] as string,
session_id: null,
status: "active",
started_at: new Date(),
completed_at: null,
created_at: new Date(),
updated_at: new Date(),
};
store.push(row);
return [row];
}
// ---- UPDATE agent_sessions SET ... WHERE "id" ----
if (q.includes("update") && q.includes("agent_sessions") && q.includes("set")) {
const id = params[params.length - 1] as number;
const idx = store.findIndex((r) => r.id === id);
if (idx === -1) return [];
// The route builds dynamic SET clauses. We parse from the query which columns are being set.
// Drizzle generates: UPDATE "agent_sessions" SET "col1" = $1, "col2" = $2 ... WHERE "id" = $N
// Extract quoted column names from the SET clause
const setMatch = query.match(/set\s+(.+?)\s+where/is);
if (setMatch) {
const setParts = setMatch[1].split(",").map((s) => s.trim());
let pIdx = 0;
for (const part of setParts) {
const colMatch = part.match(/"(\w+)"/);
if (!colMatch) { pIdx++; continue; }
const col = colMatch[1];
switch (col) {
case "task":
store[idx].task = params[pIdx] as string;
break;
case "session_type":
store[idx].session_type = params[pIdx] as string;
break;
case "issue_number":
store[idx].issue_number = params[pIdx] as number | null;
break;
case "checklist_md":
store[idx].checklist_md = params[pIdx] as string;
break;
case "session_id": {
const sid = params[pIdx] as number | null;
if (sid !== null && !VALID_SESSION_IDS.has(sid)) {
// Simulate FK constraint violation — the route translates this to 400.
throw new Error(
`insert or update on table "agent_sessions" violates foreign key constraint`
);
}
store[idx].session_id = sid;
break;
}
case "status":
store[idx].status = params[pIdx] as string;
break;
case "completed_at":
store[idx].completed_at = params[pIdx] as Date | null;
break;
case "updated_at":
store[idx].updated_at = params[pIdx] as Date ?? new Date();
break;
}
pIdx++;
}
}
return [store[idx]];
}
// ---- SELECT from agent_sessions WHERE branch = $1 (by-branch lookup) ----
if (
q.includes("agent_sessions") &&
q.includes("where") &&
q.includes('"branch"')
) {
const branch = params[0] as string;
const matches = store
.filter((r) => r.branch === branch)
.sort((a, b) => b.started_at.getTime() - a.started_at.getTime());
const limit = q.includes("limit") ? 1 : matches.length;
return matches.slice(0, limit);
}
// ---- SELECT from agent_sessions WHERE id = $1 ----
if (
q.includes("agent_sessions") &&
q.includes("where") &&
q.includes('"id"')
) {
const id = params[0] as number;
return store.filter((r) => r.id === id);
}
// ---- SELECT from agent_sessions ORDER BY ... LIMIT ... (list all) ----
if (
q.includes("agent_sessions") &&
!q.includes("where") &&
q.includes("order by")
) {
const limit = (params[0] as number) || 50;
const sorted = [...store].sort(
(a, b) => b.started_at.getTime() - a.started_at.getTime()
);
return sorted.slice(0, limit);
}
return [];
};
vi.mock("../db.js", () => mockDbModule(dispatch));
const { createApp } = await import("../app.js");
// ---- Helpers ----
function patchJson(app: Hono, path: string, body: unknown) {
return app.request(path, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
}
// ---- Tests ----
describe("Agent Sessions API", () => {
let app: Hono;
beforeEach(() => {
resetStore();
delete process.env.LONGTERMWIKI_SERVER_API_KEY;
app = createApp();
});
const sampleSession = {
branch: "claude/issue-123-abc",
task: "Fix widget rendering bug",
sessionType: "bugfix",
issueNumber: 123,
checklistMd:
"# Session Checklist\n\n- [ ] Read the issue\n- [ ] Fix the bug",
};
// ================================================================
// POST / (create or upsert)
// ================================================================
describe("POST /api/agent-sessions", () => {
it("creates a new session and returns 201", async () => {
const res = await postJson(app, "/api/agent-sessions", sampleSession);
expect(res.status).toBe(201);
const body = await res.json();
expect(body.id).toBe(1);
expect(body.branch).toBe("claude/issue-123-abc");
expect(body.task).toBe("Fix widget rendering bug");
// Drizzle maps snake_case → camelCase
expect(body.sessionType).toBe("bugfix");
expect(body.issueNumber).toBe(123);
expect(body.status).toBe("active");
});
it("upserts an existing active session for the same branch", async () => {
await postJson(app, "/api/agent-sessions", sampleSession);
const res = await postJson(app, "/api/agent-sessions", {
...sampleSession,
task: "Updated task description",
checklistMd: "# Updated checklist",
});
expect(res.status).toBe(200);
const body = await res.json();
expect(body.id).toBe(1); // Same ID — updated, not duplicated
expect(body.task).toBe("Updated task description");
});
it("creates a new session for the same branch if previous is completed", async () => {
await postJson(app, "/api/agent-sessions", sampleSession);
store[0].status = "completed";
const res = await postJson(app, "/api/agent-sessions", {
...sampleSession,
task: "Second session on same branch",
});
expect(res.status).toBe(201);
const body = await res.json();
expect(body.id).toBe(2);
});
it("accepts null issueNumber", async () => {
const res = await postJson(app, "/api/agent-sessions", {
...sampleSession,
issueNumber: null,
});
expect(res.status).toBe(201);
const body = await res.json();
expect(body.issueNumber).toBeNull();
});
it("accepts omitted issueNumber (optional)", async () => {
const { issueNumber, ...noIssue } = sampleSession;
const res = await postJson(app, "/api/agent-sessions", noIssue);
expect(res.status).toBe(201);
});
// -- Validation error cases --
it("rejects missing branch", async () => {
const { branch, ...noBranch } = sampleSession;
const res = await postJson(app, "/api/agent-sessions", noBranch);
expect(res.status).toBe(400);
});
it("rejects empty branch", async () => {
const res = await postJson(app, "/api/agent-sessions", {
...sampleSession,
branch: "",
});
expect(res.status).toBe(400);
});
it("rejects missing task", async () => {
const { task, ...noTask } = sampleSession;
const res = await postJson(app, "/api/agent-sessions", noTask);
expect(res.status).toBe(400);
});
it("rejects invalid sessionType", async () => {
const res = await postJson(app, "/api/agent-sessions", {
...sampleSession,
sessionType: "invalid-type",
});
expect(res.status).toBe(400);
});
it("rejects missing checklistMd", async () => {
const { checklistMd, ...noChecklist } = sampleSession;
const res = await postJson(app, "/api/agent-sessions", noChecklist);
expect(res.status).toBe(400);
});
it("rejects empty checklistMd", async () => {
const res = await postJson(app, "/api/agent-sessions", {
...sampleSession,
checklistMd: "",
});
expect(res.status).toBe(400);
});
it("rejects non-positive issueNumber", async () => {
const res = await postJson(app, "/api/agent-sessions", {
...sampleSession,
issueNumber: 0,
});
expect(res.status).toBe(400);
});
it("rejects negative issueNumber", async () => {
const res = await postJson(app, "/api/agent-sessions", {
...sampleSession,
issueNumber: -5,
});
expect(res.status).toBe(400);
});
it("rejects non-integer issueNumber", async () => {
const res = await postJson(app, "/api/agent-sessions", {
...sampleSession,
issueNumber: 1.5,
});
expect(res.status).toBe(400);
});
it("rejects invalid JSON body", async () => {
const res = await app.request("/api/agent-sessions", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: "not-json",
});
expect(res.status).toBe(400);
});
it("accepts all valid sessionType values", async () => {
for (const t of [
"content",
"infrastructure",
"bugfix",
"refactor",
"commands",
]) {
resetStore();
const res = await postJson(app, "/api/agent-sessions", {
...sampleSession,
sessionType: t,
branch: `claude/test-${t}`,
});
expect(res.status).toBe(201);
}
});
it("rejects branch exceeding max length (500)", async () => {
const res = await postJson(app, "/api/agent-sessions", {
...sampleSession,
branch: "x".repeat(501),
});
expect(res.status).toBe(400);
});
it("rejects task exceeding max length (2000)", async () => {
const res = await postJson(app, "/api/agent-sessions", {
...sampleSession,
task: "x".repeat(2001),
});
expect(res.status).toBe(400);
});
});
// ================================================================
// GET /by-branch/:branch
// ================================================================
describe("GET /api/agent-sessions/by-branch/:branch", () => {
it("returns the latest session for a branch", async () => {
await postJson(app, "/api/agent-sessions", sampleSession);
const res = await app.request(
`/api/agent-sessions/by-branch/${encodeURIComponent(sampleSession.branch)}`
);
expect(res.status).toBe(200);
const body = await res.json();
expect(body.branch).toBe("claude/issue-123-abc");
expect(body.id).toBe(1);
});
it("returns 404 for unknown branch", async () => {
const res = await app.request(
"/api/agent-sessions/by-branch/nonexistent-branch"
);
expect(res.status).toBe(404);
const body = await res.json();
expect(body.error).toBe("not_found");
});
it("handles URL-encoded branch names with slashes", async () => {
await postJson(app, "/api/agent-sessions", sampleSession);
const res = await app.request(
`/api/agent-sessions/by-branch/${encodeURIComponent("claude/issue-123-abc")}`
);
expect(res.status).toBe(200);
const body = await res.json();
expect(body.branch).toBe("claude/issue-123-abc");
});
});
// ================================================================
// PATCH /:id
// ================================================================
describe("PATCH /api/agent-sessions/:id", () => {
it("updates checklist markdown", async () => {
await postJson(app, "/api/agent-sessions", sampleSession);
const res = await patchJson(app, "/api/agent-sessions/1", {
checklistMd: "# Updated\n\n- [x] Done",
});
expect(res.status).toBe(200);
const body = await res.json();
expect(body.checklistMd).toBe("# Updated\n\n- [x] Done");
});
it("updates status to completed", async () => {
await postJson(app, "/api/agent-sessions", sampleSession);
const res = await patchJson(app, "/api/agent-sessions/1", {
status: "completed",
});
expect(res.status).toBe(200);
const body = await res.json();
expect(body.status).toBe("completed");
expect(body.completedAt).not.toBeNull();
});
it("updates both checklist and status", async () => {
await postJson(app, "/api/agent-sessions", sampleSession);
const res = await patchJson(app, "/api/agent-sessions/1", {
checklistMd: "# Final",
status: "completed",
});
expect(res.status).toBe(200);
});
it("returns 404 for unknown session id", async () => {
const res = await patchJson(app, "/api/agent-sessions/999", {
status: "completed",
});
expect(res.status).toBe(404);
});
it("rejects non-numeric id", async () => {
const res = await patchJson(app, "/api/agent-sessions/abc", {
status: "completed",
});
expect(res.status).toBe(400);
});
it("rejects invalid status value", async () => {
await postJson(app, "/api/agent-sessions", sampleSession);
const res = await patchJson(app, "/api/agent-sessions/1", {
status: "invalid",
});
expect(res.status).toBe(400);
});
it("rejects empty checklistMd", async () => {
await postJson(app, "/api/agent-sessions", sampleSession);
const res = await patchJson(app, "/api/agent-sessions/1", {
checklistMd: "",
});
expect(res.status).toBe(400);
});
it("rejects empty body (no-op update)", async () => {
await postJson(app, "/api/agent-sessions", sampleSession);
const res = await patchJson(app, "/api/agent-sessions/1", {});
expect(res.status).toBe(400);
});
it("rejects floating-point id", async () => {
await postJson(app, "/api/agent-sessions", sampleSession);
const res = await patchJson(app, "/api/agent-sessions/1.5", {
status: "completed",
});
expect(res.status).toBe(400);
});
it("rejects invalid JSON body", async () => {
await postJson(app, "/api/agent-sessions", sampleSession);
const res = await app.request("/api/agent-sessions/1", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: "not-json",
});
expect(res.status).toBe(400);
});
it("sets sessionId FK link to session log", async () => {
await postJson(app, "/api/agent-sessions", sampleSession);
const res = await patchJson(app, "/api/agent-sessions/1", {
sessionId: 42,
});
expect(res.status).toBe(200);
const body = await res.json();
expect(body.sessionId).toBe(42);
});
it("clears sessionId with null", async () => {
await postJson(app, "/api/agent-sessions", sampleSession);
// Set it first
await patchJson(app, "/api/agent-sessions/1", { sessionId: 42 });
// Now clear it
const res = await patchJson(app, "/api/agent-sessions/1", {
sessionId: null,
});
expect(res.status).toBe(200);
const body = await res.json();
expect(body.sessionId).toBeNull();
});
it("rejects non-integer sessionId", async () => {
await postJson(app, "/api/agent-sessions", sampleSession);
const res = await patchJson(app, "/api/agent-sessions/1", {
sessionId: 1.5,
});
expect(res.status).toBe(400);
});
it("rejects zero sessionId", async () => {
await postJson(app, "/api/agent-sessions", sampleSession);
const res = await patchJson(app, "/api/agent-sessions/1", {
sessionId: 0,
});
expect(res.status).toBe(400);
});
it("returns 400 invalid_reference for non-existent sessionId", async () => {
await postJson(app, "/api/agent-sessions", sampleSession);
const res = await patchJson(app, "/api/agent-sessions/1", {
sessionId: 9999, // not in VALID_SESSION_IDS — FK violation
});
expect(res.status).toBe(400);
const body = await res.json();
expect(body.error).toBe("invalid_reference");
});
});
// ================================================================
// GET / (list)
// ================================================================
describe("GET /api/agent-sessions", () => {
it("returns empty sessions list", async () => {
const res = await app.request("/api/agent-sessions");
expect(res.status).toBe(200);
const body = await res.json();
expect(body.sessions).toHaveLength(0);
});
it("returns all created sessions", async () => {
await postJson(app, "/api/agent-sessions", sampleSession);
await postJson(app, "/api/agent-sessions", {
...sampleSession,
branch: "claude/other-branch",
});
const res = await app.request("/api/agent-sessions");
expect(res.status).toBe(200);
const body = await res.json();
expect(body.sessions).toHaveLength(2);
});
it("respects limit parameter", async () => {
for (let i = 0; i < 5; i++) {
await postJson(app, "/api/agent-sessions", {
...sampleSession,
branch: `claude/branch-${i}`,
});
}
const res = await app.request("/api/agent-sessions?limit=3");
expect(res.status).toBe(200);
const body = await res.json();
expect(body.sessions).toHaveLength(3);
});
it("caps limit at 200", async () => {
const res = await app.request("/api/agent-sessions?limit=999");
expect(res.status).toBe(200);
});
});
// ================================================================
// Authentication
// ================================================================
describe("Authentication", () => {
it("requires bearer token when API key is set", async () => {
process.env.LONGTERMWIKI_SERVER_API_KEY = "test-secret";
app = createApp();
const res = await postJson(app, "/api/agent-sessions", sampleSession);
expect(res.status).toBe(401);
});
it("accepts valid bearer token", async () => {
process.env.LONGTERMWIKI_SERVER_API_KEY = "test-secret";
app = createApp();
const res = await app.request("/api/agent-sessions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-secret",
},
body: JSON.stringify(sampleSession),
});
expect(res.status).toBe(201);
});
it("rejects wrong bearer token", async () => {
process.env.LONGTERMWIKI_SERVER_API_KEY = "test-secret";
app = createApp();
const res = await app.request("/api/agent-sessions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer wrong-token",
},
body: JSON.stringify(sampleSession),
});
expect(res.status).toBe(401);
});
});
});