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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
/**
 * Tests for GET /api/analytics/judge-dimensions
 *
 * Covers:
 *   API key guard
 *     - returns 503 when LANGSMITH_API_KEY is not set
 *     - does NOT call langsmithClient when key is missing
 *   Response shape
 *     - returns 200 with { dimensions, alerts } keys
 *     - dimensions contains an entry for every DIMENSION_ID
 *     - each dimension entry has { avg, trend } fields
 *     - alerts is an array
 *   Score aggregation β€” avg calculation
 *     - avg is 0 when no feedback in the current period
 *     - avg is computed correctly over multiple scores
 *     - avg is rounded to 2 decimal places
 *     - denormalises: feedback scores (0-1) are multiplied by 10
 *     - ignores feedback keys that are not in DIMENSION_IDS
 *     - ignores feedback entries with non-numeric score
 *   Trend calculation
 *     - trend is 0 when there is no prior period data
 *     - trend is positive when current avg > prior avg
 *     - trend is negative when current avg < prior avg
 *     - trend is 0 when prior and current are identical
 *     - trend is rounded to 2 decimal places
 *   Alerts
 *     - no alert when drop is exactly -10% (boundary β€” not > 10%)
 *     - alert fires when drop is > 10%
 *     - alert message contains the dimension id
 *     - alert message contains the percentage drop
 *     - no alert when prior avg is 0 (no prior data)
 *     - multiple dimensions can fire alerts in the same response
 *   Error handling
 *     - returns 500 if langsmithClient.listRuns throws
 */

import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
import { DIMENSION_IDS } from "@/lib/debate/judge";

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

type FeedbackEntry = { key: string; score: number | null | undefined };
type RunEntry = { id: string };

/**
 * Build a mock async generator from an array.
 */
async function* makeAsyncGen<T>(items: T[]): AsyncGenerator<T> {
  for (const item of items) {
    yield item;
  }
}

// ---------------------------------------------------------------------------
// Mocks
// ---------------------------------------------------------------------------

// listRuns and listFeedback are configured per-test via these maps
let mockRunsByPeriod: RunEntry[][] = [[], []]; // [currentPeriod, priorPeriod]
let mockFeedbackByRunId: Map<string, FeedbackEntry[]> = new Map();

// Track call order so we can distinguish current vs prior period calls
let listRunsCallIndex = 0;

const mockListRuns = vi.fn();
const mockListFeedback = vi.fn();

vi.mock("@/lib/langsmith", () => ({
  langsmithClient: {
    listRuns: (...args: unknown[]) => mockListRuns(...args),
    listFeedback: (...args: unknown[]) => mockListFeedback(...args),
  },
}));

beforeEach(() => {
  vi.resetModules();
  mockListRuns.mockClear();
  mockListFeedback.mockClear();
  mockRunsByPeriod = [[], []];
  mockFeedbackByRunId = new Map();
  listRunsCallIndex = 0;

  // Default: return the correct period's runs in call order
  mockListRuns.mockImplementation(() => {
    const idx = listRunsCallIndex++;
    const runs = mockRunsByPeriod[idx] ?? [];
    return makeAsyncGen(runs);
  });

  // Default: return any registered feedback for the given runId
  mockListFeedback.mockImplementation(
    ({ runIds }: { runIds: string[] }) => {
      const feedbacks = mockFeedbackByRunId.get(runIds[0]) ?? [];
      return makeAsyncGen(feedbacks);
    },
  );
});

// ---------------------------------------------------------------------------
// Import the handler after mocks are set up
// ---------------------------------------------------------------------------

async function callGET(env: Record<string, string | undefined> = {}) {
  // Dynamically import to pick up the latest mock state
  const { GET } = await import("../judge-dimensions/route");
  const req = new NextRequest("http://localhost/api/analytics/judge-dimensions");

  const saved: Record<string, string | undefined> = {};
  for (const [k, v] of Object.entries(env)) {
    saved[k] = process.env[k];
    if (v === undefined) {
      delete process.env[k];
    } else {
      process.env[k] = v;
    }
  }

  try {
    const res = await GET(req);
    return res;
  } finally {
    for (const [k, v] of Object.entries(saved)) {
      if (v === undefined) {
        delete process.env[k];
      } else {
        process.env[k] = v;
      }
    }
  }
}

