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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
/**
 * Tests for src/lib/langsmith.ts
 *
 * Covers:
 *   langsmithClient singleton
 *     - exports a Client instance
 *     - is the same object on repeated access (singleton)
 *   createRunTracer
 *     - calls langsmithClient.createRun with a valid UUID id
 *     - passes name, inputs, outputs to createRun
 *     - defaults run_type to "llm" when not provided
 *     - uses the provided runType when given
 *     - includes end_time as a valid ISO string
 *     - returns the run ID string
 *     - returns a different ID on each call (UUID uniqueness)
 *     - uses provided id when given (pre-generated run ID)
 *     - returns provided id (not a new UUID) when id is specified
 *   submitDimensionFeedback
 *     - calls langsmithClient.createFeedback with runId and dimensionId
 *     - normalises score: divides by 10 (0-10 → 0-1)
 *     - normalises score: clamps above 10 to 1.0
 *     - normalises score: clamps below 0 to 0.0
 *     - normalises score: exact boundary 10 → 1.0
 *     - normalises score: exact boundary 0 → 0.0
 *     - sets a comment containing the dimensionId
 *   submitAllDimensionFeedback
 *     - calls submitDimensionFeedback once per entry in dimensionScores
 *     - passes correct runId and dimensionId to each call
 *     - passes correct score to each call
 *     - resolves when all dimensions succeed
 *     - rejects if any dimension call throws
 *   submitHumanFeedback
 *     - calls langsmithClient.createFeedback with "human_<dimensionId>" key
 *     - normalises score: 0-10 → 0-1
 *     - clamps above 10 to 1.0
 *     - clamps below 0 to 0.0
 *     - score 0 → 0.0 (exact lower bound)
 *     - score 10 → 1.0 (exact upper bound)
 *     - includes a comment mentioning the dimensionId
 *   submitAllHumanFeedback
 *     - calls submitHumanFeedback once per entry
 *     - passes the correct runId to each call
 *     - uses "human_<dim>" key for each entry
 *     - handles empty scores without calling createFeedback
 *     - rejects if any individual submission throws
 *   flushTraces
 *     - resolves after a brief delay (smoke test — no real assertion)
 */

import { describe, it, expect, vi, beforeEach } from "vitest";

// ---------------------------------------------------------------------------
// Mock the LangSmith Client
// ---------------------------------------------------------------------------

// Use vi.hoisted so the vars are available inside the hoisted vi.mock factory
const { mockCreateRun, mockCreateFeedback } = vi.hoisted(() => ({
  mockCreateRun: vi.fn().mockResolvedValue(undefined),
  mockCreateFeedback: vi.fn().mockResolvedValue(undefined),
}));

vi.mock("langsmith", () => {
  class Client {
    createRun = mockCreateRun;
    createFeedback = mockCreateFeedback;
  }
  return { Client };
});

// Reset mock call history before each test, but keep the same mock instance
beforeEach(() => {
  mockCreateRun.mockClear();
  mockCreateFeedback.mockClear();
});

// Import after the mock is in place
import {
  langsmithClient,
  createRunTracer,
  submitDimensionFeedback,
  submitAllDimensionFeedback,
  submitHumanFeedback,
  submitAllHumanFeedback,
  flushTraces,
} from "../langsmith";

// ---------------------------------------------------------------------------
// langsmithClient singleton
// ---------------------------------------------------------------------------

describe("langsmithClient singleton", () => {
  it("exports a client-like object", () => {
    expect(langsmithClient).toBeDefined();
    expect(typeof langsmithClient.createRun).toBe("function");
    expect(typeof langsmithClient.createFeedback).toBe("function");
  });

  it("is the same object on repeated imports (singleton)", async () => {
    // Re-import to verify singleton pattern
    const { langsmithClient: second } = await import("../langsmith");
    expect(second).toBe(langsmithClient);
  });
});

// ---------------------------------------------------------------------------
// createRunTracer
// ---------------------------------------------------------------------------

