Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

14.9 KB
Raw Blame
import { BUSINESS_SCHEMA_VERSION } from "../src/business-schema-version"
import { describe, expect, it } from "vitest"
import {
  COMMUNITY_BROWSER_EVENT_MAX_BYTES,
  COMMUNITY_BULK_BODY_MAX_BYTES,
  COMMUNITY_USER_TARGET_MAX_BYTES,
  CommunityWsEventSchema,
  WS_EVENTS,
  decodeCommunityBrowserEvent,
  validateCommunityWsEvent,
  encodeCommunityBrowserEvent,
  isCommunityEventCandidate,
  isCommunityEventType,
  isValidCommunityUserTarget,
  utf8ByteLength,
  type CommunityBotAuditEvent,
  type CommunityMessageCreate,
  type CommunityWsEvent,
} from "../src/community-ws-events"
import { communityWsEventFixtures, communityResourceMessageFixture, communityResourceChannelFixture, requiredFixturePaths } from "./community-ws-events.fixtures"

function clone<T>(value: T): T {
  return JSON.parse(JSON.stringify(value)) as T
}

function withoutPath(event: CommunityWsEvent, path: readonly string[]): unknown {
  const copy = clone(event) as unknown as Record<string, unknown>
  let target = copy
  for (const segment of path.slice(0, -1)) target = target[segment] as Record<string, unknown>
  delete target[path[path.length - 1]]
  return copy
}

function maximizePadding<T extends CommunityWsEvent>(factory: (padding: string) => T): {
  event: T
  body: string
  byteLength: number
} {
  let low = 0
  let high = COMMUNITY_BROWSER_EVENT_MAX_BYTES
  let best: { event: T; body: string; byteLength: number } | null = null
  while (low <= high) {
    const mid = Math.floor((low + high) / 2)
    const encoded = encodeCommunityBrowserEvent(factory("x".repeat(mid)))
    if (encoded.ok) {
      best = { event: factory("x".repeat(mid)), body: encoded.body, byteLength: encoded.byteLength }
      low = mid + 1
    } else {
      high = mid - 1
    }
  }
  if (!best) throw new Error("fixture cannot fit")
  return best
}

function worstEscapingTarget(index: number): string {
  const chars = Array.from({ length: COMMUNITY_USER_TARGET_MAX_BYTES }, () => "\u0000")
  let cursor = index
  for (let offset = 1; offset <= 4; offset += 1) {
    chars[chars.length - offset] = String.fromCharCode(cursor % 8)
    cursor = Math.floor(cursor / 8)
  }
  return chars.join("")
}