// ---------------------------------------------------------------------------
// API key guard
// ---------------------------------------------------------------------------

describe("API key guard", () => {
  it("returns 503 when LANGSMITH_API_KEY is not set", async () => {
    const res = await callGET({ LANGSMITH_API_KEY: undefined });
    expect(res.status).toBe(503);
  });

  it("returns error body when key is missing", async () => {
    const res = await callGET({ LANGSMITH_API_KEY: undefined });
    const body = await res.json();
    expect(body).toHaveProperty("error");
  });

  it("does not call listRuns when LANGSMITH_API_KEY is missing", async () => {
    await callGET({ LANGSMITH_API_KEY: undefined });
    expect(mockListRuns).not.toHaveBeenCalled();
  });
});

// ---------------------------------------------------------------------------
// Response shape
// ---------------------------------------------------------------------------

describe("Response shape", () => {
  it("returns 200 when key is present", async () => {
    const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
    expect(res.status).toBe(200);
  });

  it("response has dimensions and alerts keys", async () => {
    const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
    const body = await res.json();
    expect(body).toHaveProperty("dimensions");
    expect(body).toHaveProperty("alerts");
  });

  it("dimensions contains an entry for every DIMENSION_ID", async () => {
    const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
    const body = await res.json();
    for (const dimId of DIMENSION_IDS) {
      expect(body.dimensions).toHaveProperty(dimId);
    }
  });

  it("each dimension entry has avg and trend fields", async () => {
    const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
    const body = await res.json();
    for (const dimId of DIMENSION_IDS) {
      const entry = body.dimensions[dimId];
      expect(entry).toHaveProperty("avg");
      expect(entry).toHaveProperty("trend");
      expect(typeof entry.avg).toBe("number");
      expect(typeof entry.trend).toBe("number");
    }
  });

  it("alerts is an array", async () => {
    const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
    const body = await res.json();
    expect(Array.isArray(body.alerts)).toBe(true);
  });
});

// ---------------------------------------------------------------------------
// Score aggregation
// ---------------------------------------------------------------------------

