Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript
89.9 KB
Raw Blame
'use strict'

const assert = require('node:assert/strict')
const crypto = require('node:crypto')
const fs = require('node:fs')
const path = require('node:path')
const test = require('node:test')
const zlib = require('node:zlib')
const contract = require('./index.cjs')
const visualPayload = require('./visualPayload.cjs')
const {
  declaredHeaderPng,
  declaredHeaderPngOfSize,
  jpegOfSize,
  padJpegToSize,
  padPngToSize,
  realPng,
  realPngOfSize,
} = require('./testImageFixtures.cjs')

const FIXTURE = JSON.parse(
  fs.readFileSync(path.join(__dirname, 'fixtures/canonical-request-hashes.json'), 'utf8')
)

const FIXTURE_V2 = JSON.parse(
  fs.readFileSync(path.join(__dirname, 'fixtures/canonical-request-hashes.v2.json'), 'utf8')
)
const VISUAL_FIXTURE = JSON.parse(
  fs.readFileSync(path.join(__dirname, 'fixtures/visual-requests.json'), 'utf8')
)

const BASE = {
  schemaVersion: 'codex-completion-request.v1',
  requestId: 'req-001',
  idempotencyKey: 'idem-001',
  provider: 'codex-subscription',
  model: 'gpt-5.1',
  messages: [{ role: 'user', content: 'hello' }],
}

test('runtime exports stay aligned with the declaration file', () => {
  const declarations = fs.readFileSync(path.join(__dirname, 'index.d.ts'), 'utf8')
  const declared = Array.from(
    declarations.matchAll(/export declare (?:const|function)\s+([A-Za-z0-9_]+)/g),
    m => m[1]
  ).sort()
  assert.deepEqual(Object.keys(contract).sort(), declared)
})

// The proxy, control-api and mcp-host all import this allowance instead of
// writing their own literal, so the declared literal type has to follow the
// runtime value too.
test('exports the 16 KiB envelope allowance with a matching declared literal', () => {
  assert.equal(contract.ENVELOPE_ALLOWANCE_BYTES, 16 * 1024)
  const declarations = fs.readFileSync(path.join(__dirname, 'index.d.ts'), 'utf8')
  const declared = declarations.match(/export declare const ENVELOPE_ALLOWANCE_BYTES:\s*(\d+)\b/)
  assert.ok(declared, 'index.d.ts must declare ENVELOPE_ALLOWANCE_BYTES as a numeric literal')
  assert.equal(Number(declared[1]), contract.ENVELOPE_ALLOWANCE_BYTES)
})

