tests / logger.test.ts

import { expect, it } from "vitest";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { createRunDiagnostics, diagnosticErrorCode } from "../src/swarm/logger";

it("writes ordered structured events and correlates concurrent runs", async () => {
  const directory = await fs.mkdtemp(path.join(os.tmpdir(), "swarm-diagnostics-"));
  const file = path.join(directory, "research-events.jsonl");
  try {
    const first = createRunDiagnostics(directory);
    const second = createRunDiagnostics(directory);
    first.record("research.started");
    second.record("research.started");
    first.record("research.failed", { errorCode: diagnosticErrorCode(new TypeError("private custom error text")) });
    await first.flush();

    const raw = await fs.readFile(file, "utf8");
    const events = raw.trim().split("\n").map((line) => JSON.parse(line));
    expect(first.runId).not.toBe(second.runId);
    expect(events).toMatchObject([
      { schemaVersion: 1, runId: first.runId, event: "research.started" },
      { schemaVersion: 1, runId: second.runId, event: "research.started" },
      { schemaVersion: 1, runId: first.runId, event: "research.failed", errorCode: "TypeError" },
    ]);
    expect(raw).not.toContain("private custom error text");
  } finally {
    await fs.unlink(file).catch(() => {});
    await fs.rmdir(directory);
  }
});