describe("Score aggregation", () => {
  it("avg is 0 when there are no runs in the current period", async () => {
    // no runs in either period β€” defaults to empty arrays
    const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
    const body = await res.json();
    for (const dimId of DIMENSION_IDS) {
      expect(body.dimensions[dimId].avg).toBe(0);
    }
  });

  it("computes avg correctly over multiple scores (denormalised 0-10)", async () => {
    const dimId = DIMENSION_IDS[0]; // "flaw-detection"
    mockRunsByPeriod = [
      [{ id: "run-1" }, { id: "run-2" }],
      [],
    ];
    // run-1: score 0.7 (β†’ 7 after Γ—10), run-2: score 0.9 (β†’ 9 after Γ—10)
    mockFeedbackByRunId.set("run-1", [{ key: dimId, score: 0.7 }]);
    mockFeedbackByRunId.set("run-2", [{ key: dimId, score: 0.9 }]);

    const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
    const body = await res.json();
    // avg = (7 + 9) / 2 = 8.0
    expect(body.dimensions[dimId].avg).toBe(8.0);
  });

  it("rounds avg to 2 decimal places", async () => {
    const dimId = DIMENSION_IDS[0];
    // Three scores: 0.1 β†’ 1, 0.2 β†’ 2, 0.3 β†’ 3: avg = 6/3 = 2.0 β†’ rounded fine
    // Use values that would produce a repeating decimal: 1/3 β‰ˆ 0.333...
    // 0.1 β†’ 1, 0.2 β†’ 2, 0.4 β†’ 4: avg = 7/3 β‰ˆ 2.333... β†’ rounds to 2.33
    mockRunsByPeriod = [[{ id: "r1" }, { id: "r2" }, { id: "r3" }], []];
    mockFeedbackByRunId.set("r1", [{ key: dimId, score: 0.1 }]);
    mockFeedbackByRunId.set("r2", [{ key: dimId, score: 0.2 }]);
    mockFeedbackByRunId.set("r3", [{ key: dimId, score: 0.4 }]);

    const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
    const body = await res.json();
    // avg = (1 + 2 + 4) / 3 = 7/3 β‰ˆ 2.333... β†’ 2.33
    expect(body.dimensions[dimId].avg).toBe(2.33);
  });

  it("ignores feedback keys that are not in DIMENSION_IDS", async () => {
    const dimId = DIMENSION_IDS[0];
    mockRunsByPeriod = [[{ id: "run-x" }], []];
    mockFeedbackByRunId.set("run-x", [
      { key: "unknown-dimension", score: 0.9 },
      { key: dimId, score: 0.5 },
    ]);

    const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
    const body = await res.json();
    // Only the valid dimension score (0.5 β†’ 5) should be counted
    expect(body.dimensions[dimId].avg).toBe(5.0);
    // The unknown key should not appear in the response
    expect(body.dimensions).not.toHaveProperty("unknown-dimension");
  });

  it("ignores feedback entries with null or undefined score", async () => {
    const dimId = DIMENSION_IDS[0];
    mockRunsByPeriod = [[{ id: "run-null" }], []];
    mockFeedbackByRunId.set("run-null", [
      { key: dimId, score: null },
      { key: dimId, score: undefined },
    ] as FeedbackEntry[]);

    const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
    const body = await res.json();
    // All null/undefined scores ignored β†’ avg stays 0
    expect(body.dimensions[dimId].avg).toBe(0);
  });
});

// ---------------------------------------------------------------------------
// Trend calculation
// ---------------------------------------------------------------------------

describe("Trend calculation", () => {
  it("trend is 0 when there is no prior period data", async () => {
    const dimId = DIMENSION_IDS[0];
    mockRunsByPeriod = [[{ id: "run-cur" }], []]; // prior period empty
    mockFeedbackByRunId.set("run-cur", [{ key: dimId, score: 0.8 }]);

    const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
    const body = await res.json();
    expect(body.dimensions[dimId].trend).toBe(0);
  });

  it("trend is positive when current avg is higher than prior", async () => {
    const dimId = DIMENSION_IDS[0];
    mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]];
    // current: 0.8 β†’ 8, prior: 0.4 β†’ 4  =>  trend = (8-4)/4 * 100 = 100%
    mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.8 }]);
    mockFeedbackByRunId.set("pri", [{ key: dimId, score: 0.4 }]);

    const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
    const body = await res.json();
    expect(body.dimensions[dimId].trend).toBeGreaterThan(0);
    expect(body.dimensions[dimId].trend).toBeCloseTo(100, 0);
  });

  it("trend is negative when current avg is lower than prior", async () => {
    const dimId = DIMENSION_IDS[0];
    mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]];
    // current: 0.4 β†’ 4, prior: 0.8 β†’ 8  =>  trend = (4-8)/8 * 100 = -50%
    mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.4 }]);
    mockFeedbackByRunId.set("pri", [{ key: dimId, score: 0.8 }]);

    const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
    const body = await res.json();
    expect(body.dimensions[dimId].trend).toBeLessThan(0);
    expect(body.dimensions[dimId].trend).toBeCloseTo(-50, 0);
  });

  it("trend is 0 when prior and current averages are equal", async () => {
    const dimId = DIMENSION_IDS[0];
    mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]];
    mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.7 }]);
    mockFeedbackByRunId.set("pri", [{ key: dimId, score: 0.7 }]);

    const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
    const body = await res.json();
    expect(body.dimensions[dimId].trend).toBe(0);
  });

  it("trend is rounded to 2 decimal places", async () => {
    const dimId = DIMENSION_IDS[0];
    // current: 0.7 β†’ 7, prior: 0.6 β†’ 6  =>  trend = (7-6)/6 * 100 β‰ˆ 16.666...% β†’ 16.67
    mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]];
    mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.7 }]);
    mockFeedbackByRunId.set("pri", [{ key: dimId, score: 0.6 }]);

    const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
    const body = await res.json();
    expect(body.dimensions[dimId].trend).toBe(16.67);
  });
});

