Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

14.3 KB
Raw Blame
import { describe, it, expect } from "vitest";
import {
  CommunityMachineRuntimeSchema,
  CommunityMachineRuntimeListSchema,
  CommunityMachineSummarySchema,
  CommunityDaemonReadySchema,
  HostReadyMessageSchema,
  MachineHeartbeatAckMessageSchema,
  DiagnosticCommandAckMessageSchema,
  SessionErrorFrameSchema,
  COMMUNITY_RUNTIME_ID_MAX,
  COMMUNITY_RUNTIME_LIST_MAX,
  COMMUNITY_REASONING_DESCRIPTION_MAX,
  COMMUNITY_REASONING_MODELS_MAX,
} from "../../src/schemas";
import { CommunityWsEventSchema } from "../../src/community-ws-events";

describe("CommunityMachineSummarySchema", () => {
  const summary = { id: "machine", hostname: "host", displayName: "Host", platform: "darwin", arch: "arm64", osRelease: "26", daemonVersion: "0.1.48", lastSeenAt: null, status: "offline", availableRuntimes: [], createdAt: "2026-10-11T01:00:00Z", updatedAt: "2026-10-11T01:00:00Z" };
  it("keeps actual empty runtime lists and applies the same complete contract to WS", () => {
    expect(CommunityMachineSummarySchema.parse(summary)).toEqual(summary);
    expect(CommunityWsEventSchema.parse({ type: "community:machine.updated", machine: summary })).toEqual({ type: "community:machine.updated", machine: summary });
    const { availableRuntimes: _runtimes, ...missing } = summary;
    expect(CommunityMachineSummarySchema.safeParse(missing).success).toBe(false);
    expect(CommunityWsEventSchema.safeParse({ type: "community:machine.updated", machine: missing }).success).toBe(false);
  });
  it("rejects unknown summary, runtime and error fields without changing runtime health tolerance", () => {
    for (const invalid of [
      { ...summary, extra: true },
      { ...summary, availableRuntimes: [{ id: "codex", extra: true }] },
      { ...summary, lastRuntimeError: { requested: "codex", available: [], at: summary.updatedAt, extra: true } },
    ]) {
      expect(CommunityMachineSummarySchema.safeParse(invalid).success).toBe(false);
      expect(CommunityWsEventSchema.safeParse({ type: "community:machine.updated", machine: invalid }).success).toBe(false);
    }
    expect(CommunityMachineSummarySchema.parse({ ...summary, availableRuntimes: [{ id: "codex", status: null }] }).availableRuntimes).toEqual([{ id: "codex", status: "healthy" }]);
  });
});