describe("Community browser event runtime contract", () => {
  const fixtures = Object.values(communityWsEventFixtures)
  const names = Object.values(WS_EVENTS).sort()

  it("locks the exact 46-event inventory", () => {
    expect(names).toHaveLength(46)
    expect(Object.keys(communityWsEventFixtures).sort()).toEqual(names)
    expect(Object.keys(requiredFixturePaths).sort()).toEqual(names)
  })

  it("decodes and canonically encodes all 46 current event fixtures", () => {
    for (const fixture of fixtures) {
      expect(validateCommunityWsEvent(fixture)).toEqual({ ok: true, event: fixture })
      const encoded = encodeCommunityBrowserEvent(fixture)
      expect(encoded.ok).toBe(true)
      if (!encoded.ok) continue
      expect(encoded.event).toEqual(fixture)
      expect(encoded.event).not.toHaveProperty("contractVersion")
      expect(JSON.parse(encoded.body)).toEqual({ ...fixture, schemaVersion: BUSINESS_SCHEMA_VERSION })
      expect(decodeCommunityBrowserEvent(JSON.parse(encoded.body))).toEqual({ ok: true, event: fixture })
      expect(decodeCommunityBrowserEvent(encoded.envelope)).toEqual({ ok: true, event: fixture })
      expect(decodeCommunityBrowserEvent(fixture).ok).toBe(false)
    }
  })

  it("accepts daemon-accepted turn interrupts as live bot audit events", () => {
    const event = {
      ...communityWsEventFixtures["community:bot.audit_event"],
      kind: "turn_interrupt",
      payload: { status: "accepted" },
    }
    expect(validateCommunityWsEvent(event)).toEqual({ ok: true, event })
  })

  it("rejects missing fields or extra payload on every event", () => {
    for (const fixture of fixtures) {
      const path = requiredFixturePaths[fixture.type]
      const corrupted = path.length ? withoutPath(fixture, path) : { ...fixture, entries: [] }
      expect(validateCommunityWsEvent(corrupted)).toMatchObject({
        ok: false,
        reason: "invalid-payload",
        type: fixture.type,
      })
    }
  })

  it("uses a bounded read-state dirty hint instead of an account-sized frame", () => {
    expect(validateCommunityWsEvent({
      type: "community:read_state.advanced",
      revision: 4,
      inboxChanged: true,
    })).toMatchObject({ ok: true })
    expect(validateCommunityWsEvent({
      type: "community:inbox.changed",
      revision: 5,
      inboxChanged: true,
      reason: "read_all",
    })).toMatchObject({ ok: true })

    const accountSizedFrame = {
      type: "community:read_state.advanced",
      revision: 4,
      readStates: Array.from({ length: 500 }, (_, index) => ({
        channelId: `channel-${index}-${"c".repeat(72)}`,
        lastReadMessageId: `message-${index}-${"m".repeat(72)}`,
        lastReadAt: "2026-08-24T00:00:00.000Z",
        lastReadSeq: index,
      })),
      inboxChanged: true,
    }
    expect(utf8ByteLength(JSON.stringify(accountSizedFrame)))
      .toBeGreaterThan(COMMUNITY_BROWSER_EVENT_MAX_BYTES)
    expect(validateCommunityWsEvent(accountSizedFrame))
      .toMatchObject({ ok: false, reason: "invalid-payload" })
    const encodedHint = encodeCommunityBrowserEvent({
      type: "community:read_state.advanced",
      revision: 4,
      inboxChanged: true,
    })
    expect(encodedHint).toMatchObject({ ok: true })
    if (encodedHint.ok) expect(encodedHint.byteLength).toBeLessThan(128)
  })

  it("fails closed for family, removed-version, shape, and strict-key errors", () => {
    expect(validateCommunityWsEvent(null)).toMatchObject({ reason: "non-object" })
    expect(validateCommunityWsEvent([])).toMatchObject({ reason: "non-object" })
    expect(validateCommunityWsEvent({})).toMatchObject({ reason: "missing-type" })
    expect(validateCommunityWsEvent({ type: "task.messages" })).toMatchObject({ reason: "wrong-family" })
    expect(validateCommunityWsEvent({ type: "community:future" })).toMatchObject({ reason: "unknown-community-type" })
    expect(validateCommunityWsEvent({ ...fixtures[0], contractVersion: 1 }))
      .toMatchObject({ reason: "invalid-payload" })
    expect(encodeCommunityBrowserEvent({ ...fixtures[0], contractVersion: 1 }))
      .toMatchObject({ ok: false, reason: "invalid-payload" })
    expect(validateCommunityWsEvent({ ...fixtures[0], contractVersion: 2 }))
      .toMatchObject({ reason: "invalid-payload" })
    expect(validateCommunityWsEvent({ ...fixtures[0], extra: true })).toMatchObject({ reason: "invalid-payload" })
    const nestedExtra = clone(communityWsEventFixtures["community:message.create"]) as CommunityMessageCreate & {
      message: CommunityMessageCreate["message"] & { extra: boolean }
    }
    nestedExtra.message.extra = true
    expect(validateCommunityWsEvent(nestedExtra)).toMatchObject({ reason: "invalid-payload" })
    expect(validateCommunityWsEvent({
      type: "community:message.edited",
      channelId: "child",
      messageId: "message",
      content: "title",
      parentChannelId: "forum",
    })).toMatchObject({ reason: "unknown-community-type" })
  })

  it("validates full reply targets before a message event can publish any resource", () => {
    const base = communityWsEventFixtures["community:message.create"]
    const target = { ...base.message, id: "target", replyToId: null }
    const event = { ...base, message: { ...base.message, replyToId: target.id }, relatedMessages: [target] }
    expect(CommunityWsEventSchema.parse(event)).toEqual(event)
    for (const relatedMessages of [
      [{ ...target, channelId: "foreign" }], [{ ...target, id: "unrelated" }], [target, target], [event.message],
      [target, { ...target, id: "second-level" }],
    ]) expect(CommunityWsEventSchema.safeParse({ ...event, relatedMessages }).success).toBe(false)
  })

  it("keeps exact and candidate guards distinct", () => {
    expect(isCommunityEventType("community:message.create")).toBe(true)
    expect(isCommunityEventType("community:future")).toBe(false)
    expect(isCommunityEventCandidate({ type: "community:future" })).toBe(true)
    expect(isCommunityEventCandidate({ type: "task.messages" })).toBe(false)
  })

  it("accepts the fattest legal message and audit fixtures without truncation", () => {
    const message = maximizePadding<CommunityMessageCreate>((padding) => ({
      ...communityWsEventFixtures["community:message.create"],
      message: {
        ...communityWsEventFixtures["community:message.create"].message,
        content: "m".repeat(4000),
        attachments: Array.from({ length: 10 }, (_, index) => ({
          id: `attachment-${index}`,
          name: `file-${index}.txt`, thumbnailUrl: null, width: null, height: null,
          url: `/api/community/channels/channel-1/attachments/attachment-${index}`,
          contentType: "text/plain",
          sizeBytes: 25 * 1024 * 1024,
        })),
        embeds: [{ padding }],
      },
    }))
    const audit = maximizePadding<CommunityBotAuditEvent>((padding) => ({
      ...communityWsEventFixtures["community:bot.audit_event"],
      kind: "thinking",
      payload: { text: "t".repeat(4096), padding },
    }))
    expect(message.byteLength).toBe(COMMUNITY_BROWSER_EVENT_MAX_BYTES)
    expect(audit.byteLength).toBe(COMMUNITY_BROWSER_EVENT_MAX_BYTES)
    expect(JSON.parse(message.body).message.content).toHaveLength(4000)
    expect(JSON.parse(message.body).message.attachments).toHaveLength(10)
    expect(CommunityWsEventSchema.safeParse(message.event).success).toBe(true)
    expect(CommunityWsEventSchema.safeParse(audit.event).success).toBe(true)
    expect(encodeCommunityBrowserEvent({
      ...message.event,
      message: { ...message.event.message, embeds: [{ padding: `${(message.event.message.embeds?.[0] as { padding: string }).padding}x` }] },
    })).toMatchObject({ ok: false, reason: "oversized", byteLength: COMMUNITY_BROWSER_EVENT_MAX_BYTES + 1 })
  })

  it("locks UTF-8 target boundaries and the strict bulk formula", () => {
    const uuid = "123e4567-e89b-12d3-a456-426614174000"
    expect(isValidCommunityUserTarget("a".repeat(32))).toBe(true)
    expect(isValidCommunityUserTarget(uuid)).toBe(true)
    expect(isValidCommunityUserTarget("é".repeat(64))).toBe(true)
    expect(isValidCommunityUserTarget("é".repeat(64) + "a")).toBe(false)
    expect(isValidCommunityUserTarget("")).toBe(false)
    expect(isValidCommunityUserTarget("a".repeat(128))).toBe(true)
    expect(isValidCommunityUserTarget("a".repeat(129))).toBe(false)
    expect(isValidCommunityUserTarget("\ud800")).toBe(false)
    expect(isValidCommunityUserTarget("\udfff")).toBe(false)
    expect(isValidCommunityUserTarget("\ud83d\ude00")).toBe(true)

    const targets = Array.from({ length: 1000 }, (_, index) => worstEscapingTarget(index))
    expect(new Set(targets).size).toBe(1000)
    expect(targets.every((target) => utf8ByteLength(target) === 128)).toBe(true)
    expect(targets.every((target) => utf8ByteLength(JSON.stringify(target)) === 770)).toBe(true)
    const emptyEventBody = JSON.stringify({
      userIds: targets,
      message: {},
      excludeUserId: worstEscapingTarget(1000),
    })
    expect(utf8ByteLength(emptyEventBody)).toBe(771_813)
    expect(utf8ByteLength(emptyEventBody) + COMMUNITY_BROWSER_EVENT_MAX_BYTES - 2)
      .toBe(COMMUNITY_BULK_BODY_MAX_BYTES)
  })
})