describe("createRunTracer", () => {
  it("calls createRun on the client", async () => {
    await createRunTracer({
      name: "test-run",
      inputs: { question: "hello" },
      outputs: { answer: "world" },
    });
    expect(mockCreateRun).toHaveBeenCalledOnce();
  });

  it("passes a valid UUID as the run id", async () => {
    await createRunTracer({
      name: "uuid-test",
      inputs: {},
      outputs: {},
    });
    const call = mockCreateRun.mock.calls[0][0] as { id: string };
    // UUIDs are 36 chars with dashes: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
    expect(call.id).toMatch(
      /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
    );
  });

  it("returns the same run ID that was passed to createRun", async () => {
    const returnedId = await createRunTracer({
      name: "id-match",
      inputs: {},
      outputs: {},
    });
    const call = mockCreateRun.mock.calls[0][0] as { id: string };
    expect(returnedId).toBe(call.id);
  });

  it("returns a string", async () => {
    const id = await createRunTracer({ name: "n", inputs: {}, outputs: {} });
    expect(typeof id).toBe("string");
  });

  it("passes name to createRun", async () => {
    await createRunTracer({
      name: "debate-judge-round",
      inputs: {},
      outputs: {},
    });
    const call = mockCreateRun.mock.calls[0][0] as { name: string };
    expect(call.name).toBe("debate-judge-round");
  });

  it("passes inputs and outputs to createRun", async () => {
    const inputs = { topic: "AI ethics", round: 1 };
    const outputs = { scores: { clarity: 7 } };
    await createRunTracer({ name: "n", inputs, outputs });
    const call = mockCreateRun.mock.calls[0][0] as {
      inputs: typeof inputs;
      outputs: typeof outputs;
    };
    expect(call.inputs).toEqual(inputs);
    expect(call.outputs).toEqual(outputs);
  });

  it("defaults run_type to 'llm' when not provided", async () => {
    await createRunTracer({ name: "n", inputs: {}, outputs: {} });
    const call = mockCreateRun.mock.calls[0][0] as { run_type: string };
    expect(call.run_type).toBe("llm");
  });

  it("uses the provided runType when given", async () => {
    await createRunTracer({
      name: "n",
      inputs: {},
      outputs: {},
      runType: "chain",
    });
    const call = mockCreateRun.mock.calls[0][0] as { run_type: string };
    expect(call.run_type).toBe("chain");
  });

  it("includes end_time as a valid ISO string", async () => {
    await createRunTracer({ name: "n", inputs: {}, outputs: {} });
    const call = mockCreateRun.mock.calls[0][0] as { end_time: string };
    expect(() => new Date(call.end_time).toISOString()).not.toThrow();
    expect(call.end_time).toMatch(/^\d{4}-\d{2}-\d{2}T/);
  });

  it("returns a different ID on each call", async () => {
    const id1 = await createRunTracer({ name: "n", inputs: {}, outputs: {} });
    const id2 = await createRunTracer({ name: "n", inputs: {}, outputs: {} });
    expect(id1).not.toBe(id2);
  });

  it("propagates createRun errors", async () => {
    mockCreateRun.mockRejectedValueOnce(new Error("network error"));
    await expect(
      createRunTracer({ name: "n", inputs: {}, outputs: {} }),
    ).rejects.toThrow("network error");
  });

  it("uses the provided id when given", async () => {
    const prebuiltId = "550e8400-e29b-41d4-a716-446655440000";
    await createRunTracer({ name: "n", inputs: {}, outputs: {}, id: prebuiltId });
    const call = mockCreateRun.mock.calls[0][0] as { id: string };
    expect(call.id).toBe(prebuiltId);
  });

  it("returns the provided id (not a new UUID) when id is specified", async () => {
    const prebuiltId = "550e8400-e29b-41d4-a716-446655440001";
    const result = await createRunTracer({ name: "n", inputs: {}, outputs: {}, id: prebuiltId });
    expect(result).toBe(prebuiltId);
  });
});

// ---------------------------------------------------------------------------
// submitDimensionFeedback
// ---------------------------------------------------------------------------