describe("CommunityMachineRuntimeSchema", () => {
  it("accepts a plain id and defaults status to 'healthy' (wire back-compat for older daemons)", () => {
    expect(CommunityMachineRuntimeSchema.parse({ id: "claude" })).toEqual({
      id: "claude",
      status: "healthy",
    });
  });

  it("accepts id + version + defaulted status", () => {
    expect(
      CommunityMachineRuntimeSchema.parse({ id: "claude", version: "1.0.0" })
    ).toEqual({ id: "claude", version: "1.0.0", status: "healthy" });
  });

  it("accepts explicit unhealthy + lastError", () => {
    expect(
      CommunityMachineRuntimeSchema.parse({
        id: "codex",
        status: "unhealthy",
        lastError: "version_probe_failed",
        lastErrorAt: "2026-07-06T00:00:00.000Z",
      })
    ).toEqual({
      id: "codex",
      status: "unhealthy",
      lastError: "version_probe_failed",
      lastErrorAt: "2026-07-06T00:00:00.000Z",
    });
  });

  it("catches null status and folds it to 'healthy' — fail-open so a bad daemon doesn't poison the whole ready frame", () => {
    // .catch("healthy") on the enum absorbs null / unknown values that would
    // otherwise fail the enum literal check.
    const parsed = CommunityMachineRuntimeSchema.parse({ id: "codex", status: null as unknown as "healthy" });
    expect(parsed.status).toBe("healthy");
  });

  it("catches an unknown-enum future value ('degraded') and folds it to 'healthy'", () => {
    const parsed = CommunityMachineRuntimeSchema.parse({
      id: "codex",
      status: "degraded" as unknown as "healthy",
    });
    expect(parsed.status).toBe("healthy");
  });

  it("rejects an empty id", () => {
    expect(() => CommunityMachineRuntimeSchema.parse({ id: "" })).toThrow();
  });

  it("rejects an id longer than the cap", () => {
    const tooLong = "a".repeat(COMMUNITY_RUNTIME_ID_MAX + 1);
    expect(() => CommunityMachineRuntimeSchema.parse({ id: tooLong })).toThrow();
  });

  it("rejects an id with disallowed characters (spaces)", () => {
    expect(() => CommunityMachineRuntimeSchema.parse({ id: "cool cli" })).toThrow();
  });

  it("rejects an id with a disallowed character (colon)", () => {
    expect(() => CommunityMachineRuntimeSchema.parse({ id: "invalid:runtime" })).toThrow();
  });

  it("accepts the full charset — alnum + `._@/-`", () => {
    for (const id of ["a", "A", "0", ".", "_", "@", "/", "-", "a.b_C@d/e-1"]) {
      expect(CommunityMachineRuntimeSchema.parse({ id })).toEqual({ id, status: "healthy" });
    }
  });

  it("keeps a healthy runtime while dropping malformed reasoning entries individually", () => {
    const parsed = CommunityMachineRuntimeSchema.parse({
      id: "codex",
      reasoning: {
        updateMode: "live_next_turn",
        defaultModelId: "gpt-5",
        models: [
          {
            id: "gpt-5",
            supportedReasoningEfforts: [
              { value: "minimal", description: "Fast" },
              { value: "future_effort" },
              { value: "bad effort" },
              { value: "minimal", description: "duplicate" },
            ],
            defaultReasoningEffort: "medium",
          },
          {
            id: "gpt-5",
            supportedReasoningEfforts: [{ value: "high" }],
          },
          { id: "", supportedReasoningEfforts: [{ value: "high" }] },
          null,
        ],
      },
    });

    expect(parsed).toEqual({
      id: "codex",
      status: "healthy",
      reasoning: {
        updateMode: "live_next_turn",
        defaultModelId: "gpt-5",
        models: [{
          id: "gpt-5",
          supportedReasoningEfforts: [
            { value: "minimal", description: "Fast" },
            { value: "future_effort" },
          ],
        }],
      },
    });
  });

  it("keeps a supported default reasoning effort", () => {
    const parsed = CommunityMachineRuntimeSchema.parse({
      id: "codex",
      reasoning: {
        updateMode: "live_next_turn",
        models: [{
          id: "gpt-5",
          supportedReasoningEfforts: [{ value: "medium" }, { value: "high" }],
          defaultReasoningEffort: "medium",
        }],
      },
    });

    expect(parsed.reasoning?.models[0]?.defaultReasoningEffort).toBe("medium");
  });

  it("preserves a bounded model display label and drops only a malformed label", () => {
    const parsed = CommunityMachineRuntimeSchema.parse({
      id: "cursor",
      reasoning: {
        updateMode: "unsupported",
        models: [
          {
            id: "grok-4.6[effort=high,fast=true]",
            displayName: "grok-4.6",
            supportedReasoningEfforts: [],
          },
          {
            id: "grok-4.6[effort=max,fast=true]",
            displayName: "x".repeat(COMMUNITY_REASONING_DESCRIPTION_MAX + 1),
            supportedReasoningEfforts: [],
          },
          { id: "legacy-wire-model", supportedReasoningEfforts: [] },
        ],
      },
    });

    expect(parsed.reasoning?.models).toEqual([
      {
        id: "grok-4.6[effort=high,fast=true]",
        displayName: "grok-4.6",
        supportedReasoningEfforts: [],
      },
      {
        id: "grok-4.6[effort=max,fast=true]",
        supportedReasoningEfforts: [],
      },
      { id: "legacy-wire-model", supportedReasoningEfforts: [] },
    ]);
  });

  it("drops a malformed reasoning catalog without poisoning runtime health", () => {
    expect(CommunityMachineRuntimeSchema.parse({
      id: "codex",
      reasoning: { updateMode: "eventually", models: [] },
    })).toEqual({ id: "codex", status: "healthy" });
  });

  it("accepts the full bounded model startup snapshot", () => {
    const models = Array.from({ length: COMMUNITY_REASONING_MODELS_MAX }, (_, index) => ({
      id: `provider/model-${index}`,
      supportedReasoningEfforts: [],
    }));
    expect(CommunityMachineRuntimeSchema.parse({
      id: "opencode",
      reasoning: { updateMode: "unsupported", models },
    }).reasoning?.models).toHaveLength(COMMUNITY_REASONING_MODELS_MAX);
  });

  it("retains the first valid unique models from an overflowing catalog", () => {
    const models = Array.from({ length: COMMUNITY_REASONING_MODELS_MAX + 1 }, (_, index) => ({
      id: `provider/model-${index}`,
      supportedReasoningEfforts: [],
    }));
    expect(CommunityMachineRuntimeSchema.parse({
      id: "opencode",
      reasoning: { updateMode: "unsupported", models: [null, { id: "" }, models[0], ...models] },
    })).toEqual({
      id: "opencode",
      status: "healthy",
      reasoning: { updateMode: "unsupported", models: models.slice(0, COMMUNITY_REASONING_MODELS_MAX) },
    });
  });
});