describe("current full-resource browser events", () => {
  it("admits child resources only with matching parent identities", () => {
    const event = { type: "community:channel.child_create", parentChannelId: "parent", parentMessageId: "opener", channel: {
      ...communityResourceChannelFixture, id: "thread", type: "thread", parentChannelId: "parent", parentMessageId: "opener",
    } }
    expect(validateCommunityWsEvent(event, BUSINESS_SCHEMA_VERSION)).toEqual({ ok: true, event })
    const { parentMessageId: _parentMessageId, ...withoutOpenerClaim } = event
    expect(validateCommunityWsEvent(withoutOpenerClaim, BUSINESS_SCHEMA_VERSION)).toEqual({ ok: true, event: withoutOpenerClaim })
    for (const fields of [{ parentChannelId: "other" }, { parentMessageId: "other" }]) {
      expect(validateCommunityWsEvent({ ...event, ...fields }, BUSINESS_SCHEMA_VERSION)).toMatchObject({ ok: false, reason: "invalid-payload" })
    }
  })
  it("requires a positive avatar version on a current identity update", () => {
    const event = { type: WS_EVENTS.IDENTITY_UPDATE, userId: "user-1", avatar: null, avatarVersion: 1 }
    expect(validateCommunityWsEvent(event, BUSINESS_SCHEMA_VERSION)).toEqual({ ok: true, event })
    for (const avatarVersion of [0, -1, 0.5]) {
      expect(validateCommunityWsEvent({ ...event, avatarVersion }, BUSINESS_SCHEMA_VERSION)).toMatchObject({ ok: false, reason: "invalid-payload" })
    }
  })
  it("requires full resources on create and preserves partial deltas", () => {
    expect(validateCommunityWsEvent(communityResourceMessageFixture, BUSINESS_SCHEMA_VERSION)).toEqual({ ok: true, event: communityResourceMessageFixture })
    expect(validateCommunityWsEvent(communityResourceMessageFixture, 2).ok).toBe(false)
    expect(validateCommunityWsEvent({ ...communityWsEventFixtures["community:message.create"], message: { id: "message-1", content: "weak" } }, BUSINESS_SCHEMA_VERSION).ok).toBe(false)
    expect(validateCommunityWsEvent({ ...communityResourceMessageFixture, channelId: "other" }, BUSINESS_SCHEMA_VERSION).ok).toBe(false)
    const create = { type: WS_EVENTS.CHANNEL_CREATE, serverId: "server-1", channel: communityResourceChannelFixture }
    expect(validateCommunityWsEvent(create, BUSINESS_SCHEMA_VERSION)).toEqual({ ok: true, event: create })
    expect(validateCommunityWsEvent({ ...create, serverId: "other" }, BUSINESS_SCHEMA_VERSION).ok).toBe(false)
    expect(validateCommunityWsEvent({ ...create, channel: { id: "channel-1", name: "Channel", type: "text" } }, BUSINESS_SCHEMA_VERSION).ok).toBe(false)
    const delta = { type: WS_EVENTS.CHANNEL_UPDATE, serverId: "server-1", channelId: "channel-1", changes: { name: "Renamed" } }
    expect(validateCommunityWsEvent(delta, BUSINESS_SCHEMA_VERSION)).toEqual({ ok: true, event: delta })
    const encoded = encodeCommunityBrowserEvent(communityResourceMessageFixture, BUSINESS_SCHEMA_VERSION)
    expect(encoded.ok).toBe(true)
    if (encoded.ok) expect(encoded.byteLength).toBe(utf8ByteLength(encoded.body))
    expect(encodeCommunityBrowserEvent({ ...communityResourceMessageFixture, message: { ...communityResourceMessageFixture.message, content: "😀".repeat(COMMUNITY_BROWSER_EVENT_MAX_BYTES) } }, BUSINESS_SCHEMA_VERSION).ok).toBe(false)
  })
})

it("current server rail hints carry no order or account payload; old versions reject", () => {
  const hint = { type: "community:server_rail.changed" }
  const encoded = encodeCommunityBrowserEvent(hint)
  if (!encoded.ok) throw new Error("invalid current fixture")
  expect(decodeCommunityBrowserEvent(encoded.envelope)).toEqual({ ok: true, event: hint })
  for (const version of [1, 2, 3, BUSINESS_SCHEMA_VERSION - 1]) expect(decodeCommunityBrowserEvent({ ...hint, schemaVersion: version }).ok).toBe(false)
  for (const extra of [{ entries: [] }, { userId: "other" }]) expect(validateCommunityWsEvent({ ...hint, ...extra }).ok).toBe(false)
})