describe("submitDimensionFeedback", () => {
  it("calls createFeedback with runId and dimensionId", async () => {
    await submitDimensionFeedback("run-123", "flaw-detection", 7);
    expect(mockCreateFeedback).toHaveBeenCalledOnce();
    const [runId, dimId] = mockCreateFeedback.mock.calls[0];
    expect(runId).toBe("run-123");
    expect(dimId).toBe("flaw-detection");
  });

  it("normalises score: 7 becomes 0.7", async () => {
    await submitDimensionFeedback("run-123", "flaw-detection", 7);
    const payload = mockCreateFeedback.mock.calls[0][2] as { score: number };
    expect(payload.score).toBeCloseTo(0.7, 5);
  });

  it("normalises score: 0 becomes 0.0", async () => {
    await submitDimensionFeedback("run-abc", "dim", 0);
    const payload = mockCreateFeedback.mock.calls[0][2] as { score: number };
    expect(payload.score).toBe(0);
  });

  it("normalises score: 10 becomes 1.0", async () => {
    await submitDimensionFeedback("run-abc", "dim", 10);
    const payload = mockCreateFeedback.mock.calls[0][2] as { score: number };
    expect(payload.score).toBe(1.0);
  });

  it("clamps score above 10 to 1.0", async () => {
    await submitDimensionFeedback("run-abc", "dim", 15);
    const payload = mockCreateFeedback.mock.calls[0][2] as { score: number };
    expect(payload.score).toBe(1.0);
  });

  it("clamps score below 0 to 0.0", async () => {
    await submitDimensionFeedback("run-abc", "dim", -5);
    const payload = mockCreateFeedback.mock.calls[0][2] as { score: number };
    expect(payload.score).toBe(0.0);
  });

  it("sets a comment containing the dimensionId", async () => {
    await submitDimensionFeedback("run-xyz", "argument-structure", 8);
    const payload = mockCreateFeedback.mock.calls[0][2] as { comment: string };
    expect(payload.comment).toContain("argument-structure");
  });

  it("propagates createFeedback errors", async () => {
    mockCreateFeedback.mockRejectedValueOnce(new Error("rate limit"));
    await expect(
      submitDimensionFeedback("run-err", "dim", 5),
    ).rejects.toThrow("rate limit");
  });
});

// ---------------------------------------------------------------------------
// submitAllDimensionFeedback
// ---------------------------------------------------------------------------

describe("submitAllDimensionFeedback", () => {
  it("calls createFeedback once per dimension", async () => {
    const scores = {
      "flaw-detection": 7,
      "steelman-awareness": 8,
      "argument-structure": 6,
    };
    await submitAllDimensionFeedback("run-all", scores);
    expect(mockCreateFeedback).toHaveBeenCalledTimes(3);
  });

  it("passes the correct runId to each call", async () => {
    await submitAllDimensionFeedback("run-id-check", {
      "persuasiveness": 5,
      "rebuttal-quality": 9,
    });
    for (const call of mockCreateFeedback.mock.calls) {
      expect(call[0]).toBe("run-id-check");
    }
  });

  it("passes the correct dimension ID to each call", async () => {
    const scores = { "persuasiveness": 5, "intellectual-honesty": 9 };
    await submitAllDimensionFeedback("run-dims", scores);
    const calledDims = mockCreateFeedback.mock.calls.map((c) => c[1]);
    expect(calledDims).toContain("persuasiveness");
    expect(calledDims).toContain("intellectual-honesty");
  });

  it("passes the correct normalised score to each call", async () => {
    await submitAllDimensionFeedback("run-scores", {
      "flaw-detection": 3,
      "evidence-accuracy": 10,
    });
    const scoresByDim: Record<string, number> = {};
    for (const call of mockCreateFeedback.mock.calls) {
      const dimId = call[1] as string;
      const payload = call[2] as { score: number };
      scoresByDim[dimId] = payload.score;
    }
    expect(scoresByDim["flaw-detection"]).toBeCloseTo(0.3, 5);
    expect(scoresByDim["evidence-accuracy"]).toBeCloseTo(1.0, 5);
  });

  it("resolves when all dimensions succeed", async () => {
    await expect(
      submitAllDimensionFeedback("run-ok", { "flaw-detection": 5 }),
    ).resolves.toBeUndefined();
  });

  it("rejects if any individual dimension call throws", async () => {
    mockCreateFeedback.mockResolvedValueOnce(undefined);
    mockCreateFeedback.mockRejectedValueOnce(new Error("feedback error"));
    await expect(
      submitAllDimensionFeedback("run-fail", {
        "dim-a": 5,
        "dim-b": 7,
      }),
    ).rejects.toThrow("feedback error");
  });

  it("handles empty dimensionScores without calling createFeedback", async () => {
    await submitAllDimensionFeedback("run-empty", {});
    expect(mockCreateFeedback).not.toHaveBeenCalled();
  });
});

// ---------------------------------------------------------------------------
// submitHumanFeedback
// ---------------------------------------------------------------------------