describe("CommunityMachineRuntimeListSchema", () => {
  it("dedupes by id (first-wins)", () => {
    const out = CommunityMachineRuntimeListSchema.parse([
      { id: "claude", version: "1" },
      { id: "codex" },
      { id: "claude", version: "2" },
    ]);
    expect(out).toEqual([
      { id: "claude", version: "1", status: "healthy" },
      { id: "codex", status: "healthy" },
    ]);
  });

  it("rejects lists larger than the cap", () => {
    const too_many = Array.from(
      { length: COMMUNITY_RUNTIME_LIST_MAX + 1 },
      (_, i) => ({ id: `r${i}` })
    );
    expect(() => CommunityMachineRuntimeListSchema.parse(too_many)).toThrow();
  });

  it("accepts an empty list", () => {
    expect(CommunityMachineRuntimeListSchema.parse([])).toEqual([]);
  });

  it("rejects a list where any entry fails charset validation", () => {
    expect(() =>
      CommunityMachineRuntimeListSchema.parse([{ id: "claude" }, { id: "bad id" }])
    ).toThrow();
  });
});

describe("HostReadyMessageSchema", () => {
  it("accepts the canonical shape", () => {
    const parsed = HostReadyMessageSchema.parse({
      type: "ready",
      runtimeReport: [{ id: "claude", version: "1.0.0" }],
      runningAgents: ["agent_a"],
      hostname: "host",
      platform: "darwin",
      arch: "arm64",
      osRelease: "23.6.0",
      daemonVersion: "0.1.0",
    });
    expect(parsed.runtimeReport).toEqual([
      { id: "claude", version: "1.0.0", status: "healthy" },
    ]);
    expect(parsed.runningAgents).toEqual(["agent_a"]);
    expect(parsed.capabilities).toEqual([]);
  });

  it("defaults runningAgents to an empty array", () => {
    const parsed = HostReadyMessageSchema.parse({
      type: "ready",
      runtimeReport: [],
    });
    expect(parsed.runningAgents).toEqual([]);
    expect(parsed.capabilities).toEqual([]);
  });

  it("accepts bounded capability names and rejects an empty capability", () => {
    expect(HostReadyMessageSchema.parse({
      type: "ready",
      runtimeReport: [],
      capabilities: ["control-heartbeat-v1"],
    }).capabilities).toEqual(["control-heartbeat-v1"]);
    expect(HostReadyMessageSchema.safeParse({
      type: "ready",
      runtimeReport: [],
      capabilities: [""],
    }).success).toBe(false);
  });

  it("rejects the legacy string-only `runtimes` field (no runtimeReport)", () => {
    expect(() =>
      HostReadyMessageSchema.parse({
        type: "ready",
        runtimes: ["claude", "codex"],
        runningAgents: [],
      } as any)
    ).toThrow();
  });

  it("rejects when type is not 'ready'", () => {
    expect(() =>
      HostReadyMessageSchema.parse({
        type: "hello",
        runtimeReport: [],
      } as any)
    ).toThrow();
  });

  it("dedupes runtimeReport entries via the list schema", () => {
    const parsed = HostReadyMessageSchema.parse({
      type: "ready",
      runtimeReport: [{ id: "claude" }, { id: "claude" }],
      runningAgents: [],
    });
    expect(parsed.runtimeReport).toEqual([{ id: "claude", status: "healthy" }]);
  });

  it("accepts one quota snapshot for each supported provider backend", () => {
    const providerQuotas = (["claude", "codex", "grok", "antigravity"] as const).map((agentBackendId) => ({
      agentBackendId,
      observation: {
        status: "error" as const,
        sourceEpoch: "A".repeat(22),
        code: "unavailable" as const,
        retryable: false,
      },
    }));
    expect(HostReadyMessageSchema.parse({
      type: "ready",
      runtimeReport: [],
      providerQuotas,
    }).providerQuotas).toEqual(providerQuotas);
    expect(HostReadyMessageSchema.safeParse({
      type: "ready",
      runtimeReport: [],
      providerQuotas: [...providerQuotas, providerQuotas[0]],
    }).success).toBe(false);
  });

  it.each([125, 256, 257])("accepts and de-dupes a complete %i-item runningAgents report", (count) => {
    const ids = Array.from({ length: count }, (_, index) => `agent_${index}`);
    const parsed = HostReadyMessageSchema.parse({
      type: "ready",
      runtimeReport: [],
      runningAgents: [...ids, ids[0]],
    });
    expect(parsed.runningAgents).toEqual(ids);
  });
});