// ---------------------------------------------------------------------------
// Alerts
// ---------------------------------------------------------------------------

describe("Alerts", () => {
  it("no alert when current period has no data (prior avg = 0)", async () => {
    const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
    const body = await res.json();
    expect(body.alerts).toHaveLength(0);
  });

  it("no alert when drop is exactly -10% (boundary β€” strictly > 10% required)", async () => {
    const dimId = DIMENSION_IDS[0];
    // prior avg = 10, current avg = 9 β†’ drop = exactly 10%  β†’  NO alert
    mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]];
    mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.9 }]);
    mockFeedbackByRunId.set("pri", [{ key: dimId, score: 1.0 }]);

    const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
    const body = await res.json();
    expect(body.alerts).toHaveLength(0);
  });

  it("fires alert when drop is greater than 10%", async () => {
    const dimId = DIMENSION_IDS[0];
    // prior avg = 10, current avg = 8 β†’ drop = 20% β†’ alert
    mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]];
    mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.8 }]);
    mockFeedbackByRunId.set("pri", [{ key: dimId, score: 1.0 }]);

    const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
    const body = await res.json();
    expect(body.alerts.length).toBeGreaterThanOrEqual(1);
  });

  it("alert message contains the dimension id", async () => {
    const dimId = DIMENSION_IDS[0]; // "flaw-detection"
    mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]];
    mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.8 }]);
    mockFeedbackByRunId.set("pri", [{ key: dimId, score: 1.0 }]);

    const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
    const body = await res.json();
    expect(body.alerts.some((a: string) => a.includes(dimId))).toBe(true);
  });

  it("alert message contains the percentage drop magnitude", async () => {
    const dimId = DIMENSION_IDS[0];
    // prior = 10, current = 8 β†’ 20% drop
    mockRunsByPeriod = [[{ id: "cur" }], [{ id: "pri" }]];
    mockFeedbackByRunId.set("cur", [{ key: dimId, score: 0.8 }]);
    mockFeedbackByRunId.set("pri", [{ key: dimId, score: 1.0 }]);

    const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
    const body = await res.json();
    const alert: string = body.alerts.find((a: string) => a.includes(dimId));
    expect(alert).toContain("20.0%");
  });

  it("multiple dimensions can fire alerts in the same response", async () => {
    // Both dim 0 and dim 1 drop >10%
    const dim0 = DIMENSION_IDS[0];
    const dim1 = DIMENSION_IDS[1];

    mockRunsByPeriod = [[{ id: "cur0" }, { id: "cur1" }], [{ id: "pri0" }, { id: "pri1" }]];

    // Use separate call tracking via IDs
    mockFeedbackByRunId.set("cur0", [{ key: dim0, score: 0.7 }]);
    mockFeedbackByRunId.set("cur1", [{ key: dim1, score: 0.6 }]);
    mockFeedbackByRunId.set("pri0", [{ key: dim0, score: 1.0 }]);
    mockFeedbackByRunId.set("pri1", [{ key: dim1, score: 1.0 }]);

    const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
    const body = await res.json();
    expect(body.alerts.length).toBeGreaterThanOrEqual(2);
  });
});

// ---------------------------------------------------------------------------
// Error handling
// ---------------------------------------------------------------------------

describe("Error handling", () => {
  it("returns 500 if listRuns throws", async () => {
    mockListRuns.mockImplementationOnce(() => {
      throw new Error("LangSmith API error");
    });

    const res = await callGET({ LANGSMITH_API_KEY: "test-key" });
    expect(res.status).toBe(500);
  });
});