describe("submitHumanFeedback", () => {
  it("calls createFeedback with 'human_<dimensionId>' as the key", async () => {
    await submitHumanFeedback("run-abc", "argument-structure", 7);
    expect(mockCreateFeedback).toHaveBeenCalledOnce();
    const [runId, key] = mockCreateFeedback.mock.calls[0];
    expect(runId).toBe("run-abc");
    expect(key).toBe("human_argument-structure");
  });

  it("normalises score: 7 becomes 0.7", async () => {
    await submitHumanFeedback("run-abc", "persuasiveness", 7);
    const opts = mockCreateFeedback.mock.calls[0][2] as { score: number };
    expect(opts.score).toBeCloseTo(0.7, 5);
  });

  it("normalises score: 0 becomes 0.0", async () => {
    await submitHumanFeedback("run-abc", "flaw-detection", 0);
    const opts = mockCreateFeedback.mock.calls[0][2] as { score: number };
    expect(opts.score).toBe(0);
  });

  it("normalises score: 10 becomes 1.0", async () => {
    await submitHumanFeedback("run-abc", "flaw-detection", 10);
    const opts = mockCreateFeedback.mock.calls[0][2] as { score: number };
    expect(opts.score).toBe(1);
  });

  it("clamps score above 10 to 1.0", async () => {
    await submitHumanFeedback("run-abc", "steelman-awareness", 15);
    const opts = mockCreateFeedback.mock.calls[0][2] as { score: number };
    expect(opts.score).toBe(1);
  });

  it("clamps score below 0 to 0.0", async () => {
    await submitHumanFeedback("run-abc", "rebuttal-quality", -5);
    const opts = mockCreateFeedback.mock.calls[0][2] as { score: number };
    expect(opts.score).toBe(0);
  });

  it("sets a comment mentioning the dimensionId", async () => {
    await submitHumanFeedback("run-abc", "intellectual-honesty", 6);
    const opts = mockCreateFeedback.mock.calls[0][2] as { comment: string };
    expect(opts.comment).toContain("intellectual-honesty");
  });

  it("propagates createFeedback errors", async () => {
    mockCreateFeedback.mockRejectedValueOnce(new Error("feedback error"));
    await expect(submitHumanFeedback("run-abc", "persuasiveness", 5)).rejects.toThrow(
      "feedback error",
    );
  });
});

// ---------------------------------------------------------------------------
// submitAllHumanFeedback
// ---------------------------------------------------------------------------

describe("submitAllHumanFeedback", () => {
  it("calls createFeedback once per dimension", async () => {
    await submitAllHumanFeedback("run-xyz", {
      "argument-structure": 7,
      persuasiveness: 8,
    });
    expect(mockCreateFeedback).toHaveBeenCalledTimes(2);
  });

  it("uses 'human_<dim>' key for each entry", async () => {
    await submitAllHumanFeedback("run-xyz", {
      "flaw-detection": 5,
      "rebuttal-quality": 6,
    });
    const keys = mockCreateFeedback.mock.calls.map(
      (c: unknown[]) => c[1] as string,
    );
    expect(keys).toContain("human_flaw-detection");
    expect(keys).toContain("human_rebuttal-quality");
  });

  it("passes the correct runId to each call", async () => {
    await submitAllHumanFeedback("run-feedback-test", { "argument-structure": 9 });
    const runId = mockCreateFeedback.mock.calls[0][0];
    expect(runId).toBe("run-feedback-test");
  });

  it("passes the correct normalised score to each call", async () => {
    await submitAllHumanFeedback("run-xyz", { persuasiveness: 4 });
    const opts = mockCreateFeedback.mock.calls[0][2] as { score: number };
    expect(opts.score).toBeCloseTo(0.4, 5);
  });

  it("handles empty scores without calling createFeedback", async () => {
    await submitAllHumanFeedback("run-xyz", {});
    expect(mockCreateFeedback).not.toHaveBeenCalled();
  });

  it("rejects if any individual submission throws", async () => {
    mockCreateFeedback.mockRejectedValueOnce(new Error("LangSmith down"));
    await expect(
      submitAllHumanFeedback("run-xyz", { "argument-structure": 7 }),
    ).rejects.toThrow("LangSmith down");
  });
});

// ---------------------------------------------------------------------------
// flushTraces
// ---------------------------------------------------------------------------

describe("flushTraces", () => {
  it("resolves without throwing", async () => {
    await expect(flushTraces()).resolves.toBeUndefined();
  });
});