describe("CommunityDaemonReadySchema", () => {
  it("does not expose the WS-only machine timezone on the activation helper contract", () => {
    expect(CommunityDaemonReadySchema.parse({
      runtimeReport: [{ id: "codex" }],
      timeZone: "Asia/Shanghai",
    })).toEqual({
      runtimeReport: [{ id: "codex", status: "healthy" }],
      runningAgents: [],
    });
  });
});

describe("control-plane receipt schemas", () => {
  it("strictly parses heartbeat and diagnostic ingress receipts", () => {
    expect(MachineHeartbeatAckMessageSchema.parse({
      type: "machine_heartbeat_ack",
      nonce: "nonce_1",
    })).toEqual({ type: "machine_heartbeat_ack", nonce: "nonce_1" });
    expect(DiagnosticCommandAckMessageSchema.parse({
      type: "diagnostics_ack",
      reportId: "dbr_0123456789abcdef",
    })).toEqual({ type: "diagnostics_ack", reportId: "dbr_0123456789abcdef" });
    expect(MachineHeartbeatAckMessageSchema.safeParse({
      type: "machine_heartbeat_ack",
      nonce: "nonce_1",
      extra: true,
    }).success).toBe(false);
  });
});

describe("SessionErrorFrameSchema", () => {
  it("accepts a runtime_not_available frame", () => {
    const parsed = SessionErrorFrameSchema.parse({
      type: "session.error",
      code: "runtime_not_available",
      agentId: "agent_a",
      payload: { requested: "cursor", available: ["claude"] },
    });
    expect(parsed.code).toBe("runtime_not_available");
  });

  it("rejects an unknown code", () => {
    expect(() =>
      SessionErrorFrameSchema.parse({
        type: "session.error",
        code: "bogus",
      } as any)
    ).toThrow();
  });
});