// The export-name check above compares export names only. `LIMITS` is declared with literal
// types, so a bound raised in the runtime module and left behind in the
// declaration file compiles every TypeScript consumer against the old number
// while the runtime accepts the new one.
test('declared LIMITS literals match the runtime values', () => {
  const declarations = fs.readFileSync(path.join(__dirname, 'index.d.ts'), 'utf8')
  const block = declarations.match(/export declare const LIMITS: \{([\s\S]*?)\n\}/)
  assert.ok(block, 'index.d.ts must declare a LIMITS object literal')
  // Comments are stripped first, so a commented-out member cannot stand in for
  // a real one. Every remaining line must be a member with a plain integer
  // literal: a widened `number`, a decimal or a numeric separator fails here
  // rather than being skipped by the scrape.
  const members = block[1]
    .replace(/\/\*[\s\S]*?\*\//g, '')
    .replace(/\/\/.*$/gm, '')
    .split('\n')
    .map(line => line.trim())
    .filter(line => line !== '')
  const declared = Object.fromEntries(
    members.map(line => {
      const m = /^readonly ([A-Za-z0-9_]+): (\d+)$/.exec(line)
      assert.ok(m, `LIMITS member must be "readonly <name>: <integer literal>": ${line}`)
      return [m[1], Number(m[2])]
    })
  )
  // fromEntries keeps the last of two members with the same name.
  assert.equal(Object.keys(declared).length, members.length, 'LIMITS declares a member twice')
  assert.deepEqual(declared, { ...contract.LIMITS })
})

// control-api signs execution tickets for this long and derives its ticket TTL
// from this value; the proxies bound their admission waits against it (#739).
test('LIMITS publishes the execution ticket TTL, declared as the same literal', () => {
  assert.equal(contract.LIMITS.executionTicketTtlMs, 60000)
  const declarations = fs.readFileSync(path.join(__dirname, 'index.d.ts'), 'utf8')
  const block = declarations.match(/export declare const LIMITS: \{([\s\S]*?)\n\}/)
  // Witness: the declaration block was found and read.
  assert.ok(block, 'index.d.ts must declare a LIMITS object literal')
  assert.match(block[1], /^\s*readonly maxRequestBodyBytes: 8388608$/m)
  assert.match(block[1], /^\s*readonly executionTicketTtlMs: 60000$/m)
})

test('parses the bounded V1 request and hashes with SHA-256', () => {
  const parsed = contract.parseCodexCompletionRequestV1(BASE)
  assert.equal(parsed.ok, true)
  const digest = contract.hashCodexCompletionRequestV1(parsed.value)
  assert.match(digest, /^[a-f0-9]{64}$/)
})

test('fixture corpus: valid cases match frozen hashes and equivalent reorderings', () => {
  for (const fixture of FIXTURE.cases) {
    const parsed = contract.parseCodexCompletionRequestV1(fixture.request)
    assert.equal(parsed.ok, true, fixture.name)
    const digest = contract.hashCodexCompletionRequestV1(parsed.value)
    assert.equal(digest, fixture.sha256, fixture.name)
    if (fixture.equivalentRequest) {
      const other = contract.parseCodexCompletionRequestV1(fixture.equivalentRequest)
      assert.equal(other.ok, true, `${fixture.name} equivalent`)
      assert.equal(
        contract.hashCodexCompletionRequestV1(other.value),
        digest,
        `${fixture.name} reorder`
      )
    }
    if (fixture.distinctRequest) {
      const other = contract.parseCodexCompletionRequestV1(fixture.distinctRequest)
      assert.equal(other.ok, true, `${fixture.name} distinct`)
      assert.notEqual(
        contract.hashCodexCompletionRequestV1(other.value),
        digest,
        `${fixture.name} array order`
      )
    }
  }
})

test('fixture corpus: rejected payloads fail closed', () => {
  for (const fixture of FIXTURE.rejects) {
    const parsed = contract.parseCodexCompletionRequestV1(fixture.request)
    assert.equal(parsed.ok, false, fixture.name)
    assert.equal(typeof parsed.code, 'string')
  }
})

test('rejects NaN and Infinity before hashing (stableStringify would coerce them to null)', () => {
  const nanParsed = contract.parseCodexCompletionRequestV1({
    ...BASE,
    generation: { temperature: Number.NaN },
  })
  assert.equal(nanParsed.ok, false)
  assert.match(nanParsed.code, /non-finite|invalid/)

  const infParsed = contract.parseCodexCompletionRequestV1({
    ...BASE,
    generation: { maxOutputTokens: Number.POSITIVE_INFINITY },
  })
  assert.equal(infParsed.ok, false)
  assert.match(infParsed.code, /non-finite|invalid/)
})

test('unknown fields, OAuth, account selector, URL/header/cookie/path and MCP/shell/browser are rejected', () => {
  const extras = [
    { headers: { Authorization: 'x' } },
    { authorization: 'Bearer x' },
    { accessToken: 'sk-x' },
    { refreshToken: 'rt-x' },
    { oauth: { code: 'x' } },
    { accountSelector: 'acct' },
    { accountId: 'acct' },
    { url: 'https://example.com' },
    { cookie: 'a=b' },
    { path: '/tmp' },
    { mcp: true },
    { shell: true },
    { browser: true },
  ]
  for (const extra of extras) {
    const parsed = contract.parseCodexCompletionRequestV1({ ...BASE, ...extra })
    assert.equal(parsed.ok, false, JSON.stringify(Object.keys(extra)))
  }
})

test('hash is SHA-256 of lexicographic stableStringify of the projection', () => {
  const parsed = contract.parseCodexCompletionRequestV1(BASE)
  assert.equal(parsed.ok, true)
  const expected = crypto
    .createHash('sha256')
    .update(contract.stableStringify(parsed.value))
    .digest('hex')
  assert.equal(contract.hashCodexCompletionRequestV1(parsed.value), expected)
})

test('computeCodexPolicyHash is SHA-256 of lexicographic stableStringify of the binding', () => {
  const binding = {
    catalogRevision: 4,
    connectionKey: 'deployment-default',
    credentialRevision: 3,
    model: 'gpt-5.1',
    provider: 'codex-subscription',
  }
  const expected = crypto
    .createHash('sha256')
    .update(contract.stableStringify(binding))
    .digest('hex')
  assert.equal(
    contract.computeCodexPolicyHash({
      model: 'gpt-5.1',
      catalogRevision: 4,
      credentialRevision: 3,
    }),
    expected
  )
  assert.equal(
    contract.computeCodexPolicyHash({
      credentialRevision: 3,
      catalogRevision: 4,
      model: 'gpt-5.1',
      connectionKey: 'deployment-default',
    }),
    expected
  )
  assert.notEqual(
    contract.computeCodexPolicyHash({
      model: 'gpt-5.6-luna',
      catalogRevision: 4,
      credentialRevision: 3,
    }),
    expected
  )
  assert.notEqual(
    contract.computeCodexPolicyHash({
      model: 'gpt-5.1',
      catalogRevision: 4,
      credentialRevision: 3,
      connectionKey: 'team-plus',
    }),
    expected
  )
})

test('stableStringify sorts object keys and drops undefined like control-api', () => {
  assert.equal(contract.stableStringify({ b: 1, a: 2 }), '{"a":2,"b":1}')
  assert.equal(contract.stableStringify({ a: undefined, b: 1 }), '{"b":1}')
  assert.equal(contract.stableStringify([1, undefined, 2]), '[1,null,2]')
})

test('assistant toolCalls are hashed into the request and rejected on other roles', () => {
  const withTools = contract.parseCodexCompletionRequestV1({
    ...BASE,
    messages: [
      { role: 'user', content: 'hi' },
      {
        role: 'assistant',
        content: '',
        toolCalls: [{ id: 'call-1', name: 'echo', arguments: { x: 1 } }],
      },
      { role: 'tool', content: 'ok', toolCallId: 'call-1' },
    ],
  })
  assert.equal(withTools.ok, true)
  const digest = contract.hashCodexCompletionRequestV1(withTools.value)
  const without = contract.parseCodexCompletionRequestV1({
    ...BASE,
    messages: [
      { role: 'user', content: 'hi' },
      { role: 'assistant', content: '' },
      { role: 'tool', content: 'ok', toolCallId: 'call-1' },
    ],
  })
  assert.equal(without.ok, true)
  assert.notEqual(contract.hashCodexCompletionRequestV1(without.value), digest)

  const onUser = contract.parseCodexCompletionRequestV1({
    ...BASE,
    messages: [
      {
        role: 'user',
        content: 'hi',
        toolCalls: [{ id: 'call-1', name: 'echo', arguments: {} }],
      },
    ],
  })
  assert.equal(onUser.ok, false)
})

test('ticket and receipt types stay credential-free at the contract boundary', () => {
  const claims = {
    jti: 'jti-1',
    typ: 'codex-execution-ticket',
    sub: 'host-a',
    hostRef: 'host-a',
    invocationId: 'inv-1',
    attemptGeneration: 1,
    providerAttemptId: 'att-1',
    providerAttemptIndex: 0,
    provider: 'codex-subscription',
    model: 'gpt-5.1',
    requestHash: 'a'.repeat(64),
    policyRevision: 1,
    policyHash: 'b'.repeat(64),
    budgetReservationId: 'bud-1',
    connectionRevision: 1,
  }
  const parsed = contract.parseCodexExecutionTicketClaims(claims)
  assert.equal(parsed.ok, true)
  assert.equal('accessToken' in parsed.value, false)

  const receipt = contract.parseCodexAttemptReceiptV1({
    schemaVersion: 'codex-attempt-receipt.v1',
    providerAttemptId: 'att-1',
    requestHash: 'a'.repeat(64),
    outcome: 'success',
    usage: { inputTokens: 3, outputTokens: 5 },
  })
  assert.equal(receipt.ok, true)
  assert.equal('accessToken' in receipt.value, false)
})

test('authorize response is metadata-only; redeem type is documented but not parsed here', () => {
  const authorize = contract.parseAuthorizeAttemptResponse({
    providerAttemptId: 'att-1',
    requestHash: 'a'.repeat(64),
    executionTicket: 'jwt.ticket',
    expiresAt: '2026-08-20T10:00:00.000Z',
  })
  assert.equal(authorize.ok, true)
  assert.equal('accessToken' in authorize.value, false)
  assert.equal('accountId' in authorize.value, false)
  assert.equal(typeof contract.RedeemAttemptResponseSensitive, 'undefined')
})

function catalog(count) {
  return Array.from({ length: count }, (_, index) => ({
    name: `eventasks__read_${index}`,
    description: 'Read an approved development record',
    parameters: { type: 'object', properties: { id: { type: 'string' } } },
  }))
}

for (const count of [1, 32, 33, 83, 150, 250]) {
  test(`preserves every definition in a ${count}-tool approved catalog`, () => {
    const tools = catalog(count)
    const parsed = contract.parseCodexCompletionRequestV1({ ...BASE, tools })
    assert.equal(parsed.ok, true, parsed.message)
    assert.deepEqual(parsed.value.tools, tools)
    const reordered = tools.map(({ name, description, parameters }) => ({
      parameters,
      description,
      name,
    }))
    const equivalent = contract.parseCodexCompletionRequestV1({ ...BASE, tools: reordered })
    assert.equal(equivalent.ok, true)
    assert.equal(
      contract.hashCodexCompletionRequestV1(parsed.value),
      contract.hashCodexCompletionRequestV1(equivalent.value)
    )
    const changed = contract.parseCodexCompletionRequestV1({
      ...BASE,
      tools: [...tools.slice(0, -1), { ...tools.at(-1), description: 'Changed capability' }],
    })
    assert.equal(changed.ok, true)
    assert.notEqual(
      contract.hashCodexCompletionRequestV1(parsed.value),
      contract.hashCodexCompletionRequestV1(changed.value)
    )
  })
}

test('tool definition count never widens the independent assistant call limit', () => {
  assert.equal(contract.LIMITS.maxToolCalls, 256)
  assert.equal(Object.hasOwn(contract.LIMITS, 'maxTools'), false)
  for (const count of [256, 257]) {
    const parsed = contract.parseCodexCompletionRequestV1({
      ...BASE,
      tools: catalog(250),
      messages: [
        {
          role: 'assistant',
          content: '',
          toolCalls: Array.from({ length: count }, (_, index) => ({
            id: `call-${index}`,
            name: `eventasks__read_${index}`,
            arguments: {},
          })),
        },
      ],
    })
    assert.equal(parsed.ok, count === 256)
    if (!parsed.ok) assert.equal(parsed.message, 'messages[0].toolCalls exceed 256')
  }
})

test('message count is bounded at maxMessages', () => {
  assert.equal(contract.LIMITS.maxMessages, 1024)
  for (const count of [1024, 1025]) {
    const parsed = contract.parseCodexCompletionRequestV1({
      ...BASE,
      messages: Array.from({ length: count }, (_, index) => ({ role: 'user', content: `m${index}` })),
    })
    assert.equal(parsed.ok, count === 1024)
    if (!parsed.ok) assert.equal(parsed.message, 'messages exceed 1024')
  }
})

test('large catalogs remain bounded by serialized request bytes including UTF-8', () => {
  const request = { ...BASE, tools: catalog(250) }
  const originalBytes = Buffer.byteLength(JSON.stringify(request), 'utf8')
  request.tools[249].description += 'x'.repeat(contract.LIMITS.maxRequestBodyBytes - originalBytes)
  assert.equal(
    Buffer.byteLength(JSON.stringify(request), 'utf8'),
    contract.LIMITS.maxRequestBodyBytes
  )
  assert.equal(contract.parseCodexCompletionRequestV1(request).ok, true)
  request.tools[249].description += 'é'
  assert.deepEqual(contract.parseCodexCompletionRequestV1(request), {
    ok: false,
    code: 'limit',
    kind: 'size',
    message: 'request exceeds maxRequestBodyBytes',
  })
})

// A conversation whose size is data, not tools: tool calls answered by
// minified JSON exports, the shape that filled the subscription paths.
function dataHeavyConversation(targetBytes) {
  const row = JSON.stringify({ id: 'c_0001', company: 'Northwind Labs', score: 42.5, tags: ['saas', 'partner'] })
  const chunk = `[${new Array(Math.ceil((256 * 1024) / (row.length + 1))).fill(row).join(',')}]`
  const request = {
    ...BASE,
    tools: [{ name: 'crm__export', description: 'Export CRM rows', parameters: { type: 'object' } }],
    messages: [{ role: 'user', content: 'Summarize the CRM export.' }],
  }
  for (let i = 0; Buffer.byteLength(JSON.stringify(request), 'utf8') < targetBytes; i++) {
    const id = `call-${i}`
    request.messages.push({ role: 'assistant', content: '', toolCalls: [{ id, name: 'crm__export', arguments: { page: i } }] })
    request.messages.push({ role: 'tool', content: chunk, toolCallId: id, name: 'crm__export' })
  }
  return request
}

// R3-1 (#731): the non-image request cap is 8 MiB. Customer workloads reached
// the former 1 MiB with data, and 8 MiB carries a 1M-token window as escaped
// JSON. The two byte-bound tests above derive their payload from LIMITS, so
// they keep pinning the exact boundary at the new value.
test('T-R3-1a maxRequestBodyBytes is 8 MiB', () => {
  assert.equal(contract.LIMITS.maxRequestBodyBytes, 8 * 1024 * 1024)
})

test('T-R3-1b a 4 MiB conversation of tool results is accepted', () => {
  const request = dataHeavyConversation(4 * 1024 * 1024)
  assert.ok(Buffer.byteLength(JSON.stringify(request), 'utf8') >= 4 * 1024 * 1024)
  const parsed = contract.parseCodexCompletionRequestV1(request)
  assert.equal(parsed.ok, true, parsed.message)
})

test('T-E2 the element bound reports itself distinctly from the byte bound', () => {
  // Before #731 two different guards refused with the identical sentence: the
  // element count inside `checkStructure` and the real byte measurement that
  // the two tests above pin. A user reporting `request exceeds
  // maxRequestBodyBytes` therefore could not say which one fired. Compaction is the remedy either way;
  // the distinct wording buys diagnosis, not a different fix (#731).
  //
  // The shape fits the byte bound; only the element count refuses it.
  const refused = contract.parseCodexCompletionRequestV1({
    ...BASE,
    messages: new Array(contract.LIMITS.maxRequestElements + 1).fill(0),
  })
  assert.deepEqual(refused, {
    ok: false,
    code: 'limit',
    kind: 'size',
    message: 'request exceeds maxRequestElements',
  })
})

test('validates the last definition beyond the former count boundary', () => {
  for (const invalid of [
    { name: 'invalid\u0000name' },
    { parameters: { value: Infinity } },
    { headers: {} },
  ]) {
    const tools = catalog(250)
    tools[249] = { ...tools[249], ...invalid }
    const parsed = contract.parseCodexCompletionRequestV1({ ...BASE, tools })
    assert.equal(parsed.ok, false)
    assert.match(parsed.message, /tools\[249\]/)
  }
})

function withCanonicalName(name) {
  return {
    ...BASE,
    tools: [{ name, description: 'Read a record', parameters: { type: 'object' } }],
    messages: [
      { role: 'assistant', content: '', toolCalls: [{ id: 'call-1', name, arguments: {} }] },
      { role: 'tool', content: 'ok', toolCallId: 'call-1', name },
    ],
  }
}

test('preserves opaque canonical names in definitions and assistant/tool history', () => {
  for (const name of ['read record', '工具@café', 'x'.repeat(129)]) {
    const request = withCanonicalName(name)
    const parsed = contract.parseCodexCompletionRequestV1(request)
    assert.equal(parsed.ok, true, parsed.message)
    assert.deepEqual(parsed.value, request)
    assert.equal(
      contract.hashCodexCompletionRequestV1(parsed.value),
      crypto.createHash('sha256').update(contract.stableStringify(request)).digest('hex')
    )
  }
})

test('rejects empty and control-bearing names at every canonical name location', () => {
  for (const name of ['', 'a\u0000b', 'a\nb', 'a\u007fb', 'a\u0085b', 'a\ud800b']) {
    for (const location of ['definition', 'assistant', 'result']) {
      const request = withCanonicalName('valid')
      if (location === 'definition') request.tools[0].name = name
      if (location === 'assistant') request.messages[0].toolCalls[0].name = name
      if (location === 'result') request.messages[1].name = name
      assert.equal(contract.parseCodexCompletionRequestV1(request).ok, false, location)
    }
  }
})

test('opaque tool name support retains strict request and call identifiers', () => {
  for (const value of ['read record', '工具@café', 'x'.repeat(129)]) {
    for (const location of ['requestId', 'idempotencyKey', 'callId', 'toolCallId']) {
      const request = withCanonicalName(value)
      if (location === 'callId') request.messages[0].toolCalls[0].id = value
      else if (location === 'toolCallId') request.messages[1].toolCallId = value
      else request[location] = value
      assert.equal(contract.parseCodexCompletionRequestV1(request).ok, false, location)
    }
  }
})

test('opaque canonical names remain bounded by serialized UTF-8 request bytes', () => {
  const request = {
    ...BASE,
    tools: [{ name: '工具', description: 'Read a record', parameters: {} }],
  }
  request.tools[0].name += 'x'.repeat(
    contract.LIMITS.maxRequestBodyBytes - Buffer.byteLength(JSON.stringify(request))
  )
  assert.equal(contract.parseCodexCompletionRequestV1(request).ok, true)
  request.tools[0].name += 'é'
  assert.deepEqual(contract.parseCodexCompletionRequestV1(request), {
    ok: false,
    code: 'limit',
    kind: 'size',
    message: 'request exceeds maxRequestBodyBytes',
  })
})

// --- V2 (codex-completion-request.v2) -------------------------------------

const V2_REQUEST_KEYS = { schemaVersion: contract.SCHEMA_VERSION_V2 }
const IMAGE_DATA = {
  png: VISUAL_FIXTURE.png.messages[0].contentParts.find(part => part.type === 'image').data,
  jpeg: VISUAL_FIXTURE.jpeg.messages[0].contentParts.find(part => part.type === 'image').data,
}
const MAX_ENCODED_IMAGE_CHARS = 4 * Math.ceil(contract.VISUAL_LIMITS.maxImageBytes / 3)

/**
 * Fixture image parts carry `dataRef` (resolved from visual-requests.json) so
 * the frozen hash corpus stays readable, and `mutate` for documented
 * truncations. Resolution returns a deep copy: a loaded fixture is never
 * mutated in place.
 */
function resolveFixtureImages(value) {
  if (Array.isArray(value)) return value.map(resolveFixtureImages)
  if (value && typeof value === 'object') {
    if (typeof value.dataRef === 'string') {
      const source = IMAGE_DATA[value.dataRef]
      assert.ok(source, `unknown image ref ${value.dataRef}`)
      const bytes = Buffer.from(source, 'base64')
      let data = source
      if (value.mutate === 'strip-eoi')
        data = bytes.subarray(0, bytes.length - 2).toString('base64')
      else if (value.mutate === 'truncate-after-ihdr')
        data = bytes.subarray(0, 33).toString('base64')
      else assert.equal(value.mutate, undefined, `unknown mutate ${value.mutate}`)
      const clone = { ...value, data }
      delete clone.dataRef
      delete clone.mutate
      return clone
    }
    const out = {}
    for (const [key, inner] of Object.entries(value)) out[key] = resolveFixtureImages(inner)
    return out
  }
  return value
}

function pngChunks(bytes) {
  const chunks = []
  let pos = 8
  while (pos < bytes.length) {
    const length = bytes.readUInt32BE(pos)
    chunks.push({
      type: bytes.toString('latin1', pos + 4, pos + 8),
      data: bytes.subarray(pos + 8, pos + 8 + length),
      crc: bytes.readUInt32BE(pos + 8 + length),
      crcInput: bytes.subarray(pos + 4, pos + 8 + length),
    })
    pos += 12 + length
  }
  return chunks
}

const MIB = 1024 * 1024
// The per-image ceiling this suite replaced. Kept as a literal so the tests
// prove the raise rather than restating the current constant.
const FORMER_IMAGE_CEILING = 524288

function imagePart(data, mimeType = 'image/png') {
  return {
    type: 'image',
    mimeType,
    data,
    source: { kind: 'tool', attachmentId: 'att_1700000000001_ff00aa11', toolCallId: 'call_abc123' },
  }
}

function v2WithMessages(messages) {
  return { ...BASE, ...V2_REQUEST_KEYS, messages }
}

function v2WithParts(parts, content = '') {
  return v2WithMessages([{ role: 'user', content, contentParts: parts }])
}

function v2TextRequest(content) {
  return v2WithMessages([{ role: 'user', content }])
}

test('v2 fixture corpus: valid cases match frozen digests and distinct payloads differ', () => {
  for (const fixture of FIXTURE_V2.cases) {
    const request = resolveFixtureImages(fixture.request)
    const parsed = contract.parseCodexCompletionRequest(request)
    assert.equal(parsed.ok, true, fixture.name)
    const direct = contract.parseCodexCompletionRequestV2(request)
    assert.equal(direct.ok, true, fixture.name)
    assert.deepEqual(parsed, direct, `${fixture.name} dispatcher parity`)
    const digest = contract.hashCodexCompletionRequest(parsed.value)
    assert.equal(digest, fixture.sha256, fixture.name)
    assert.equal(
      contract.hashCodexCompletionRequest(direct.value),
      digest,
      `${fixture.name} hash parity`
    )
    if (fixture.distinctRequest) {
      const other = contract.parseCodexCompletionRequest(
        resolveFixtureImages(fixture.distinctRequest)
      )
      assert.equal(other.ok, true, `${fixture.name} distinct`)
      assert.notEqual(contract.hashCodexCompletionRequest(other.value), digest, fixture.name)
    }
  }
})

test('v2 fixture corpus: rejected payloads fail closed with the frozen code and message', () => {
  for (const fixture of FIXTURE_V2.rejects) {
    const parsed = contract.parseCodexCompletionRequest(resolveFixtureImages(fixture.request))
    assert.equal(parsed.ok, false, fixture.name)
    assert.equal(parsed.code, fixture.reason, fixture.name)
    assert.equal(parsed.message, fixture.message, fixture.name)
  }
})

test('v2 visual fixtures: inline png/jpeg requests parse and pin the exact octets', () => {
  for (const key of ['png', 'jpeg', 'pngImageOnly']) {
    const request = VISUAL_FIXTURE[key]
    assert.equal(request.schemaVersion, contract.SCHEMA_VERSION_V2, key)
    const imageParts = request.messages[0].contentParts.filter(part => part.type === 'image')
    assert.equal(imageParts.length, 1, key)
    const bytes = Buffer.from(imageParts[0].data, 'base64')
    const pinned = VISUAL_FIXTURE.imageSha256[imageParts[0].mimeType.replace('image/', '')]
    assert.equal(crypto.createHash('sha256').update(bytes).digest('hex'), pinned, key)
    const parsed = contract.parseCodexCompletionRequest(request)
    assert.equal(parsed.ok, true, `${key}: ${parsed.message}`)
    assert.deepEqual(
      parsed.value.messages[0].contentParts,
      request.messages[0].contentParts,
      `${key} projection`
    )
  }

  const png = Buffer.from(IMAGE_DATA.png, 'base64')
  assert.deepEqual(
    [png.readUInt32BE(16), png.readUInt32BE(20)],
    [VISUAL_FIXTURE.expectedDimensions.png.width, VISUAL_FIXTURE.expectedDimensions.png.height]
  )
  const jpeg = Buffer.from(IMAGE_DATA.jpeg, 'base64')
  assert.deepEqual([jpeg[0], jpeg[1]], [0xff, 0xd8])
  assert.deepEqual([jpeg[jpeg.length - 2], jpeg[jpeg.length - 1]], [0xff, 0xd9])
  assert.ok(jpeg.includes(Buffer.from([0xff, 0xda])), 'jpeg carries a start-of-scan segment')
})

test('v2 fixture png is a real image: real CRCs and an inflatable scanline stream', () => {
  const bytes = Buffer.from(IMAGE_DATA.png, 'base64')
  const chunks = pngChunks(bytes)
  assert.deepEqual(
    chunks.map(chunk => chunk.type),
    ['IHDR', 'IDAT', 'IEND']
  )
  for (const chunk of chunks) {
    assert.equal(chunk.crc, zlib.crc32(chunk.crcInput) >>> 0, chunk.type)
  }
  const { width, height } = VISUAL_FIXTURE.expectedDimensions.png
  const raw = zlib.inflateSync(chunks[1].data)
  assert.equal(raw.length, height * (1 + width * 3))
  for (let row = 0; row < height; row++) {
    assert.equal(raw[row * (1 + width * 3)], 0, `scanline ${row} filter byte`)
  }
})

test('visualPayload: marker-fill and IHDR-length edges return exact verdicts', () => {
  const u32 = value => [(value >>> 24) & 255, (value >>> 16) & 255, (value >>> 8) & 255, value & 255]
  // CRCs are zero because this corpus tests container structure, not pixel decoding.
  const chunk = (type, data = []) => [...u32(data.length), ...Buffer.from(type, 'latin1'), ...data, 0, 0, 0, 0]
  const SIG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
  const SOI = [0xff, 0xd8]
  const EOI = [0xff, 0xd9]
  const sof = [
    0xff, 0xc0, 0x00, 0x11, 0x08, 0, 6, 0, 8,
    0x03, 1, 0x11, 0, 2, 0x11, 0, 3, 0x11, 0,
  ]
  const sos = [0xff, 0xda, 0x00, 0x0c, 0x03, 1, 0, 2, 0x11, 3, 0x11, 0x00, 0x3f, 0x00]
  const jpegWithPrefix = prefix => [...SOI, ...prefix, ...sof, ...sos, 0x12, 0x34, ...EOI]
  const invalid = message => ({ ok: false, code: 'invalid', message })
  const accepted = (bytes, width, height) => ({ ok: true, value: { bytes, width, height } })
  const jpegLength = jpegWithPrefix([]).length
  const corpus = [
    ['legal FF FF fill before a marker', 'image/jpeg', jpegWithPrefix([0xff, 0xff]), accepted(jpegLength + 2, 8, 6)],
    ['standalone temporary marker', 'image/jpeg', jpegWithPrefix([0xff, 0x01]), accepted(jpegLength + 2, 8, 6)],
    ['standalone restart marker 7', 'image/jpeg', jpegWithPrefix([0xff, 0xd7]), accepted(jpegLength + 2, 8, 6)],
    [
      'malformed 14-byte IHDR',
      'image/png',
      [
        ...SIG,
        ...chunk('IHDR', [...u32(3), ...u32(2), 8, 6, 0, 0, 0, 0]),
        ...chunk('IDAT', [0x78, 0x9c]),
        ...chunk('IEND'),
      ],
      invalid('PNG first chunk must be a 13-byte IHDR'),
    ],
    // Eight or more bytes with one wrong signature byte and otherwise valid
    // chunks: the signature check alone must refuse it.
    [
      'wrong last PNG signature byte',
      'image/png',
      [
        ...SIG.slice(0, 7),
        0x0b,
        ...chunk('IHDR', [...u32(3), ...u32(2), 8, 6, 0, 0, 0]),
        ...chunk('IDAT', [0x78, 0x9c]),
        ...chunk('IEND'),
      ],
      invalid('PNG signature is missing'),
    ],
    // SOF length boundary: 7 is one byte short of length+P+Y+X+Nf, 8 is the minimum.
    [
      '7-byte JPEG frame header',
      'image/jpeg',
      [...SOI, 0xff, 0xc0, 0x00, 0x07, 0x08, 0x00, 0x06, 0x00, 0x08, ...sos, 0x12, 0x34, ...EOI],
      invalid('JPEG frame header is truncated'),
    ],
    [
      '8-byte JPEG frame header is the minimum accepted',
      'image/jpeg',
      [...SOI, 0xff, 0xc0, 0x00, 0x08, 0x08, 0x00, 0x06, 0x00, 0x08, 0x01, ...sos, 0x12, 0x34, ...EOI],
      accepted(2 + 10 + 14 + 2 + 2, 8, 6),
    ],
  ]
  for (const [name, mimeType, bytes, expected] of corpus) {
    assert.deepEqual(
      visualPayload.inspectVisualImage({ mimeType, data: Buffer.from(bytes).toString('base64') }),
      expected,
      name
    )
  }
})

test('dispatcher: v1 rejects contentParts, unknown versions fail closed, one hash serves both', () => {
  const v1WithParts = { ...VISUAL_FIXTURE.png, schemaVersion: contract.SCHEMA_VERSION }
  const rejected = contract.parseCodexCompletionRequestV1(v1WithParts)
  assert.equal(rejected.ok, false)
  assert.equal(rejected.code, 'unknown-field')
  assert.match(rejected.message, /contentParts/)
  assert.equal(contract.parseCodexCompletionRequest(v1WithParts).ok, false)

  for (const schemaVersion of ['codex-completion-request.v3', undefined, null, 2]) {
    const parsed = contract.parseCodexCompletionRequest({ ...BASE, schemaVersion })
    assert.equal(parsed.ok, false, String(schemaVersion))
    assert.equal(parsed.code, 'invalid', String(schemaVersion))
  }
  assert.equal(contract.parseCodexCompletionRequest('not an object').ok, false)

  const v1 = contract.parseCodexCompletionRequest(BASE)
  const v2 = contract.parseCodexCompletionRequest(v2TextRequest('hello'))
  assert.equal(v1.ok, true)
  assert.equal(v2.ok, true)
  assert.equal(
    contract.hashCodexCompletionRequest(v1.value),
    contract.hashCodexCompletionRequestV1(v1.value)
  )
  const withoutVersion = ({ schemaVersion, ...rest }) => rest
  assert.deepEqual(
    withoutVersion(v2.value),
    withoutVersion(v1.value),
    'text-only v2 keeps v1 semantics'
  )
  assert.notEqual(
    contract.hashCodexCompletionRequest(v2.value),
    contract.hashCodexCompletionRequest(v1.value)
  )
})

test('dispatcher: v2 keeps every v1 root check instead of bypassing it', () => {
  for (const fixture of FIXTURE.rejects) {
    const asV1 = contract.parseCodexCompletionRequest(fixture.request)
    const asV2 = contract.parseCodexCompletionRequest({
      ...fixture.request,
      schemaVersion: contract.SCHEMA_VERSION_V2,
    })
    assert.equal(asV1.ok, false, fixture.name)
    assert.equal(asV2.ok, false, `${fixture.name} v2`)
    assert.equal(asV2.code, asV1.code, `${fixture.name} code`)
  }

  const roots = [
    { name: 'requestId', patch: { requestId: 'bad id' } },
    { name: 'idempotencyKey', patch: { idempotencyKey: 'é' } },
    { name: 'provider', patch: { provider: 'openai-api' } },
    { name: 'model', patch: { model: 'bad model' } },
    { name: 'deadline-low', patch: { deadlineMs: 0 }, code: 'limit' },
    {
      name: 'deadline-high',
      patch: { deadlineMs: contract.LIMITS.maxDeadlineMs + 1 },
      code: 'limit',
    },
    { name: 'deadline-fraction', patch: { deadlineMs: 1.5 }, code: 'non-finite' },
    {
      name: 'deadline-nonfinite',
      patch: { deadlineMs: Number.POSITIVE_INFINITY },
      code: 'non-finite',
    },
    { name: 'generation-unknown', patch: { generation: { topK: 5 } } },
    { name: 'generation-temperature', patch: { generation: { temperature: 3 } } },
    { name: 'transport-hints-unknown', patch: { transportHints: { cacheKey: 'x' } } },
    { name: 'messages-empty', patch: { messages: [] } },
    { name: 'message-role', patch: { messages: [{ role: 'human', content: 'x' }] } },
    { name: 'message-content-type', patch: { messages: [{ role: 'user', content: 5 }] } },
    {
      name: 'message-tool-calls-on-user',
      patch: {
        messages: [
          { role: 'user', content: 'x', toolCalls: [{ id: 'a', name: 'b', arguments: {} }] },
        ],
      },
    },
    { name: 'tool-description', patch: { tools: [{ name: 'a', description: 1, parameters: {} }] } },
    {
      name: 'tool-name-control',
      patch: { tools: [{ name: 'a\u0000b', description: 'x', parameters: {} }] },
    },
    {
      name: 'text-part-text-type',
      patch: {
        messages: [{ role: 'user', content: 'x', contentParts: [{ type: 'text', text: 5 }] }],
      },
    },
  ]
  for (const entry of roots) {
    const parsed = contract.parseCodexCompletionRequest({
      ...BASE,
      ...V2_REQUEST_KEYS,
      ...entry.patch,
    })
    assert.equal(parsed.ok, false, entry.name)
    if (entry.code) assert.equal(parsed.code, entry.code, entry.name)
  }
})

test('v2 projection preserves part order, source identity and the text projection verbatim', () => {
  const multi = resolveFixtureImages(
    FIXTURE_V2.cases.find(item => item.name === 'multi-image-order-significant').request
  )
  const parsed = contract.parseCodexCompletionRequest(multi)
  assert.equal(parsed.ok, true)
  assert.equal(Object.isFrozen(parsed.value), true)
  assert.deepEqual(parsed.value.messages[0].contentParts, multi.messages[0].contentParts)
  assert.deepEqual(
    parsed.value.messages[0].contentParts.map(part => part.type),
    ['text', 'image', 'image']
  )

  const compacted = resolveFixtureImages(
    FIXTURE_V2.cases.find(item => item.name === 'text-only-parts-after-compaction').request
  )
  const parsedCompacted = contract.parseCodexCompletionRequest(compacted)
  assert.equal(parsedCompacted.ok, true)
  const parts = parsedCompacted.value.messages[0].contentParts
  assert.ok(
    parts.every(part => part.type === 'text'),
    'text-only parts survive without an image'
  )
  assert.equal(parsedCompacted.value.messages[0].content, parts.map(part => part.text).join('\n'))

  const imageOnly = contract.parseCodexCompletionRequest(VISUAL_FIXTURE.pngImageOnly)
  assert.equal(imageOnly.ok, true)
  assert.equal(imageOnly.value.messages[0].content, '', 'an image-only message has empty text')
})

test('v2 limits: image count, encoder bound, per-image bytes, total bytes, dimensions and pixels', () => {
  const png = IMAGE_DATA.png
  const twenty = Array.from({ length: contract.VISUAL_LIMITS.maxImages }, () => imagePart(png))
  assert.equal(
    contract.parseCodexCompletionRequest(v2WithParts(twenty)).ok,
    true,
    'twenty images fit'
  )
  const twentyOne = contract.parseCodexCompletionRequest(v2WithParts([...twenty, imagePart(png)]))
  assert.equal(twentyOne.ok, false)
  assert.equal(twentyOne.code, 'limit')
  assert.match(twentyOne.message, /20 images/)

  const encoded = contract.parseCodexCompletionRequest(
    v2WithParts([imagePart('A'.repeat(MAX_ENCODED_IMAGE_CHARS + 4))])
  )
  assert.equal(encoded.code, 'limit', 'encoded length is bounded before decoding')
  const decoded = contract.parseCodexCompletionRequest(
    v2WithParts([
      imagePart(Buffer.alloc(contract.VISUAL_LIMITS.maxImageBytes + 1).toString('base64')),
    ])
  )
  assert.equal(decoded.code, 'limit')

  // Above the ceiling this suite replaced, in both accepted containers.
  const pngOverFormerCeiling = declaredHeaderPngOfSize(FORMER_IMAGE_CEILING + 1)
  assert.equal(pngOverFormerCeiling.length, FORMER_IMAGE_CEILING + 1)
  const acceptedPng = contract.parseCodexCompletionRequest(
    v2WithParts([imagePart(pngOverFormerCeiling.toString('base64'))])
  )
  assert.equal(acceptedPng.ok, true, acceptedPng.message)
  const acceptedJpeg = contract.parseCodexCompletionRequest(
    v2WithParts([imagePart(jpegOfSize(FORMER_IMAGE_CEILING + 1).toString('base64'), 'image/jpeg')])
  )
  assert.equal(acceptedJpeg.ok, true, acceptedJpeg.message)
  const acceptedFiveMiBJpeg = contract.parseCodexCompletionRequest(
    v2WithParts([imagePart(jpegOfSize(5 * MIB).toString('base64'), 'image/jpeg')])
  )
  assert.equal(acceptedFiveMiBJpeg.ok, true, acceptedFiveMiBJpeg.message)

  // 3 MiB, and exactly the per-image ceiling, are inside the budget.
  const acceptedThreeMiB = contract.parseCodexCompletionRequest(
    v2WithParts([imagePart(declaredHeaderPngOfSize(3 * MIB).toString('base64'))])
  )
  assert.equal(acceptedThreeMiB.ok, true, acceptedThreeMiB.message)
  const acceptedCeiling = contract.parseCodexCompletionRequest(
    v2WithParts([
      imagePart(declaredHeaderPngOfSize(contract.VISUAL_LIMITS.maxImageBytes).toString('base64')),
    ])
  )
  assert.equal(acceptedCeiling.ok, true, acceptedCeiling.message)

  // One byte over the per-image ceiling, as a container that is otherwise valid.
  const overCeiling = contract.parseCodexCompletionRequest(
    v2WithParts([
      imagePart(
        declaredHeaderPngOfSize(contract.VISUAL_LIMITS.maxImageBytes + 1).toString('base64')
      ),
    ])
  )
  assert.equal(overCeiling.ok, false)
  assert.equal(overCeiling.code, 'limit')
  assert.match(overCeiling.message, /image exceeds/)
  assert.match(overCeiling.message, new RegExp(String(contract.VISUAL_LIMITS.maxImageBytes)))

  // Exceptional >10 MiB is allowed; the hard per-image ceiling is 16 MiB.
  const twelveMiB = contract.parseCodexCompletionRequest(
    v2WithParts([imagePart(declaredHeaderPngOfSize(12 * MIB).toString('base64'))])
  )
  assert.equal(twelveMiB.ok, true, twelveMiB.message)

  // A larger individual image does not increase the aggregate resource budget.
  const tenMiB = declaredHeaderPngOfSize(10 * MIB).toString('base64')
  const fiveMiB = declaredHeaderPngOfSize(5 * MIB).toString('base64')
  const combined = contract.parseCodexCompletionRequest(
    v2WithParts([imagePart(tenMiB), imagePart(fiveMiB)])
  )
  assert.equal(combined.ok, true, combined.message)
  const combinedWithJpeg = contract.parseCodexCompletionRequest(
    v2WithParts([imagePart(tenMiB), imagePart(jpegOfSize(5 * MIB).toString('base64'), 'image/jpeg')])
  )
  assert.equal(combinedWithJpeg.ok, true, combinedWithJpeg.message)
  const atAggregate = contract.parseCodexCompletionRequest(
    v2WithParts([imagePart(tenMiB), imagePart(declaredHeaderPngOfSize(6 * MIB).toString('base64'))])
  )
  assert.equal(atAggregate.ok, true, atAggregate.message)
  const overAggregate = contract.parseCodexCompletionRequest(
    v2WithParts([
      imagePart(tenMiB),
      imagePart(declaredHeaderPngOfSize(6 * MIB + 1).toString('base64')),
    ])
  )
  assert.equal(overAggregate.ok, false)
  assert.equal(overAggregate.code, 'limit')
  assert.match(overAggregate.message, /total image bytes/)

  const atDimension = contract.parseCodexCompletionRequest(
    v2WithParts([
      imagePart(realPng(contract.VISUAL_LIMITS.maxImageDimension, 1, 9).toString('base64')),
    ])
  )
  assert.equal(atDimension.ok, true, atDimension.message)
  const overDimension = contract.parseCodexCompletionRequest(
    v2WithParts([
      imagePart(realPng(contract.VISUAL_LIMITS.maxImageDimension + 1, 1, 11).toString('base64')),
    ])
  )
  assert.equal(overDimension.code, 'limit')
  assert.equal(overDimension.kind, 'size')
  assert.match(overDimension.message, /dimension/)

  // Phone-sized frames are a Codex pixel problem, not a byte problem.
  const phoneShape = contract.parseCodexCompletionRequest(
    v2WithParts([imagePart(declaredHeaderPng(8064, 6048).toString('base64'))])
  )
  assert.equal(phoneShape.ok, false)
  assert.equal(phoneShape.code, 'limit')
  assert.equal(phoneShape.kind, 'size')
  assert.match(phoneShape.message, /dimension/)

  // 2048×2048 is both the dimension and the pixel ceiling.
  assert.equal(
    contract.VISUAL_LIMITS.maxImageDimension * contract.VISUAL_LIMITS.maxImageDimension,
    contract.VISUAL_LIMITS.maxImagePixels
  )
  const atPixels = contract.parseCodexCompletionRequest(
    v2WithParts([
      imagePart(
        declaredHeaderPng(
          contract.VISUAL_LIMITS.maxImageDimension,
          contract.VISUAL_LIMITS.maxImageDimension
        ).toString('base64')
      ),
    ])
  )
  assert.equal(atPixels.ok, true, atPixels.message)

  const wrongMime = contract.parseCodexCompletionRequest(
    v2WithParts([imagePart(png, 'image/jpeg')])
  )
  assert.equal(wrongMime.ok, false, 'mime and container signature must agree')
  const jpegAsPng = contract.parseCodexCompletionRequest(
    v2WithParts([imagePart(IMAGE_DATA.jpeg, 'image/png')])
  )
  assert.equal(jpegAsPng.ok, false)
})

test('v2 visual budgets are request-scoped across messages: twenty small images fit, twenty-one do not', () => {
  const png = IMAGE_DATA.png
  const userWithImages = count => ({
    role: 'user',
    content: '',
    contentParts: Array.from({ length: count }, () => imagePart(png)),
  })

  // 11 + 10 images: every message is inside maxImages on its own, the request is not.
  const splitOverCap = contract.parseCodexCompletionRequest(
    v2WithMessages([userWithImages(11), userWithImages(10)])
  )
  assert.equal(splitOverCap.ok, false)
  assert.equal(splitOverCap.code, 'limit')
  assert.match(splitOverCap.message, /20 images/)

  // Boundary: exactly maxImages spread over twenty messages is accepted.
  const oneEach = contract.parseCodexCompletionRequest(
    v2WithMessages(Array.from({ length: contract.VISUAL_LIMITS.maxImages }, () => userWithImages(1)))
  )
  assert.equal(oneEach.ok, true, oneEach.message)

  // Three 5 MiB images across messages fill the unchanged aggregate budget.
  const atCeiling = declaredHeaderPngOfSize(5 * MIB).toString('base64')
  const messageWith = encoded => ({
    role: 'user',
    content: '',
    contentParts: [imagePart(encoded)],
  })
  const oneEachAtCeiling = contract.parseCodexCompletionRequest(
    v2WithMessages([messageWith(atCeiling), messageWith(atCeiling), messageWith(atCeiling)])
  )
  assert.equal(oneEachAtCeiling.ok, true, oneEachAtCeiling.message)
  // Three ceiling images are the exact aggregate boundary, and the encoded body
  // is larger than the V1 ceiling — this is the request that needs the V2 budget.
  const ceilingBody = Buffer.byteLength(
    JSON.stringify(
      v2WithMessages([messageWith(atCeiling), messageWith(atCeiling), messageWith(atCeiling)])
    ),
    'utf8'
  )
  assert.ok(ceilingBody > contract.LIMITS.maxRequestBodyBytes)
  assert.ok(ceilingBody <= contract.LIMITS.maxVisualRequestBodyBytes)

  // A fourth ceiling image is refused before the count gate is reached: four
  // 5 MiB payloads encode to more than the 24 MiB body ceiling. The count rule
  // is exercised with small images above; this asserts which gate fires first
  // for maximum-size payloads.
  const fourMessages = contract.parseCodexCompletionRequest(
    v2WithMessages([
      messageWith(atCeiling),
      messageWith(atCeiling),
      messageWith(atCeiling),
      messageWith(atCeiling),
    ])
  )
  assert.equal(fourMessages.ok, false)
  assert.equal(fourMessages.code, 'limit')
  assert.equal(fourMessages.message, 'request exceeds maxVisualRequestBodyBytes')
})

/**
 * The request with every image payload replaced by an empty string, and the
 * text parts blanked where they repeat `content` — the non-image share the V2
 * budget is defined on. Used to find an exact boundary; the assertions below
 * always check the contract's verdict, not this helper.
 */
function nonImageBytes(request) {
  return Buffer.byteLength(
    JSON.stringify({
      ...request,
      messages: request.messages.map(message => {
        if (!Array.isArray(message.contentParts)) return message
        const texts = message.contentParts.filter(part => part.type === 'text').map(part => part.text)
        const repeatsContent = texts.join('\n') === message.content
        return {
          ...message,
          contentParts: message.contentParts.map(part => {
            if (part.type === 'image') return { ...part, data: '' }
            if (repeatsContent && part.type === 'text') return { ...part, text: '' }
            return part
          }),
        }
      }),
    }),
    'utf8'
  )
}

test('requestBodyLimitBytes: V2 declares 24 MiB; every other body keeps the 8 MiB ceiling', () => {
  assert.equal(contract.LIMITS.maxRequestBodyBytes, 8388608)
  assert.equal(contract.LIMITS.maxVisualRequestBodyBytes, 25165824)
  assert.equal(contract.VISUAL_LIMITS.maxImages, 20)
  assert.equal(contract.VISUAL_LIMITS.typicalImageBytes, 5 * MIB)
  assert.equal(contract.VISUAL_LIMITS.typicalTotalImageBytes, 9 * MIB)
  assert.equal(contract.VISUAL_LIMITS.typicalEnvelopeBytes, 14 * MIB)
  assert.equal(contract.VISUAL_LIMITS.maxImageBytes, 16 * MIB)
  assert.equal(contract.VISUAL_LIMITS.maxTotalImageBytes, 16 * MIB)
  assert.equal(contract.VISUAL_LIMITS.maxImageDimension, 2048)
  assert.equal(contract.VISUAL_LIMITS.maxImagePixels, 2048 * 2048)

  for (const v2 of [VISUAL_FIXTURE.png, VISUAL_FIXTURE.jpeg, VISUAL_FIXTURE.pngImageOnly]) {
    assert.equal(v2.schemaVersion, contract.SCHEMA_VERSION_V2)
    assert.equal(contract.requestBodyLimitBytes(v2), 25165824)
  }
  // A declaration is not a payload: unknown, missing and non-object bodies keep
  // the smaller ceiling so a caller cannot ask for the larger budget it has not
  // satisfied.
  for (const other of [
    BASE,
    { ...BASE, schemaVersion: 'codex-completion-request.v3' },
    { ...BASE, schemaVersion: undefined },
    {},
    null,
    undefined,
    'x',
    7,
    [],
  ]) {
    assert.equal(contract.requestBodyLimitBytes(other), contract.LIMITS.maxRequestBodyBytes, String(other))
  }
})

test('v2 preserves the non-image budget: text and tools stay on the maxRequestBodyBytes ceiling', () => {
  const { maxRequestBodyBytes, maxVisualRequestBodyBytes } = contract.LIMITS
  const image = imagePart(IMAGE_DATA.png)
  const overflow = 'request exceeds maxRequestBodyBytes outside image data'
  const longText = 'x'.repeat(maxRequestBodyBytes + MIB)

  // Images do not buy text: content-class payload over the non-image cap is
  // refused below the 24 MiB ceiling the same body may use for image data.
  const textHeavy = contract.parseCodexCompletionRequest(
    v2WithParts([image, { type: 'text', text: longText }], longText)
  )
  assert.equal(textHeavy.ok, false)
  assert.equal(textHeavy.code, 'limit')
  assert.equal(textHeavy.message, overflow)

  // A text-only V2 body is not a 24 MiB allowance either.
  assert.deepEqual(contract.parseCodexCompletionRequest(v2TextRequest(longText)), {
    ok: false,
    code: 'limit',
    kind: 'size',
    message: overflow,
  })

  // Tool definitions are on the same caller-controlled budget.
  const toolHeavy = contract.parseCodexCompletionRequest({
    ...v2WithParts([image]),
    tools: [{ name: 'read', description: 'y'.repeat(maxRequestBodyBytes + MIB), parameters: {} }],
  })
  assert.equal(toolHeavy.ok, false)
  assert.equal(toolHeavy.code, 'limit')
  assert.equal(toolHeavy.message, overflow)

  // Exact boundary. The image is blanked out of the measurement, so the largest
  // accepted text still leaves the body far under the V2 ceiling, and one byte
  // more is refused by the non-image rule.
  const withImageAndText = length =>
    v2WithParts([image, { type: 'text', text: 'z'.repeat(length) }], 'z'.repeat(length))
  const base = nonImageBytes(withImageAndText(0))
  const growth = (nonImageBytes(withImageAndText(10)) - base) / 10
  assert.equal(growth, 1, 'the text part repeats content and is counted once')
  const exactLength = Math.floor((maxRequestBodyBytes - base) / growth)
  const boundary = nonImageBytes(withImageAndText(exactLength))
  assert.ok(
    boundary <= maxRequestBodyBytes && boundary > maxRequestBodyBytes - growth,
    `non-image boundary landed at ${boundary}`
  )
  const bodyAtBoundary = Buffer.byteLength(JSON.stringify(withImageAndText(exactLength)), 'utf8')
  assert.ok(
    bodyAtBoundary < maxVisualRequestBodyBytes,
    'the non-image boundary is decided well below the V2 ceiling'
  )
  const atLimit = contract.parseCodexCompletionRequest(withImageAndText(exactLength))
  assert.equal(atLimit.ok, true, atLimit.message)
  const overLimit = contract.parseCodexCompletionRequest(withImageAndText(exactLength + 1))
  assert.equal(overLimit.ok, false)
  assert.equal(overLimit.code, 'limit')
  assert.equal(overLimit.message, overflow)
  assert.ok(
    nonImageBytes(withImageAndText(exactLength + 1)) > maxRequestBodyBytes,
    'the rejection is the non-image budget, not another gate'
  )
})

// Review R3-L3: a V2 user message carries its text twice, in `content` and in
// its text parts, and the parser requires their '\n' join to equal `content`.
// The non-image share counts that text once, as a V1 request would.
function textAndImage(text) {
  return v2WithParts([{ type: 'text', text }, imagePart(IMAGE_DATA.png)], text)
}

const AUTHORIZE_WRAPPER_BYTES =
  Buffer.byteLength(JSON.stringify({ request: null }), 'utf8') - Buffer.byteLength('null', 'utf8')

/** The non-image share of `request` as the contract measures it. */
function nonImageShare(request) {
  return contract.measureNonImageAuthorizeBytes({ request }) - AUTHORIZE_WRAPPER_BYTES
}

/**
 * `request` serialized with image data blanked and, when `blankText`, the text
 * of its text parts blanked too: the two measurements the share can take.
 */
function shadowBytes(request, blankText) {
  return Buffer.byteLength(
    JSON.stringify({
      ...request,
      messages: request.messages.map(message =>
        Array.isArray(message.contentParts)
          ? {
              ...message,
              contentParts: message.contentParts.map(part => {
                if (part?.type === 'image') return { ...part, data: '' }
                if (blankText && part?.type === 'text') return { ...part, text: '' }
                return part
              }),
            }
          : message
      ),
    }),
    'utf8'
  )
}

const TEXT_OVERFLOW = {
  ok: false,
  code: 'limit',
  kind: 'size',
  message: 'request exceeds maxRequestBodyBytes outside image data',
}

const PARTS_MISMATCH = index => ({
  ok: false,
  code: 'invalid',
  message: `messages[${index}].content must equal the text parts joined by '\\n'`,
})

test('R3-L3 the non-image share counts text repeated in content and its parts once', () => {
  const growth = (nonImageShare(textAndImage('z'.repeat(10))) - nonImageShare(textAndImage(''))) / 10
  assert.equal(growth, 1)
  const request = textAndImage('look')
  assert.equal(nonImageShare(request), shadowBytes(request, true))
  assert.ok(nonImageShare(request) < shadowBytes(request, false))
})

test('R3-L3 a 4.5 MiB prompt beside an image is accepted, as the same prompt is in V1', () => {
  const { maxRequestBodyBytes } = contract.LIMITS
  const text = 'x'.repeat(4.5 * MIB)
  const v1 = { ...BASE, messages: [{ role: 'user', content: text }] }
  const v1Parsed = contract.parseCodexCompletionRequest(v1)
  assert.equal(v1Parsed.ok, true, v1Parsed.message)

  const v2 = textAndImage(text)
  assert.ok(shadowBytes(v2, false) > maxRequestBodyBytes, 'counted twice, the prompt is over the budget')
  const parsed = contract.parseCodexCompletionRequest(v2)
  assert.equal(parsed.ok, true, parsed.message)
  assert.equal(parsed.value.messages[0].content, text)
  assert.equal(parsed.value.messages[0].contentParts[0].text, text)

  // The authorize and completion helpers take the same share.
  assert.ok(
    contract.measureNonImageAuthorizeBytes({ request: v2, invocationId: 'invocation-1' }) <=
      maxRequestBodyBytes
  )
  assert.ok(
    contract.measureNonImageCompletionBytes({
      request: v2,
      requestHash: 'a'.repeat(64),
      executionTicket: `header.${'a'.repeat(2048)}.sig`,
    }) <= maxRequestBodyBytes
  )
  // The measurement works on a detached copy.
  assert.equal(v2.messages[0].contentParts[0].text, text)
  assert.equal(v2.messages[0].contentParts[1].data, IMAGE_DATA.png)
})

test('R3-L3 exact boundary: the largest text beside an image is accepted and one byte more is refused', () => {
  const { maxRequestBodyBytes } = contract.LIMITS
  const length = maxRequestBodyBytes - shadowBytes(textAndImage(''), true)
  const atLimit = textAndImage('x'.repeat(length))
  assert.equal(nonImageShare(atLimit), maxRequestBodyBytes)
  assert.ok(shadowBytes(atLimit, false) > maxRequestBodyBytes, 'counted twice, this body was refused')
  const accepted = contract.parseCodexCompletionRequest(atLimit)
  assert.equal(accepted.ok, true, accepted.message)
  const over = textAndImage('x'.repeat(length + 1))
  assert.equal(nonImageShare(over), maxRequestBodyBytes + 1)
  assert.deepEqual(contract.parseCodexCompletionRequest(over), TEXT_OVERFLOW)
})

test('R3-L3 text parts that do not repeat content keep both copies in the share and are refused', () => {
  const text = 'x'.repeat(4.5 * MIB)
  // Same length, one character different: counted twice, over the budget.
  assert.deepEqual(
    contract.parseCodexCompletionRequest(v2WithParts([{ type: 'text', text }, imagePart(IMAGE_DATA.png)], `${text.slice(1)}y`)),
    TEXT_OVERFLOW
  )
  const image = imagePart(IMAGE_DATA.png)
  const mismatches = [
    ['different text', [{ type: 'text', text: 'look' }, image], 'lock'],
    ['swapped parts', [{ type: 'text', text: 'b' }, image, { type: 'text', text: 'a' }], 'a\nb'],
    ['joined without the separator', [{ type: 'text', text: 'a' }, { type: 'text', text: 'b' }, image], 'ab'],
    ['a trailing separator', [{ type: 'text', text: 'a' }, image], 'a\n'],
    ['content without text parts', [image], 'look'],
    ['text parts with empty content', [{ type: 'text', text: 'look' }, image], ''],
  ]
  for (const [label, parts, content] of mismatches) {
    const request = v2WithParts(parts, content)
    assert.equal(nonImageShare(request), shadowBytes(request, false), label)
    assert.deepEqual(contract.parseCodexCompletionRequest(request), PARTS_MISMATCH(0), label)
  }
  // Malformed messages are measured as sent, never throw, and the parser
  // refuses them.
  const malformed = [
    ['a non-string text part', [{ type: 'text', text: 7 }, image], '7'],
    ['a non-object part beside a matching text part', ['junk', { type: 'text', text: 'look' }, image], 'look'],
    ['a non-string content', [{ type: 'text', text: 'look' }, image], 7],
  ]
  for (const [label, parts, content] of malformed) {
    const request = v2WithParts(parts, content)
    assert.equal(nonImageShare(request), shadowBytes(request, false), label)
    const parsed = contract.parseCodexCompletionRequest(request)
    assert.equal(parsed.ok, false, label)
    assert.equal(parsed.code, 'invalid', label)
  }
})

test('R3-L3 multi-part and multi-message requests count each matching message once', () => {
  const { maxRequestBodyBytes } = contract.LIMITS
  const multiPart = v2WithParts(
    [
      { type: 'text', text: 'a' },
      imagePart(IMAGE_DATA.png),
      { type: 'text', text: 'b' },
      imagePart(IMAGE_DATA.jpeg, 'image/jpeg'),
      { type: 'text', text: '' },
    ],
    'a\nb\n'
  )
  assert.equal(nonImageShare(multiPart), shadowBytes(multiPart, true))
  const multiPartParsed = contract.parseCodexCompletionRequest(multiPart)
  assert.equal(multiPartParsed.ok, true, multiPartParsed.message)

  const turn = content => ({
    role: 'user',
    content,
    contentParts: [{ type: 'text', text: content }, imagePart(IMAGE_DATA.png)],
  })
  const text = 'x'.repeat(3 * MIB)
  const twoTurns = v2WithMessages([turn(text), { role: 'assistant', content: 'ok' }, turn(text)])
  assert.ok(shadowBytes(twoTurns, false) > maxRequestBodyBytes, 'counted twice, the history is over the budget')
  assert.equal(nonImageShare(twoTurns), shadowBytes(twoTurns, true))
  const twoTurnsParsed = contract.parseCodexCompletionRequest(twoTurns)
  assert.equal(twoTurnsParsed.ok, true, twoTurnsParsed.message)

  // Each message is judged on its own: the mismatched turn keeps its text.
  const mismatched = { role: 'user', content: 'lock', contentParts: [{ type: 'text', text: 'look' }, imagePart(IMAGE_DATA.png)] }
  const mixed = v2WithMessages([turn('look'), mismatched])
  const expected = {
    ...mixed,
    messages: [
      { ...turn('look'), contentParts: [{ type: 'text', text: '' }, imagePart('')] },
      { ...mismatched, contentParts: [{ type: 'text', text: 'look' }, imagePart('')] },
    ],
  }
  assert.equal(nonImageShare(mixed), Buffer.byteLength(JSON.stringify(expected), 'utf8'))
  assert.deepEqual(contract.parseCodexCompletionRequest(mixed), PARTS_MISMATCH(1))
})

test('v2 total budget: the raw body is capped at 24 MiB and the three budgets stay consistent', () => {
  const { maxVisualRequestBodyBytes, maxRequestBodyBytes } = contract.LIMITS
  // The V2 ceiling covers the whole non-image share plus its envelope, and the
  // largest legal image set (16 MiB decoded, ~21.3 MiB of canonical base64)
  // plus a documented non-image floor. It does not cover both maxima at once
  // (#731 raised the non-image share to 8 MiB); a request carrying both is
  // refused by the whole-body gate. Asserted so a change to any of the image
  // numbers or to either ceiling is caught here.
  const aggregateEncoded = 4 * Math.ceil(contract.VISUAL_LIMITS.maxTotalImageBytes / 3) + 8
  const nonImageFloorBesideMaxImages = 2.5 * 1024 * 1024
  assert.ok(maxRequestBodyBytes + 16 * 1024 < maxVisualRequestBodyBytes)
  assert.ok(maxVisualRequestBodyBytes - aggregateEncoded >= nonImageFloorBesideMaxImages)

  // Over the ceiling is refused by the size gate, before any payload work.
  const oversized = v2WithParts([imagePart('A'.repeat(maxVisualRequestBodyBytes))])
  assert.ok(Buffer.byteLength(JSON.stringify(oversized), 'utf8') > maxVisualRequestBodyBytes)
  const refused = contract.parseCodexCompletionRequest(oversized)
  assert.equal(refused.ok, false)
  assert.equal(refused.code, 'limit')
  assert.equal(refused.message, 'request exceeds maxVisualRequestBodyBytes')

  // The same shape parsed as V1 keeps the V1 ceiling and its V1 message: the
  // larger budget is a property of the version, not of the payload.
  const asV1 = contract.parseCodexCompletionRequestV1({
    ...oversized,
    schemaVersion: contract.SCHEMA_VERSION,
  })
  assert.equal(asV1.ok, false)
  assert.equal(asV1.code, 'limit')
  assert.equal(asV1.message, 'request exceeds maxRequestBodyBytes')
})

test('large real PNG: CRCs and inflatable scanlines at 3 MiB and at 10 MiB', () => {
  const cases = [
    ['3 MiB', 3 * MIB, 512, 512, 21],
    ['10 MiB', 10 * MIB, 1150, 1150, 31],
  ]
  for (const [label, target, width, height, seed] of cases) {
    const png = realPngOfSize(target, width, height, seed)
    assert.equal(png.length, target, label)
    const chunks = pngChunks(png)
    assert.deepEqual(
      chunks.map(chunk => chunk.type),
      ['IHDR', 'IDAT', 'tEXt', 'IEND'],
      label
    )
    for (const chunk of chunks) {
      assert.equal(chunk.crc, zlib.crc32(chunk.crcInput) >>> 0, `${label} ${chunk.type} crc`)
    }
    const raw = zlib.inflateSync(chunks[1].data)
    assert.equal(raw.length, height * (1 + width * 3), label)
    const parsed = contract.parseCodexCompletionRequest(
      v2WithParts([imagePart(png.toString('base64'))])
    )
    assert.equal(parsed.ok, true, `${label}: ${parsed.message}`)
  }
})

test('shared pads keep a real fixture JPEG/PNG contract-valid at 5 MiB', () => {
  const jpeg = padJpegToSize(Buffer.from(IMAGE_DATA.jpeg, 'base64'), 5 * MIB)
  const png = padPngToSize(Buffer.from(IMAGE_DATA.png, 'base64'), 5 * MIB)
  assert.equal(jpeg.length, 5 * MIB)
  assert.equal(png.length, 5 * MIB)
  const jpegParsed = contract.parseCodexCompletionRequest(
    v2WithParts([imagePart(jpeg.toString('base64'), 'image/jpeg')])
  )
  const pngParsed = contract.parseCodexCompletionRequest(
    v2WithParts([imagePart(png.toString('base64'))])
  )
  assert.equal(jpegParsed.ok, true, jpegParsed.message)
  assert.equal(pngParsed.ok, true, pngParsed.message)
})

test('buildCodexProxyEnvelope: exact shape, no outer deadline, exact size boundary', () => {
  const ticket = 'header.payload.signature'.repeat(3)
  const parsed = contract.parseCodexCompletionRequest({
    ...BASE,
    ...V2_REQUEST_KEYS,
    deadlineMs: 15000,
  })
  assert.equal(parsed.ok, true)
  const requestHash = contract.hashCodexCompletionRequest(parsed.value)
  const envelope = contract.buildCodexProxyEnvelope({
    executionTicket: ticket,
    requestHash,
    request: parsed.value,
  })
  assert.equal(envelope.ok, true, envelope.message)
  assert.deepEqual(Object.keys(envelope.value), ['executionTicket', 'requestHash', 'request'])
  assert.equal('deadlineMs' in envelope.value, false, 'outer deadline is never emitted')
  assert.equal(
    envelope.value.request.deadlineMs,
    15000,
    'deadline travels inside the hashed request'
  )
  assert.equal(Object.isFrozen(envelope.value), true)
  assert.equal(
    Buffer.byteLength(JSON.stringify(envelope.value), 'utf8') <=
      contract.requestBodyLimitBytes(envelope.value.request),
    true
  )

  const shifted = contract.parseCodexCompletionRequest({
    ...BASE,
    ...V2_REQUEST_KEYS,
    deadlineMs: 15001,
  })
  assert.notEqual(
    contract.hashCodexCompletionRequest(shifted.value),
    requestHash,
    'the deadline is bound by the request hash'
  )

  // V2 exact boundary. The request's own share is bounded (images at ~21 MiB
  // encoded, everything else at 1 MiB), so padding its text can no longer reach
  // the envelope ceiling — the ticket is the field that moves it, and the ticket
  // is what the authorizer really adds.
  const envelopeForTicket = ticketBytes => {
    const request = contract.parseCodexCompletionRequest(VISUAL_FIXTURE.png)
    assert.equal(request.ok, true, request.message)
    const hash = contract.hashCodexCompletionRequest(request.value)
    const executionTicket = 't'.repeat(ticketBytes)
    return {
      executionTicket,
      hash,
      request,
      size: Buffer.byteLength(
        JSON.stringify({ executionTicket, requestHash: hash, request: request.value }),
        'utf8'
      ),
    }
  }
  const limit = contract.requestBodyLimitBytes(parsed.value)
  assert.equal(limit, contract.LIMITS.maxVisualRequestBodyBytes)
  const probe = envelopeForTicket(8)
  const exactTicket = 8 + (limit - probe.size)
  const exact = envelopeForTicket(exactTicket)
  assert.equal(exact.size, limit)
  const atLimit = contract.buildCodexProxyEnvelope({
    executionTicket: exact.executionTicket,
    requestHash: exact.hash,
    request: exact.request.value,
  })
  assert.equal(atLimit.ok, true, atLimit.message)
  assert.equal(Buffer.byteLength(JSON.stringify(atLimit.value), 'utf8'), limit)

  const over = envelopeForTicket(exactTicket + 1)
  assert.equal(over.size, limit + 1)
  const refused = contract.buildCodexProxyEnvelope({
    executionTicket: over.executionTicket,
    requestHash: over.hash,
    request: over.request.value,
  })
  assert.equal(refused.ok, false)
  assert.equal(refused.code, 'limit')
  assert.equal(refused.message, 'proxy envelope exceeds maxVisualRequestBodyBytes')

  // V1 keeps the 1 MiB envelope ceiling: same construction, exact boundary, and
  // the V1 failure message.
  const v1Request = contract.parseCodexCompletionRequest({ ...BASE, deadlineMs: 5000 })
  assert.equal(v1Request.ok, true)
  const v1Hash = contract.hashCodexCompletionRequest(v1Request.value)
  const v1Size = ticketBytes =>
    Buffer.byteLength(
      JSON.stringify({
        executionTicket: 't'.repeat(ticketBytes),
        requestHash: v1Hash,
        request: v1Request.value,
      }),
      'utf8'
    )
  const v1Ticket = 8 + (contract.LIMITS.maxRequestBodyBytes - v1Size(8))
  const v1Exact = contract.buildCodexProxyEnvelope({
    executionTicket: 't'.repeat(v1Ticket),
    requestHash: v1Hash,
    request: v1Request.value,
  })
  assert.equal(v1Exact.ok, true, v1Exact.message)
  assert.equal(Buffer.byteLength(JSON.stringify(v1Exact.value), 'utf8'), v1Size(v1Ticket))
  assert.equal(
    Buffer.byteLength(JSON.stringify(v1Exact.value), 'utf8'),
    contract.LIMITS.maxRequestBodyBytes
  )
  const v1Over = contract.buildCodexProxyEnvelope({
    executionTicket: 't'.repeat(v1Ticket + 1),
    requestHash: v1Hash,
    request: v1Request.value,
  })
  assert.equal(v1Over.ok, false)
  assert.equal(v1Over.code, 'limit')
  assert.equal(v1Over.message, 'proxy envelope exceeds maxRequestBodyBytes')
})

test('buildCodexProxyEnvelope: fails closed on hash mismatch, bad input and invalid requests', () => {
  const ticket = 'header.payload.signature'
  const parsed = contract.parseCodexCompletionRequest(VISUAL_FIXTURE.png)
  assert.equal(parsed.ok, true)
  const requestHash = contract.hashCodexCompletionRequest(parsed.value)
  const cases = [
    {
      name: 'hash-mismatch',
      input: { executionTicket: ticket, requestHash: 'a'.repeat(64), request: parsed.value },
      code: 'request_hash_mismatch',
    },
    {
      name: 'hash-shape',
      input: { executionTicket: ticket, requestHash: 'not-a-digest', request: parsed.value },
      code: 'invalid',
    },
    {
      name: 'unknown-envelope-field',
      input: { executionTicket: ticket, requestHash, request: parsed.value, deadlineMs: 1000 },
      code: 'unknown-field',
    },
    {
      name: 'short-ticket',
      input: { executionTicket: 'short', requestHash, request: parsed.value },
      code: 'invalid',
    },
    {
      name: 'ticket-control-character',
      input: { executionTicket: 'ticket\u0000value', requestHash, request: parsed.value },
      code: 'invalid',
    },
    {
      name: 'request-unknown-root-field',
      input: {
        executionTicket: ticket,
        requestHash,
        request: { ...VISUAL_FIXTURE.png, headers: { Authorization: 'Bearer x' } },
      },
      code: 'unknown-field',
    },
    {
      name: 'request-contradictory-parts',
      input: {
        executionTicket: ticket,
        requestHash,
        request: v2WithParts([{ type: 'text', text: 'actual' }], 'different'),
      },
      code: 'invalid',
    },
  ]
  for (const entry of cases) {
    const built = contract.buildCodexProxyEnvelope(entry.input)
    assert.equal(built.ok, false, entry.name)
    assert.equal(built.code, entry.code, entry.name)
  }
  assert.equal(contract.buildCodexProxyEnvelope(null).code, 'invalid')

  const v1 = contract.parseCodexCompletionRequest({ ...BASE, deadlineMs: 5000 })
  assert.equal(v1.ok, true)
  const v1Envelope = contract.buildCodexProxyEnvelope({
    executionTicket: ticket,
    requestHash: contract.hashCodexCompletionRequest(v1.value),
    request: v1.value,
  })
  assert.equal(v1Envelope.ok, true, v1Envelope.message)
  assert.deepEqual(Object.keys(v1Envelope.value), ['executionTicket', 'requestHash', 'request'])
  assert.equal('deadlineMs' in v1Envelope.value, false)
})

test('isBoundedId rejects empty, oversized, and non-id characters', () => {
  assert.equal(contract.isBoundedId('invocation-1'), true)
  assert.equal(contract.isBoundedId('ns/name:slot'), true)
  assert.equal(contract.isBoundedId(''), false)
  assert.equal(contract.isBoundedId('x'.repeat(129)), false)
  assert.equal(contract.isBoundedId('has space'), false)
  assert.equal(contract.isBoundedId(1), false)
})

test('measureNonImageAuthorizeBytes keeps wrapper fields on the maxRequestBodyBytes budget', () => {
  const image = imagePart(IMAGE_DATA.png)
  const request = {
    ...BASE,
    schemaVersion: contract.SCHEMA_VERSION_V2,
    messages: [
      {
        role: 'user',
        content: 'look',
        contentParts: [{ type: 'text', text: 'look' }, image],
      },
    ],
  }
  const wrapper = {
    request,
    invocationId: 'invocation-1',
    attemptGeneration: 1,
    targetRef: 'codex-primary',
  }
  const whole = Buffer.byteLength(JSON.stringify(wrapper), 'utf8')
  const nonImage = contract.measureNonImageAuthorizeBytes(wrapper)
  assert.ok(whole > nonImage)
  assert.ok(nonImage < contract.LIMITS.maxRequestBodyBytes)
  assert.equal(contract.requestBodyLimitBytes(wrapper.request), 25165824)

  const stuffed = {
    ...wrapper,
    invocationId: 'x'.repeat(contract.LIMITS.maxRequestBodyBytes + 1024 * 1024),
  }
  assert.ok(contract.measureNonImageAuthorizeBytes(stuffed) > contract.LIMITS.maxRequestBodyBytes)
  assert.equal(contract.requestBodyLimitBytes(stuffed.request), 25165824)
})

test('measureNonImageCompletionBytes omits the execution ticket', () => {
  const request = {
    ...BASE,
    schemaVersion: contract.SCHEMA_VERSION_V2,
    messages: [
      {
        role: 'user',
        content: 'look',
        contentParts: [{ type: 'text', text: 'look' }, imagePart(IMAGE_DATA.png)],
      },
    ],
  }
  const authorize = {
    request,
    invocationId: 'invocation-1',
    attemptGeneration: 1,
    targetRef: 'codex-primary',
  }
  const room = 500
  const pad =
    contract.LIMITS.maxRequestBodyBytes - contract.measureNonImageAuthorizeBytes(authorize) - room
  assert.ok(pad > 64)
  const tightAuthorize = {
    ...authorize,
    invocationId: `${authorize.invocationId}${'x'.repeat(pad)}`,
  }
  assert.ok(contract.measureNonImageAuthorizeBytes(tightAuthorize) < contract.LIMITS.maxRequestBodyBytes)

  const completion = {
    ...tightAuthorize,
    requestHash: 'a'.repeat(64),
    executionTicket: `header.${'a'.repeat(2048)}.sig`,
  }
  assert.ok(contract.measureNonImageAuthorizeBytes(completion) > contract.LIMITS.maxRequestBodyBytes)
  assert.ok(contract.measureNonImageCompletionBytes(completion) <= contract.LIMITS.maxRequestBodyBytes)
  assert.equal(
    contract.measureNonImageCompletionBytes(completion),
    contract.measureNonImageAuthorizeBytes({
      ...tightAuthorize,
      requestHash: completion.requestHash,
    })
  )
})

// ---------------------------------------------------------------------------
// Canonical hashing shared by mcp-host (client) and control-api/codex-llm-proxy
// (server), plus the structural depth cap.
// ---------------------------------------------------------------------------

const GOLDEN = JSON.parse(
  fs.readFileSync(path.join(__dirname, 'fixtures/golden-request-hashes.json'), 'utf8')
)

function nest(depth, key, leaf = {}) {
  let value = leaf
  for (let i = 1; i < depth; i++) value = { [key]: value }
  return value
}

function nestArrays(depth) {
  let value = []
  for (let i = 1; i < depth; i++) value = [value]
  return value
}

/** What a JSON peer (control-api authorize, codex-llm-proxy) computes. */
function serverHash(wireRequest) {
  const onWire = JSON.parse(JSON.stringify({ request: wireRequest })).request
  const parsed = contract.parseCodexCompletionRequestV1(onWire)
  assert.equal(parsed.ok, true, parsed.message)
  return contract.hashCodexCompletionRequestV1(parsed.value)
}

test('golden digests: well-formed requests keep their pre-change hashes on every path', () => {
  const golden = [
    ...GOLDEN.cases,
    {
      name: 'parameters-at-max-depth-64',
      request: {
        ...BASE,
        requestId: 'req-golden',
        idempotencyKey: 'idem-golden',
        messages: [{ role: 'user', content: 'deep' }],
        tools: [{ name: 'deep', description: 'deep schema', parameters: nest(64, 'n') }],
      },
      sha256: GOLDEN.depthBoundaryDigests['parameters-at-max-depth-64'],
    },
    {
      name: 'arguments-at-max-depth-64',
      request: {
        ...BASE,
        requestId: 'req-golden',
        idempotencyKey: 'idem-golden',
        messages: [
          {
            role: 'assistant',
            content: '',
            toolCalls: [{ id: 'call-deep', name: 'deep', arguments: nest(64, 'a') }],
          },
        ],
      },
      sha256: GOLDEN.depthBoundaryDigests['arguments-at-max-depth-64'],
    },
  ]
  assert.equal(golden.length, 6)
  for (const entry of golden) {
    const parsed = contract.parseCodexCompletionRequestV1(entry.request)
    assert.equal(parsed.ok, true, `${entry.name}: ${parsed.message}`)
    assert.equal(contract.hashCodexCompletionRequestV1(parsed.value), entry.sha256, entry.name)
    const canonical = contract.hashCanonicalCodexRequest(entry.request)
    assert.equal(canonical.ok, true, entry.name)
    assert.equal(canonical.value.requestHash, entry.sha256, entry.name)
    assert.equal(serverHash(canonical.value.request), entry.sha256, entry.name)
  }
})

const DIVERGENT_SHAPES = [
  ['empty generation from a non-enum tool_choice', { generation: {} }],
  ['empty tools array', { tools: [] }],
  ['empty transportHints', { transportHints: {} }],
  ['transportHints with an undefined cache key', { transportHints: { promptCacheKey: undefined } }],
  [
    'undefined optional message fields',
    { messages: [{ role: 'user', content: 'x', name: undefined, toolCallId: undefined }] },
  ],
  [
    'undefined leaves in assistant tool-call arguments',
    {
      messages: [
        { role: 'user', content: 'x' },
        {
          role: 'assistant',
          content: '',
          toolCalls: [{ id: 'c1', name: 't', arguments: { a: undefined, b: [undefined] } }],
        },
      ],
    },
  ],
  [
    'a Date inside tool parameters (serialized by toJSON on the wire)',
    {
      tools: [{ name: 't', description: 'd', parameters: { type: 'object', since: new Date(0) } }],
    },
  ],
]

for (const [label, overrides] of DIVERGENT_SHAPES) {
  test(`hashCanonicalCodexRequest matches the server hash for ${label}`, () => {
    const raw = { ...BASE, ...overrides }
    const canonical = contract.hashCanonicalCodexRequest(raw)
    assert.equal(canonical.ok, true, canonical.message)
    assert.match(canonical.value.requestHash, /^[a-f0-9]{64}$/)
    // mcp-host sends the canonical request; a caller that still sent the raw
    // request must land on the same digest.
    assert.equal(serverHash(canonical.value.request), canonical.value.requestHash)
    assert.equal(serverHash(raw), canonical.value.requestHash)
  })
}

test('hashCanonicalCodexRequest drops empty optional containers from the canonical request', () => {
  const canonical = contract.hashCanonicalCodexRequest({
    ...BASE,
    generation: {},
    tools: [],
    transportHints: {},
  })
  assert.equal(canonical.ok, true)
  assert.deepEqual(Object.keys(canonical.value.request).sort(), Object.keys(BASE).sort())
})

test('hashCanonicalCodexRequest fails closed without throwing on invalid input', () => {
  const cases = [
    [{ ...BASE, generation: { temperature: 3 } }, 'invalid'],
    [{ ...BASE, provider: 'grok-subscription' }, 'invalid'],
    [{ ...BASE, headers: { authorization: 'x' } }, 'unknown-field'],
    [{ ...BASE, deadlineMs: 10n }, 'invalid'],
    ['not-an-object', 'invalid'],
  ]
  for (const [raw, code] of cases) {
    const result = contract.hashCanonicalCodexRequest(raw)
    assert.equal(result.ok, false)
    assert.equal(result.code, code)
  }
  const cyclic = { ...BASE, tools: [{ name: 't', description: 'd', parameters: {} }] }
  cyclic.tools[0].parameters.self = cyclic.tools[0].parameters
  const cyclicResult = contract.hashCanonicalCodexRequest(cyclic)
  assert.equal(cyclicResult.ok, false)
  assert.equal(cyclicResult.code, 'limit')
})

test('LIMITS publishes the nesting depth cap', () => {
  assert.equal(contract.LIMITS.maxNestingDepth, 64)
})

test('LIMITS publishes the id length cap', () => {
  assert.equal(contract.LIMITS.maxIdLength, 128)
})

// ID_PATTERN spells the id length out instead of reading LIMITS.maxIdLength,
// so this ties the two together: changing either one alone fails here.
test('request ids accept LIMITS.maxIdLength characters and reject one more', () => {
  const max = contract.LIMITS.maxIdLength
  assert.equal(contract.parseCodexCompletionRequestV1({ ...BASE, requestId: 'r'.repeat(max) }).ok, true)
  assert.deepEqual(contract.parseCodexCompletionRequestV1({ ...BASE, requestId: 'r'.repeat(max + 1) }), {
    ok: false,
    code: 'invalid',
    message: 'requestId is invalid',
  })
})

test('tool parameters accept depth 64 and reject depth 65 with a limit failure', () => {
  const at = contract.parseCodexCompletionRequestV1({
    ...BASE,
    tools: [{ name: 'deep', description: 'd', parameters: nest(64, 'n') }],
  })
  assert.equal(at.ok, true, at.message)
  const over = contract.parseCodexCompletionRequestV1({
    ...BASE,
    tools: [{ name: 'deep', description: 'd', parameters: nest(65, 'n') }],
  })
  assert.equal(over.ok, false)
  assert.equal(over.code, 'limit')
  assert.match(over.message, /nesting depth/)
})

test('assistant tool-call arguments accept depth 64 and reject depth 65', () => {
  const request = depth => ({
    ...BASE,
    messages: [
      {
        role: 'assistant',
        content: '',
        toolCalls: [{ id: 'c1', name: 'deep', arguments: nest(depth, 'a') }],
      },
    ],
  })
  const at = contract.parseCodexCompletionRequestV1(request(64))
  assert.equal(at.ok, true, at.message)
  const over = contract.parseCodexCompletionRequestV1(request(65))
  assert.equal(over.ok, false)
  assert.equal(over.code, 'limit')
})

for (const depth of [5000, 150000]) {
  test(`a ${depth}-deep body returns a limit failure instead of a RangeError`, () => {
    const viaObjects = {
      ...BASE,
      tools: [{ name: 't', description: 'd', parameters: nest(depth, 'n') }],
    }
    const viaArrays = {
      ...BASE,
      tools: [{ name: 't', description: 'd', parameters: { x: nestArrays(depth) } }],
    }
    for (const raw of [viaObjects, viaArrays]) {
      const parsed = contract.parseCodexCompletionRequestV1(raw)
      assert.equal(parsed.ok, false)
      assert.equal(parsed.code, 'limit')
      const canonical = contract.hashCanonicalCodexRequest(raw)
      assert.equal(canonical.ok, false)
      assert.equal(canonical.code, 'limit')
    }
  })
}

test('stableStringify rejects over-deep values with a limit error, not a stack overflow', () => {
  for (const value of [nest(5000, 'n'), nestArrays(150000)]) {
    assert.throws(
      () => contract.stableStringify(value),
      err => err.code === 'limit' && !(err instanceof RangeError)
    )
  }
  // Any request the parser accepts stays serializable.
  assert.doesNotThrow(() =>
    contract.stableStringify({
      tools: [{ parameters: nest(64, 'n') }],
      m: [[{ a: nest(64, 'a') }]],
    })
  )
})

test('frozen Codex fixture corpus hashes identically through hashCanonicalCodexRequest', () => {
  for (const fixture of FIXTURE.cases) {
    for (const request of [fixture.request, fixture.equivalentRequest].filter(Boolean)) {
      const canonical = contract.hashCanonicalCodexRequest(request)
      assert.equal(canonical.ok, true, fixture.name)
      assert.equal(canonical.value.requestHash, fixture.sha256, fixture.name)
    }
  }
  for (const fixture of FIXTURE.rejects) {
    assert.equal(contract.hashCanonicalCodexRequest(fixture.request).ok, false, fixture.name)
  }
})

// A8: JSON.parse allocates one heap object per container, so a body can fit
// every byte bound and still exhaust the proxy heap. The contract bounds the
// container count of a request, and codex-llm-proxy and control-api scan the
// raw body against the same bound before JSON.parse runs. The scan's own
// behaviour is tested in the Grok contract; bodyStructure.cjs is the same
// file in both packages, which the test below enforces.

/** Containers (objects and arrays) in a parsed value, the root included. */
function countContainers(value) {
  let containers = 0
  const stack = [value]
  while (stack.length > 0) {
    const node = stack.pop()
    if (node === null || typeof node !== 'object') continue
    containers++
    for (const child of Object.values(node)) stack.push(child)
  }
  return containers
}

/** A valid request holding exactly `target` containers. */
function requestWithContainers(target) {
  const filler = []
  const request = {
    ...BASE,
    tools: [{ name: 'crm__export', description: 'd', parameters: { type: 'object', filler } }],
  }
  for (let count = countContainers(request); count < target; count++) filler.push([])
  assert.equal(countContainers(request), target)
  return request
}

test('LIMITS.maxRequestContainers is pinned', () => {
  assert.equal(contract.LIMITS.maxRequestContainers, 262144)
})

// Only the refusal fields are compared, so a regression that accepts the
// request fails with a short diff instead of inspecting a value that holds
// hundreds of thousands of containers.
function refusalOf(result) {
  return { ok: result.ok, code: result.code, kind: result.kind, message: result.message }
}

test("a request over maxRequestContainers is refused with kind:'size'", () => {
  const limit = contract.LIMITS.maxRequestContainers
  const at = requestWithContainers(limit)
  assert.equal(contract.parseCodexCompletionRequest(at).ok, true)
  assert.equal(contract.hashCanonicalCodexRequest(at).ok, true)
  const expected = {
    ok: false,
    code: 'limit',
    kind: 'size',
    message: 'request exceeds maxRequestContainers',
  }
  const over = requestWithContainers(limit + 1)
  assert.ok(Buffer.byteLength(JSON.stringify(over), 'utf8') < contract.LIMITS.maxRequestBodyBytes)
  assert.deepEqual(refusalOf(contract.parseCodexCompletionRequest(over)), expected)
  assert.deepEqual(refusalOf(contract.hashCanonicalCodexRequest(over)), expected)
  assert.deepEqual(
    refusalOf(contract.parseCodexCompletionRequest({ ...over, schemaVersion: 'codex-completion-request.v2' })),
    expected
  )
})

/** Object members in a parsed value, over every object in the tree. */
function countMembers(value) {
  let members = 0
  const stack = [value]
  while (stack.length > 0) {
    const node = stack.pop()
    if (node === null || typeof node !== 'object') continue
    if (!Array.isArray(node)) members += Object.keys(node).length
    for (const child of Object.values(node)) stack.push(child)
  }
  return members
}

/** A valid request holding exactly `target` object members. */
function requestWithMembers(target) {
  const filler = {}
  const request = {
    ...BASE,
    tools: [{ name: 'crm__export', description: 'd', parameters: { type: 'object', properties: filler } }],
  }
  for (let count = countMembers(request); count < target; count++) {
    filler[`m${String(count).padStart(7, '0')}`] = 0
  }
  assert.equal(countMembers(request), target)
  return request
}

test('LIMITS.maxRequestMembers is pinned', () => {
  assert.equal(contract.LIMITS.maxRequestMembers, 262144)
})

/** Count JSON values independently of the contract's structural pre-check. */
function countElements(value) {
  let elements = 1
  const stack = [value]
  while (stack.length > 0) {
    const node = stack.pop()
    if (node === null || typeof node !== 'object') continue
    const children = Array.isArray(node) ? node : Object.values(node)
    elements += children.length
    for (const child of children) if (child !== null && typeof child === 'object') stack.push(child)
  }
  return elements
}

function requestWithElements(target) {
  const filler = []
  const request = {
    ...BASE,
    tools: [{ name: 'crm__export', description: 'd', parameters: { type: 'object', enum: filler } }],
  }
  filler.length = target - countElements(request)
  filler.fill(0)
  assert.equal(countElements(request), target)
  return request
}

test('LIMITS.maxRequestElements is pinned', () => {
  assert.equal(contract.LIMITS.maxRequestElements, 1048576)
})

test("a request over maxRequestElements is refused with kind:'size'", () => {
  const limit = contract.LIMITS.maxRequestElements
  const at = requestWithElements(limit)
  assert.equal(contract.parseCodexCompletionRequest(at).ok, true)
  assert.equal(contract.hashCanonicalCodexRequest(at).ok, true)
  const over = requestWithElements(limit + 1)
  assert.ok(Buffer.byteLength(JSON.stringify(over), 'utf8') < contract.LIMITS.maxRequestBodyBytes)
  const expected = {
    ok: false,
    code: 'limit',
    kind: 'size',
    message: 'request exceeds maxRequestElements',
  }
  assert.deepEqual(refusalOf(contract.parseCodexCompletionRequest(over)), expected)
  assert.deepEqual(refusalOf(contract.hashCanonicalCodexRequest(over)), expected)
  assert.deepEqual(
    refusalOf(contract.parseCodexCompletionRequest({ ...over, schemaVersion: 'codex-completion-request.v2' })),
    expected
  )
})

test("a request over maxRequestMembers is refused with kind:'size'", () => {
  const limit = contract.LIMITS.maxRequestMembers
  const at = requestWithMembers(limit)
  assert.equal(contract.parseCodexCompletionRequest(at).ok, true)
  assert.equal(contract.hashCanonicalCodexRequest(at).ok, true)
  const expected = {
    ok: false,
    code: 'limit',
    kind: 'size',
    message: 'request exceeds maxRequestMembers',
  }
  const over = requestWithMembers(limit + 1)
  // The refusal is the member bound, not a byte bound.
  assert.ok(Buffer.byteLength(JSON.stringify(over), 'utf8') < contract.LIMITS.maxRequestBodyBytes)
  assert.deepEqual(refusalOf(contract.parseCodexCompletionRequest(over)), expected)
  assert.deepEqual(refusalOf(contract.hashCanonicalCodexRequest(over)), expected)
  assert.deepEqual(
    refusalOf(contract.parseCodexCompletionRequest({ ...over, schemaVersion: 'codex-completion-request.v2' })),
    expected
  )
})

test('bodyStructure.cjs is byte-identical in both contract packages', () => {
  const codex = fs.readFileSync(path.join(__dirname, 'bodyStructure.cjs'))
  const grok = fs.readFileSync(path.join(__dirname, '../grok-provider-attempt-contract/bodyStructure.cjs'))
  assert.ok(codex.length > 0)
  assert.equal(Buffer.compare(codex, grok), 0)
})

test('BODY_STRUCTURE_LIMITS derive from LIMITS', () => {
  const limits = contract.BODY_STRUCTURE_LIMITS
  assert.deepEqual(limits, {
    maxStructuralBytes: contract.LIMITS.maxRequestBodyBytes + contract.ENVELOPE_ALLOWANCE_BYTES,
    maxContainers: contract.LIMITS.maxRequestContainers + 16,
    maxDepth: contract.LIMITS.maxNestingDepth + 6,
    maxMembers: contract.LIMITS.maxRequestMembers + 64,
    maxElements: contract.LIMITS.maxRequestElements + 64,
  })
  assert.deepEqual(limits, {
    maxStructuralBytes: 8404992,
    maxContainers: 262160,
    maxDepth: 70,
    maxMembers: 262208,
    maxElements: 1048640,
  })
  assert.equal(Object.isFrozen(limits), true)
})

test('the body scan admits the deepest and the largest request the contract admits', () => {
  const limits = contract.BODY_STRUCTURE_LIMITS
  const deepest = {
    ...BASE,
    messages: [
      {
        role: 'assistant',
        content: '',
        toolCalls: [{ id: 'c1', name: 'deep', arguments: nest(contract.LIMITS.maxNestingDepth, 'a') }],
      },
    ],
  }
  assert.equal(contract.parseCodexCompletionRequest(deepest).ok, true)
  const deep = Buffer.from(JSON.stringify({ executionTicket: 't', requestHash: 'h', request: deepest }))
  assert.equal(contract.scanJsonStructure(deep, limits).deepest, limits.maxDepth)
  const request = requestWithContainers(contract.LIMITS.maxRequestContainers)
  const wide = Buffer.from(JSON.stringify({ executionTicket: 't', requestHash: 'h', request }))
  assert.equal(contract.scanJsonStructure(wide, limits).containers, contract.LIMITS.maxRequestContainers + 1)
})

test('the body scan bounds object members and never counts string contents', () => {
  const limits = contract.BODY_STRUCTURE_LIMITS
  const atBound = Buffer.from(
    `{${Array.from({ length: limits.maxMembers }, (_, i) => `"m${i}":0`).join(',')}}`
  )
  assert.equal(contract.scanJsonStructure(atBound, limits).members, limits.maxMembers)
  assert.throws(
    () =>
      contract.scanJsonStructure(
        Buffer.from(`{${Array.from({ length: limits.maxMembers + 1 }, (_, i) => `"m${i}":0`).join(',')}}`),
        limits
      ),
    {
      name: 'BodyStructureError',
      status: 413,
      type: 'body.structure.too.many.members',
    }
  )
  // A colon inside a string is content, not a member.
  const quoted = Buffer.from(`["${':'.repeat(10)}"]`)
  assert.equal(contract.scanJsonStructure(quoted, limits).members, 0)
})

test('the body scan counts values exactly and bounds elements before JSON.parse', () => {
  const limits = contract.BODY_STRUCTURE_LIMITS
  for (const [json, elements] of [
    ['{"a":0}', 2],
    ['[{},{}]', 3],
    ['[ 0 , "x,[{}]", {"a": [1, 2]} ]', 7],
    ['{"a\\\"[,": "\\\\,]"}', 2],
  ]) {
    assert.equal(contract.scanJsonStructure(Buffer.from(json), limits).elements, elements, json)
  }
  const at = Buffer.from(`[${'0,'.repeat(limits.maxElements - 2)}0]`)
  assert.equal(contract.scanJsonStructure(at, limits).elements, limits.maxElements)
  const over = Buffer.from(`[${'0,'.repeat(limits.maxElements - 1)}0]`)
  assert.throws(() => contract.scanJsonStructure(over, limits), {
    name: 'BodyStructureError',
    status: 413,
    type: 'body.structure.too.many.elements',
  })
})

test('the body scan treats a container holding only whitespace as empty', () => {
  const limits = contract.BODY_STRUCTURE_LIMITS
  for (const [json, elements] of [
    ['[ ]', 1],
    ['{ \n }', 1],
    ['[\n]', 1],
    ['[\t\r\n ]', 1],
    ['[[ ], { \n }, [\n]]', 4],
    // Liveness witnesses: a container with a value inside is still counted.
    ['[ 0 ]', 2],
    ['{ "a" : 0 }', 2],
    ['[\n[ ]\n]', 2],
  ]) {
    assert.equal(contract.scanJsonStructure(Buffer.from(json), limits).elements, elements, json)
  }
  // The element bound sees the same counts: three whitespace-only containers in
  // an array make 4 values, and a fourth makes 5.
  const tight = { ...limits, maxElements: 4 }
  assert.equal(contract.scanJsonStructure(Buffer.from('[[ ],[\n],{ }]'), tight).elements, 4)
  assert.throws(() => contract.scanJsonStructure(Buffer.from('[[ ],[\n],{ },[]]'), tight), {
    name: 'BodyStructureError',
    status: 413,
    type: 'body.structure.too.many.elements',
  })
})

test('the verify hook refuses a charset other than UTF-8 and scans UTF-8 bodies', () => {
  const verify = contract.createBodyStructureVerify(contract.BODY_STRUCTURE_LIMITS)
  const body = Buffer.from('{"a":[1]}')
  assert.throws(() => verify({}, {}, body, 'utf-16le'), {
    name: 'BodyStructureError',
    status: 415,
    type: 'charset.unsupported',
  })
  assert.equal(verify({}, {}, body, 'utf-8'), undefined)
  const deep = Buffer.from('['.repeat(71) + ']'.repeat(71))
  assert.throws(() => verify({}, {}, deep, 'utf-8'), { status: 400, type: 'body.structure.too.deep' })
  const wide = Buffer.from(`[${'[],'.repeat(contract.BODY_STRUCTURE_LIMITS.maxContainers)}[]]`)
  assert.throws(() => verify({}, {}, wide, 'utf-8'), { status: 413, type: 'body.structure.too.many.containers' })
})

test('the verify hook fails closed unless every bound is a positive safe integer', () => {
  const good = contract.BODY_STRUCTURE_LIMITS
  for (const name of ['maxStructuralBytes', 'maxContainers', 'maxDepth', 'maxMembers', 'maxElements']) {
    for (const value of [undefined, 0, -1, 1.5, Number.MAX_SAFE_INTEGER + 1]) {
      assert.throws(() => contract.createBodyStructureVerify({ ...good, [name]: value }), TypeError)
    }
  }
  // Liveness witness: the contract's own bounds construct the hook.
  assert.equal(typeof contract.createBodyStructureVerify(good), 'function')
})