diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 576e1810e91..1b0b739f9fa 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -480,6 +480,7 @@ jobs: "/brand/mcp" "/inventory-adserver/mcp" "/inventory-content/mcp" + "/adserver-us/mcp" "/mcp" ) # Build curl args once. Omit the Authorization header when the secret diff --git a/server/src/training-agent/inventory-sim/engine/index.ts b/server/src/training-agent/inventory-sim/engine/index.ts index 57f0c2ec85f..f9c5464f334 100644 --- a/server/src/training-agent/inventory-sim/engine/index.ts +++ b/server/src/training-agent/inventory-sim/engine/index.ts @@ -51,3 +51,4 @@ export { toAdcpForecast, type AdcpDeliveryForecast, type ForecastRange } from '. export { ENGINE_VERSION } from './version.js'; export { ADSERVER_SEASON } from './seeds/adserver-season.js'; export { CONTENT_SEASON } from './seeds/content-season.js'; +export { ADSERVER_US_SEASON } from './seeds/adserver-us-season.js'; diff --git a/server/src/training-agent/inventory-sim/engine/seeds/adserver-us-season.ts b/server/src/training-agent/inventory-sim/engine/seeds/adserver-us-season.ts new file mode 100644 index 00000000000..07cec252d68 --- /dev/null +++ b/server/src/training-agent/inventory-sim/engine/seeds/adserver-us-season.ts @@ -0,0 +1,122 @@ +/** + * Season seed for a US ad server: three publishers, Northstar, Meridian and + * Harbor, each selling run of site 300x250 display. Northstar sells in an + * open first-price auction; Meridian and Harbor sell guaranteed at a fixed CPM. + * Sales regions are the three US regions. The rng_seed is shared with the + * other ad server season on purpose, so the two seasons' noise is correlated. + */ +import type { SeasonSeed } from '../types.js'; + +// The publishers' domains use the reserved .example suffix like the other ad server season. +const NORTHSTAR_DOMAIN = 'northstar.example'; +const MERIDIAN_DOMAIN = 'meridian.example'; +const HARBOR_DOMAIN = 'harbor.example'; + +export const ADSERVER_US_SEASON: SeasonSeed = { + seed_id: 'adserver-us-2027', + rng_seed: 'adserver-2027-v1', + start_date: '2026-11-01', + days: 730, + currency: 'USD', + regions: [ + { region_id: 'us_northeast', country: 'US', name: 'US Northeast', share: 0.35 }, + { region_id: 'us_south', country: 'US', name: 'US South', share: 0.35 }, + { region_id: 'us_west', country: 'US', name: 'US West', share: 0.3 }, + ], + audience_profiles: [ + { profile_id: 'young_urban', name: 'Young urban', share: 0.3, rate_multipliers: { click_rate: 1.3, conversion_rate: 0.8 } }, + { profile_id: 'families', name: 'Families', share: 0.25 }, + { profile_id: 'professionals', name: 'Professionals', share: 0.3, rate_multipliers: { viewability: 1.05, conversion_rate: 1.3 } }, + { profile_id: 'retirees', name: 'Retirees', share: 0.15, rate_multipliers: { click_rate: 0.7, completion_rate: 1.1 } }, + ], + segments: [ + { segment_id: 'sports_fans', name: 'Sports fans', profile_ids: ['young_urban', 'professionals'] }, + { segment_id: 'household_decision_makers', name: 'Household decision makers', profile_ids: ['families', 'professionals'] }, + { segment_id: 'news_loyalists', name: 'News loyalists', profile_ids: ['professionals', 'retirees'] }, + ], + properties: [ + { property_id: 'northstar_site', name: 'Northstar', domain: NORTHSTAR_DOMAIN, publisher_id: 'northstar' }, + { property_id: 'meridian_site', name: 'Meridian', domain: MERIDIAN_DOMAIN, publisher_id: 'meridian' }, + { property_id: 'harbor_site', name: 'Harbor', domain: HARBOR_DOMAIN, publisher_id: 'harbor' }, + ], + placements: [ + { + placement_id: 'northstar', + name: 'Northstar run of site', + channel: 'display', + property_ids: ['northstar_site'], + formats: ['display_300x250'], + base_daily_impressions: 500_000, + floor_cpm: 2, + rates: { viewability: 0.7, click_rate: 0.0028, completion_rate: 0, conversion_rate: 0.02 }, + reporting_lag_days: 0, + }, + { + placement_id: 'meridian', + name: 'Meridian run of site', + channel: 'display', + property_ids: ['meridian_site'], + formats: ['display_300x250'], + base_daily_impressions: 320_000, + floor_cpm: 2, + rates: { viewability: 0.7, click_rate: 0.0035, completion_rate: 0, conversion_rate: 0.025 }, + reporting_lag_days: 0, + }, + { + placement_id: 'harbor', + name: 'Harbor run of site', + channel: 'display', + property_ids: ['harbor_site'], + formats: ['display_300x250'], + base_daily_impressions: 200_000, + floor_cpm: 2, + rates: { viewability: 0.7, click_rate: 0.0038, completion_rate: 0, conversion_rate: 0.03 }, + reporting_lag_days: 0, + }, + ], + products: [ + { + product_id: 'northstar_auction', + name: 'Northstar auction', + description: 'Run of site 300x250 display across Northstar. Sold in an open auction, first-price, above the 2 CPM floor.', + delivery_type: 'non_guaranteed', + placement_ids: ['northstar'], + }, + { + product_id: 'meridian_guaranteed', + name: 'Meridian guaranteed', + description: 'Guaranteed run of site 300x250 display across Meridian at a fixed 5 CPM, with an impression goal.', + delivery_type: 'guaranteed', + placement_ids: ['meridian'], + rate_cpm: 5, + }, + { + product_id: 'harbor_guaranteed', + name: 'Harbor guaranteed', + description: 'Guaranteed run of site 300x250 display across Harbor at a fixed 6 CPM, with an impression goal.', + delivery_type: 'guaranteed', + placement_ids: ['harbor'], + rate_cpm: 6, + }, + ], + traffic: { + weekday_shape: [0.8, 1.05, 1.1, 1.1, 1.05, 1, 0.85], + trend_per_day: 0.0002, + truth_daily_sigma: 0.03, + }, + forecast_error: { + channel_sigma: { display: 0.06, olv: 0.06 }, + ar1_phi: 0.85, + lead_time_tau_days: 14, + lead_time_horizon_days: 60, + log_clip: 0.6931471805599453, + cell_kappa: 3.08, + cell_min_impressions: 100, + publishers: [ + { publisher_id: 'northstar', bias: -0.02 }, + { publisher_id: 'meridian', bias: -0.02 }, + { publisher_id: 'harbor', bias: -0.02 }, + ], + }, + events: [], +}; diff --git a/server/src/training-agent/tenants/inventory.ts b/server/src/training-agent/tenants/inventory.ts index 7c7c3f75b76..29f3e6c67d5 100644 --- a/server/src/training-agent/tenants/inventory.ts +++ b/server/src/training-agent/tenants/inventory.ts @@ -10,6 +10,10 @@ * sold as exclusive sponsorships of the installments scheduled in a * package's flight. Installments run, are postponed or are cancelled on * their dates, and each builds its audience over its channel's curve. + * - `/adserver-us` — an ad server of the same kind as `/inventory-adserver` + * with its own season: run of site 300x250 display on three US publishers, + * Northstar in an open auction, Meridian and Harbor guaranteed at a fixed + * CPM, sold in US regions. * * Their `comply_test_controller` serves `sandbox_clock` (get, start and advance * the caller's sandbox clock), `simulation_truth` (a sandbox readout of what @@ -27,7 +31,7 @@ */ import type { TenantConfig } from '@adcp/sdk/server'; -import { ADSERVER_SEASON, CONTENT_SEASON, type SeasonSeed } from '../inventory-sim/engine/index.js'; +import { ADSERVER_SEASON, ADSERVER_US_SEASON, CONTENT_SEASON, type SeasonSeed } from '../inventory-sim/engine/index.js'; import { InventoryPlatform, type InventoryTenantProfile } from '../inventory-sim/platform.js'; import { readSeasonFile } from '../inventory-sim/season-file.js'; import { TRAINING_FORMAT_LABELS } from '../product-factory.js'; @@ -46,24 +50,59 @@ import { SALES_COMPLY_INPUT_SCHEMA, createPrincipalScopedSeedCache, seedAccountA export const INVENTORY_ADSERVER_TENANT_ID = 'inventory-adserver'; export const INVENTORY_CONTENT_TENANT_ID = 'inventory-content'; +export const INVENTORY_ADSERVER_US_TENANT_ID = 'adserver-us'; const logger = createLogger('training-agent-inventory-tenants'); +interface InventoryTenantEntry { + id: string; + kind: 'adserver' | 'content'; + /** Env var naming the season file that replaces the tenant's shipped season. */ + seasonFileEnv: string; + shipped: SeasonSeed; + label: string; + /** MCP server name reported on initialize. Default: the platform's. */ + serverName?: string; + /** Prefix of the tenant's signing key id. Default: the platform's. */ + kidPrefix?: string; +} + +const INVENTORY_TENANTS: readonly InventoryTenantEntry[] = [ + { + id: INVENTORY_ADSERVER_TENANT_ID, + kind: 'adserver', + seasonFileEnv: 'TRAINING_AGENT_INVENTORY_ADSERVER_SEASON_FILE', + shipped: ADSERVER_SEASON, + label: 'Training agent — inventory: ad server', + }, + { + id: INVENTORY_CONTENT_TENANT_ID, + kind: 'content', + seasonFileEnv: 'TRAINING_AGENT_INVENTORY_CONTENT_SEASON_FILE', + shipped: CONTENT_SEASON, + label: 'Training agent — inventory: content', + }, + { + // The id is part of every stored market document's key; it is final once deployed. + id: INVENTORY_ADSERVER_US_TENANT_ID, + kind: 'adserver', + seasonFileEnv: 'TRAINING_AGENT_INVENTORY_ADSERVER_US_SEASON_FILE', + shipped: ADSERVER_US_SEASON, + label: 'Ad server: Northstar, Meridian and Harbor', + serverName: 'northstar-meridian-harbor-adserver', + kidPrefix: '', + }, +]; + /** Env var naming the season file that replaces a tenant's shipped season. */ -export const INVENTORY_SEASON_FILE_ENV: Readonly> = { - [INVENTORY_ADSERVER_TENANT_ID]: 'TRAINING_AGENT_INVENTORY_ADSERVER_SEASON_FILE', - [INVENTORY_CONTENT_TENANT_ID]: 'TRAINING_AGENT_INVENTORY_CONTENT_SEASON_FILE', -}; - -const SHIPPED_SEASONS: Readonly> = { - [INVENTORY_ADSERVER_TENANT_ID]: ADSERVER_SEASON, - [INVENTORY_CONTENT_TENANT_ID]: CONTENT_SEASON, -}; - -function seasonFor(tenantId: string, env: NodeJS.ProcessEnv): SeasonSeed { - const envVar = INVENTORY_SEASON_FILE_ENV[tenantId]; +export const INVENTORY_SEASON_FILE_ENV: Readonly> = Object.fromEntries( + INVENTORY_TENANTS.map(tenant => [tenant.id, tenant.seasonFileEnv]), +); + +function seasonFor(tenant: InventoryTenantEntry, env: NodeJS.ProcessEnv): SeasonSeed { + const envVar = tenant.seasonFileEnv; const file = env[envVar]?.trim(); - if (!file) return SHIPPED_SEASONS[tenantId]; + if (!file) return tenant.shipped; let seed: SeasonSeed; try { seed = readSeasonFile(file, { formats: TRAINING_FORMAT_LABELS }); @@ -71,7 +110,7 @@ function seasonFor(tenantId: string, env: NodeJS.ProcessEnv): SeasonSeed { const reason = error instanceof Error ? error.message : String(error); throw new Error(`${envVar}=${file}: ${reason}`, { cause: error }); } - logger.info(`${tenantId}: season ${seed.seed_id} from ${file}`); + logger.info(`${tenant.id}: season ${seed.seed_id} from ${file}`); return seed; } @@ -80,8 +119,9 @@ function seasonFor(tenantId: string, env: NodeJS.ProcessEnv): SeasonSeed { * file throws, naming the env var and the path. */ export function resolveInventoryTenantProfiles(env: NodeJS.ProcessEnv): Record { const profiles: Record = {}; - for (const tenantId of Object.keys(SHIPPED_SEASONS)) { - profiles[tenantId] = { tenantId, seed: seasonFor(tenantId, env) }; + for (const tenant of INVENTORY_TENANTS) { + const seed = seasonFor(tenant, env); + profiles[tenant.id] = { tenantId: tenant.id, seed }; } return profiles; } @@ -91,10 +131,17 @@ export const INVENTORY_TENANT_PROFILES: Readonly> = { - [INVENTORY_ADSERVER_TENANT_ID]: 'Training agent — inventory: ad server', - [INVENTORY_CONTENT_TENANT_ID]: 'Training agent — inventory: content', -}; +/** Inventory tenants that are ad servers, whichever season they run. */ +export const INVENTORY_ADSERVER_KIND_TENANT_IDS: readonly string[] = + INVENTORY_TENANTS.filter(tenant => tenant.kind === 'adserver').map(tenant => tenant.id); + +const TENANT_ENTRIES: Readonly> = Object.fromEntries( + INVENTORY_TENANTS.map(tenant => [tenant.id, tenant]), +); + +export function isAdserverKindTenant(tenantId: string): boolean { + return INVENTORY_ADSERVER_KIND_TENANT_IDS.includes(tenantId); +} export function isInventoryTenant(tenantId: string): boolean { return INVENTORY_TENANT_IDS.includes(tenantId); @@ -189,7 +236,8 @@ export function buildInventoryTenantConfig( ): { tenantId: string; config: TenantConfig } { const profile = INVENTORY_TENANT_PROFILES[tenantId]; if (!profile) throw new Error(`Unknown inventory tenant ${tenantId}`); - const material = getTenantSigningMaterial(tenantId); + const entry = TENANT_ENTRIES[tenantId]; + const material = getTenantSigningMaterial(tenantId, entry.kidPrefix); const platform = new InventoryPlatform(profile); // Project the seed's own formats too, so canonical creatives in them // (inline on create_media_buy) map to the formats this tenant serves. @@ -199,10 +247,11 @@ export function buildInventoryTenantConfig( config: { agentUrl: `${host}/${tenantId}`, signingKey: material.signingKey, - label: LABELS[tenantId] ?? tenantId, + label: entry.label, // eslint-disable-next-line @typescript-eslint/no-explicit-any platform: platform as any, serverOptions: { + ...(entry.serverName === undefined ? {} : { name: entry.serverName }), legacyCreativeFormatConverter: projection.legacyFormatConverter, canonicalFormatLegacyResolver: projection.canonicalFormatLegacyResolver, legacyHandlers: { diff --git a/server/src/training-agent/tenants/router.ts b/server/src/training-agent/tenants/router.ts index f644143c9e1..4e065844939 100644 --- a/server/src/training-agent/tenants/router.ts +++ b/server/src/training-agent/tenants/router.ts @@ -88,7 +88,7 @@ import { grantFor, grantPermits, loadSandbox } from '../account-sandbox.js'; import { projectCollectionCapabilities } from '../collections/capabilities.js'; import { supportsCollections33 } from '../collections/card-catalog.js'; import { SEED_COLLECTION_SCENARIO } from '../collections/seed-collection.js'; -import { INVENTORY_ADSERVER_TENANT_ID, INVENTORY_COMPLY_SCENARIOS, INVENTORY_TENANT_PROFILES, handleInventorySandboxClock, handleInventorySimulationTruth, handleInventoryWinShareCut, isInventoryTenant } from './inventory.js'; +import { INVENTORY_COMPLY_SCENARIOS, INVENTORY_TENANT_IDS, INVENTORY_TENANT_PROFILES, handleInventorySandboxClock, handleInventorySimulationTruth, handleInventoryWinShareCut, isAdserverKindTenant, isInventoryTenant } from './inventory.js'; import { SIMULATION_TRUTH_SCENARIO } from '../inventory-sim/truth-scenario.js'; import { PLACE_CATALOG_VERSION, placeSystem, placeType, resolveGeoPlaces } from '../inventory-sim/geo-places.js'; import { SANDBOX_CLOCK_SCENARIO } from '../inventory-sim/sandbox-clock.js'; @@ -113,8 +113,7 @@ const TENANT_PROTOCOLS: Readonly> = { 'creative-builder': ['creative'], brand: ['brand'], si: ['sponsored_intelligence'], - 'inventory-adserver': ['media_buy'], - 'inventory-content': ['media_buy'], + ...Object.fromEntries(INVENTORY_TENANT_IDS.map(id => [id, ['media_buy']])), }; const OPERATOR_UNIT_BRIDGE_TENANTS = new Set([ @@ -1237,10 +1236,10 @@ function stripContentLengthOnWriteHead(res: Response): void { }; } -/** Declares the ad server's place system under `execution.targeting.geo_places`, +/** Declares an ad server's place system under `execution.targeting.geo_places`, * beside whatever targeting the SDK declared. */ -function advertiseGeoPlaces(mediaBuy: Record): void { - const seed = INVENTORY_TENANT_PROFILES[INVENTORY_ADSERVER_TENANT_ID].seed; +function advertiseGeoPlaces(mediaBuy: Record, tenantId: string): void { + const seed = INVENTORY_TENANT_PROFILES[tenantId].seed; const system = placeSystem(); const type = placeType(system); const countries: Record = {}; @@ -1260,7 +1259,7 @@ function advertiseGeoPlaces(mediaBuy: Record): void { current_version: PLACE_CATALOG_VERSION, supported_versions: [PLACE_CATALOG_VERSION], resolver: { - url: `${base}/${INVENTORY_ADSERVER_TENANT_ID}/geo-places`, + url: `${base}/${tenantId}/geo-places`, auth: 'none', protocol: 'adcp_geo_place_resolver_v1', }, @@ -1684,8 +1683,8 @@ function projectTenantCapabilities( ...(structured.compliance_testing && typeof structured.compliance_testing === 'object' ? structured.compliance_testing : {}), scenarios: [...INVENTORY_COMPLY_SCENARIOS], }; - if (tenantId === INVENTORY_ADSERVER_TENANT_ID && structured.media_buy && typeof structured.media_buy === 'object') { - advertiseGeoPlaces(structured.media_buy); + if (isAdserverKindTenant(tenantId) && structured.media_buy && typeof structured.media_buy === 'object') { + advertiseGeoPlaces(structured.media_buy, tenantId); } } // Every tenant: a release whose capabilities schema closes the scenario @@ -1943,8 +1942,8 @@ export function mountTenantRoutes( ...(tenantId === 'governance' ? governanceMw : tenantId === 'sales' ? salesMw : mw), tenantMcpHandler(holder, tenantId, middleware.storyboardCompat, undefined, previewHolder), ); - if (tenantId === INVENTORY_ADSERVER_TENANT_ID) { - // The place resolver the ad server's capabilities advertise. Public: it + if (isAdserverKindTenant(tenantId)) { + // The place resolver an ad server's capabilities advertise. Public: it // publishes the seed's region catalogue and nothing per caller. parent.get(`/${tenantId}/geo-places`, (req, res) => { setCORSHeaders(res); diff --git a/server/src/training-agent/tenants/signing.ts b/server/src/training-agent/tenants/signing.ts index 2ac6f3410a7..8820b608b09 100644 --- a/server/src/training-agent/tenants/signing.ts +++ b/server/src/training-agent/tenants/signing.ts @@ -29,7 +29,11 @@ interface TenantMaterial { publicJwk: AdcpJsonWebKey; } +const DEFAULT_KID_PREFIX = 'training-'; + const materials: Map = new Map(); +/** The kid prefix each cached tenant's material was created with. */ +const materialPrefixes: Map = new Map(); type AdcpKeyPurpose = 'request-signing'; @@ -41,11 +45,11 @@ interface EphemeralEd25519 { } /** Generate an ephemeral Ed25519 keypair for a tenant + purpose. */ -function generateEphemeralEd25519(tenantId: string, purpose: AdcpKeyPurpose, kidSuffix: string): EphemeralEd25519 { +function generateEphemeralEd25519(tenantId: string, purpose: AdcpKeyPurpose, kidSuffix: string, kidPrefix: string): EphemeralEd25519 { const { publicKey, privateKey } = generateKeyPairSync('ed25519'); const privateJwk = privateKey.export({ format: 'jwk' }) as Record; const publicJwk = publicKey.export({ format: 'jwk' }) as Record; - const kid = `training-${tenantId}-${kidSuffix}${randomBytes(4).toString('hex')}`; + const kid = `${kidPrefix}${tenantId}-${kidSuffix}${randomBytes(4).toString('hex')}`; const brandJwk: AdcpJsonWebKey = { ...publicJwk, kid, @@ -61,8 +65,8 @@ function generateEphemeralEd25519(tenantId: string, purpose: AdcpKeyPurpose, kid return { kid, privateJwk, publicJwk, brandJwk }; } -function generateEphemeralKey(tenantId: string): TenantMaterial { - const e = generateEphemeralEd25519(tenantId, 'request-signing', ''); +function generateEphemeralKey(tenantId: string, kidPrefix: string): TenantMaterial { + const e = generateEphemeralEd25519(tenantId, 'request-signing', '', kidPrefix); return { signingKey: { keyId: e.kid, @@ -74,14 +78,22 @@ function generateEphemeralKey(tenantId: string): TenantMaterial { } /** - * Get-or-create signing material for a tenant. Memoizes per process. + * Get-or-create signing material for a tenant. Memoizes per process. The kid + * is `-`; the prefix defaults to `training-`. */ -export function getTenantSigningMaterial(tenantId: string): TenantMaterial { +export function getTenantSigningMaterial(tenantId: string, kidPrefix?: string): TenantMaterial { + const prefix = kidPrefix ?? DEFAULT_KID_PREFIX; let m = materials.get(tenantId); - if (!m) { - m = generateEphemeralKey(tenantId); - materials.set(tenantId, m); + if (m) { + const cachedPrefix = materialPrefixes.get(tenantId); + if (cachedPrefix !== prefix) { + throw new Error(`Signing material for tenant ${tenantId} was created with kid prefix '${cachedPrefix}', not '${prefix}'`); + } + return m; } + m = generateEphemeralKey(tenantId, prefix); + materials.set(tenantId, m); + materialPrefixes.set(tenantId, prefix); return m; } @@ -110,4 +122,5 @@ export function getAggregatedPublicJwks(): { keys: AdcpJsonWebKey[] } { /** Reset state — tests only. */ export function resetTenantSigning(): void { materials.clear(); + materialPrefixes.clear(); } diff --git a/server/tests/integration/training-agent-lifecycle-tools-declaration.test.ts b/server/tests/integration/training-agent-lifecycle-tools-declaration.test.ts index c673b88edf0..f596ca7840a 100644 --- a/server/tests/integration/training-agent-lifecycle-tools-declaration.test.ts +++ b/server/tests/integration/training-agent-lifecycle-tools-declaration.test.ts @@ -47,6 +47,7 @@ const SERVING_ROUTES = [ const NON_SERVING_ROUTES = [ { name: '/inventory-adserver', path: '/api/training-agent/inventory-adserver/mcp' }, { name: '/inventory-content', path: '/api/training-agent/inventory-content/mcp' }, + { name: '/adserver-us', path: '/api/training-agent/adserver-us/mcp' }, { name: '/signals', path: '/api/training-agent/signals/mcp' }, ]; diff --git a/server/tests/unit/training-agent-inventory-adserver-us.test.ts b/server/tests/unit/training-agent-inventory-adserver-us.test.ts new file mode 100644 index 00000000000..dc5e167a741 --- /dev/null +++ b/server/tests/unit/training-agent-inventory-adserver-us.test.ts @@ -0,0 +1,563 @@ +/** + * The `/adserver-us` inventory tenant: a second ad-server-kind tenant with its + * own shipped season (three US publishers, one auction line and two guaranteed + * lines). Covers the season, that the first tenants are untouched, what the + * tenant serves, a booking round trip, the controller scenarios and what a + * buyer can read from it. + */ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import express from 'express'; +import fs from 'node:fs'; +import http from 'node:http'; +import os from 'node:os'; +import path from 'node:path'; +import { getCanonicalToolValidator } from '@adcp/sdk/schemas'; + +process.env.PUBLIC_TEST_AGENT_TOKEN = 'adserver-us-test-public-token'; + +import { stopSessionCleanup } from '../../src/training-agent/state.js'; +import { setSandboxWallClockForTesting } from '../../src/training-agent/account-sandbox.js'; +import { seasonFingerprint, readSeasonFile } from '../../src/training-agent/inventory-sim/season-file.js'; +import { TRAINING_FORMAT_LABELS } from '../../src/training-agent/product-factory.js'; +import { + INVENTORY_ADSERVER_US_TENANT_ID, + INVENTORY_COMPLY_SCENARIOS, + INVENTORY_TENANT_IDS, + INVENTORY_TENANT_PROFILES, + buildInventoryTenantConfig, + isAdserverKindTenant, +} from '../../src/training-agent/tenants/inventory.js'; +import { + ADSERVER_SEASON, + ADSERVER_US_SEASON, + CONTENT_SEASON, + ENGINE_VERSION, +} from '../../src/training-agent/inventory-sim/engine/index.js'; +import { placeSystem, placeType } from '../../src/training-agent/inventory-sim/geo-places.js'; + +const DAY_MS = 24 * 60 * 60 * 1000; +/** Where an unpinned sandbox clock starts. */ +const WALL_CLOCK = '2026-11-20T09:00:00Z'; +const TENANT = 'adserver-us'; +const FIRST_TENANT = 'inventory-adserver'; +const ACCOUNT = { brand: { domain: 'inventory-buyer.example' }, operator: 'inventory-buyer.example', sandbox: true }; +const BRAND = { domain: 'inventory-buyer.example' }; +/** The buyer used where responses are scanned for wording: its own strings + * must not trip the scan when a response echoes them. */ +const PLAIN_ACCOUNT = { brand: { domain: 'acme-buyer.com' }, operator: 'acme-buyer.com', sandbox: true }; + +type Structured = Record; + +function expectCanonical(tool: string, value: Structured, adcpVersion = '3.2'): void { + const validate = getCanonicalToolValidator(tool, 'sync', { adcpVersion }) as + | (((payload: unknown) => boolean) & { errors?: unknown }) + | undefined; + expect(validate, `no canonical validator for ${tool}`).toBeDefined(); + if (value.adcp_error || value.__envelope) throw new Error(`${tool} failed: ${JSON.stringify(value).slice(0, 1500)}`); + const ok = validate!(value); + expect(ok, `${tool}: ${JSON.stringify(validate!.errors)?.slice(0, 1500)}`).toBe(true); +} + +function expectCanonicalAll(tool: string, value: Structured): void { + for (const version of ['3.2', '3.3.0-rc.3']) expectCanonical(tool, value, version); +} + +/** The publishers' own domains, the only strings that may carry the word + * 'example', and only as whole strings. */ +const PUBLISHER_DOMAINS = ['northstar.example', 'meridian.example', 'harbor.example']; +const PUBLISHER_DOMAIN_PATTERN = new RegExp(`(? domain.replace('.', '\\.')).join('|')})(?![\\w.-])`, 'g'); + +const BANNED = /\b(sim\w*|test\w*|game\w*|scenario\w*|fault\w*|m2|draft\w*|demo\w*|example\w*|stand-in|milestone\w*)\b/i; + +function stringsOf(value: unknown, into: string[] = []): string[] { + if (typeof value === 'string') into.push(value); + else if (Array.isArray(value)) for (const item of value) stringsOf(item, into); + else if (value && typeof value === 'object') { + for (const [key, item] of Object.entries(value)) { + into.push(key); + stringsOf(item, into); + } + } + return into; +} + +describe('adserver-us inventory tenant', () => { + let server: http.Server; + let baseUrl: string; + let rpcId = 0; + let keyCounter = 0; + const key = (label: string) => `adserver-us-${label}-${String(++keyCounter).padStart(6, '0')}`; + + const call = async (tenant: string, name: string, args: Record, token: string): Promise => { + rpcId += 1; + const response = await fetch(`${baseUrl}/${tenant}/mcp`, { + method: 'POST', + headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', authorization: `Bearer ${token}` }, + body: JSON.stringify({ jsonrpc: '2.0', id: rpcId, method: 'tools/call', params: { name, arguments: args } }), + }); + const envelope = await response.json() as Record; + return (envelope.result?.structuredContent ?? { __envelope: envelope }) as Structured; + }; + + const provision = async (token: string, account: Record = ACCOUNT) => { + const synced = await call(TENANT, 'sync_accounts', { + idempotency_key: key('provision'), + accounts: [{ ...account, billing: 'operator' }], + }, token); + if (synced.adcp_error || synced.__envelope) throw new Error(`sync_accounts failed: ${JSON.stringify(synced).slice(0, 500)}`); + }; + + const control = (token: string, scenario: string, params: Record, on = TENANT, account: Record = ACCOUNT) => + call(on, 'comply_test_controller', { scenario, account, params }, token); + const advanceTo = (token: string, to: string, on = TENANT) => control(token, 'sandbox_clock', { operation: 'advance_time', to }, on); + + const flightStart = new Date(Date.parse(WALL_CLOCK.slice(0, 10)) + 2 * DAY_MS); + const flightEnd = new Date(flightStart.getTime() + 30 * DAY_MS); + const day = (date: Date) => date.toISOString().slice(0, 10); + + const productsOf = (token: string, account: Record = ACCOUNT, on = TENANT) => call(on, 'get_products', { + buying_mode: 'wholesale', account, brand: account.brand, + filters: { start_date: day(flightStart), end_date: day(new Date(flightEnd.getTime() - DAY_MS)) }, + }, token); + + const pricingOptionOf = (products: Structured, productId: string): string => + products.products.find((product: Structured) => product.product_id === productId).pricing_options[0].pricing_option_id; + + /** Books the Meridian guaranteed line and the Northstar auction line in one + * buy each, and returns both package ids. */ + const bookBoth = async (token: string, account: Record = ACCOUNT, on = TENANT) => { + const products = await productsOf(token, account, on); + const guaranteed = await call(on, 'create_media_buy', { + idempotency_key: key('guaranteed'), account, brand: account.brand, + start_time: flightStart.toISOString(), end_time: flightEnd.toISOString(), + packages: [{ product_id: 'meridian_guaranteed', pricing_option_id: pricingOptionOf(products, 'meridian_guaranteed'), budget: 1000, impressions: 100_000 }], + }, token); + expectCanonical('create_media_buy', guaranteed); + const auction = await call(on, 'create_media_buy', { + idempotency_key: key('auction'), account, brand: account.brand, + start_time: flightStart.toISOString(), end_time: flightEnd.toISOString(), + packages: [{ product_id: 'northstar_auction', pricing_option_id: pricingOptionOf(products, 'northstar_auction'), budget: 6000, bid_price: 3 }], + }, token); + expectCanonical('create_media_buy', auction); + return { guaranteed, auction }; + }; + + beforeAll(async () => { + const { createTrainingAgentRouter } = await import('../../src/training-agent/index.js'); + const app = express(); + app.use(express.json({ limit: '5mb' })); + app.use('/api/training-agent', createTrainingAgentRouter({ disableRateLimit: true })); + server = http.createServer(app); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const address = server.address(); + if (!address || typeof address === 'string') throw new Error('Missing test server address'); + baseUrl = `http://127.0.0.1:${address.port}/api/training-agent`; + const offset = Date.parse(WALL_CLOCK) - Date.now(); + setSandboxWallClockForTesting(() => Date.now() + offset); + }, 90_000); + + afterAll(async () => { + setSandboxWallClockForTesting(); + stopSessionCleanup(); + if (!server) return; + server.closeAllConnections(); + await new Promise(resolve => server.close(() => resolve())); + }); + + describe('season', () => { + it('round-trips through the strict season-file loader', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'adserver-us-season-')); + const file = path.join(dir, 'season.json'); + try { + fs.writeFileSync(file, JSON.stringify(ADSERVER_US_SEASON)); + const loaded = readSeasonFile(file, { formats: TRAINING_FORMAT_LABELS }); + expect(loaded).toEqual(ADSERVER_US_SEASON); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } + }); + + it('is US only, in USD', () => { + expect(ADSERVER_US_SEASON.seed_id).toBe('adserver-us-2027'); + expect(ADSERVER_US_SEASON.currency).toBe('USD'); + expect(ADSERVER_US_SEASON.regions).toHaveLength(3); + for (const region of ADSERVER_US_SEASON.regions) expect(region.country).toBe('US'); + }); + + it('sells an auction line and two guaranteed lines at fixed rates', () => { + const byId = new Map(ADSERVER_US_SEASON.products.map(product => [product.product_id, product])); + expect([...byId.keys()].sort()).toEqual(['harbor_guaranteed', 'meridian_guaranteed', 'northstar_auction']); + const northstar = byId.get('northstar_auction')!; + expect(northstar.delivery_type).toBe('non_guaranteed'); + expect(northstar).not.toHaveProperty('rate_cpm'); + expect(byId.get('meridian_guaranteed')).toMatchObject({ delivery_type: 'guaranteed', rate_cpm: 5 }); + expect(byId.get('harbor_guaranteed')).toMatchObject({ delivery_type: 'guaranteed', rate_cpm: 6 }); + expect(ADSERVER_US_SEASON.placements.find(placement => placement.placement_id === 'northstar')!.floor_cpm).toBe(2); + expect(ADSERVER_US_SEASON.properties.map(property => property.publisher_id).sort()).toEqual(['harbor', 'meridian', 'northstar']); + }); + + it('has a fingerprint of its own', () => { + const own = seasonFingerprint(ADSERVER_US_SEASON); + expect(own).not.toBe(seasonFingerprint(ADSERVER_SEASON)); + expect(own).not.toBe(seasonFingerprint(CONTENT_SEASON)); + }); + }); + + describe('the first inventory tenants', () => { + it('still run their own seasons on the same engine', () => { + expect(INVENTORY_TENANT_PROFILES[FIRST_TENANT].seed).toBe(ADSERVER_SEASON); + expect(INVENTORY_TENANT_PROFILES['inventory-content'].seed).toBe(CONTENT_SEASON); + expect(ENGINE_VERSION).toBe('3'); + }); + }); + + describe('listing and serving', () => { + const TOKEN = 'demo-adserver-us-serving-v1'; + beforeAll(() => provision(TOKEN)); + + it('lists the tenant and classes it as an ad server', () => { + expect(INVENTORY_TENANT_IDS).toContain(TENANT); + expect(INVENTORY_ADSERVER_US_TENANT_ID).toBe(TENANT); + expect(isAdserverKindTenant(TENANT)).toBe(true); + expect(isAdserverKindTenant(FIRST_TENANT)).toBe(true); + expect(isAdserverKindTenant('inventory-content')).toBe(false); + expect(INVENTORY_TENANT_PROFILES[TENANT].seed).toBe(ADSERVER_US_SEASON); + }); + + it('declares a media-buy seller with every controller scenario and its own resolver', async () => { + const capabilities = await call(TENANT, 'get_adcp_capabilities', {}, TOKEN); + expectCanonicalAll('get_adcp_capabilities', capabilities); + expect(capabilities.supported_protocols).toContain('media_buy'); + expect(capabilities.compliance_testing.scenarios).toEqual(expect.arrayContaining([...INVENTORY_COMPLY_SCENARIOS])); + const targeting = capabilities.media_buy.execution.targeting; + const system = placeSystem(); + expect(Object.keys(targeting.geo_places)).toEqual([system]); + expect(targeting.geo_places[system].countries).toEqual({ US: [placeType(system)] }); + expect(targeting.geo_places[system].catalog.resolver).toEqual({ + url: expect.stringMatching(/\/adserver-us\/geo-places$/), auth: 'none', protocol: 'adcp_geo_place_resolver_v1', + }); + }); + + it('advertises the same place system as the first ad server', async () => { + const us = await call(TENANT, 'get_adcp_capabilities', {}, TOKEN); + const first = await call(FIRST_TENANT, 'get_adcp_capabilities', {}, TOKEN); + expect(Object.keys(us.media_buy.execution.targeting.geo_places)).toEqual(Object.keys(first.media_buy.execution.targeting.geo_places)); + expect(Object.keys(us.media_buy.execution.targeting.geo_places)).toEqual([placeSystem()]); + const usBody = await (await fetch(`${baseUrl}/${TENANT}/geo-places?q=us&country=US`)).json() as Structured; + const firstBody = await (await fetch(`${baseUrl}/${FIRST_TENANT}/geo-places?q=us&country=US`)).json() as Structured; + expect(usBody.system).toBe(firstBody.system); + }); + + it('has each ad-server tenant name its own resolver', async () => { + const first = await call(FIRST_TENANT, 'get_adcp_capabilities', {}, TOKEN); + const system = placeSystem(); + expect(first.media_buy.execution.targeting.geo_places[system].catalog.resolver.url).toMatch(/\/inventory-adserver\/geo-places$/); + expect(first.media_buy.execution.targeting.geo_places[system].catalog.resolver.url).not.toContain('/adserver-us/'); + }); + + it('serves the three US regions from its resolver, and nothing for another country', async () => { + const resolver = `${baseUrl}/${TENANT}/geo-places`; + const all = await fetch(`${resolver}?q=us&country=US`); + expect(all.status).toBe(200); + const body = await all.json() as Structured; + expect(body.system).toBe(placeSystem()); + expect(body.matches.map((match: Structured) => match.value).sort()).toEqual(['us_northeast', 'us_south', 'us_west']); + for (const match of body.matches) expect(match.country).toBe('US'); + + const byValue = await (await fetch(`${resolver}?value=us_west&country=US`)).json() as Structured; + expect(byValue.matches.map((match: Structured) => match.value)).toEqual(['us_west']); + + // The resolver answers an unserved country with an empty page, not an error. + const canada = await fetch(`${resolver}?q=us&country=CA`); + expect(canada.status).toBe(200); + expect((await canada.json() as Structured).matches).toEqual([]); + const canadianValue = await (await fetch(`${resolver}?value=ca&country=CA`)).json() as Structured; + expect(canadianValue.matches).toEqual([]); + + // A query needs q or value. + expect((await fetch(`${resolver}?country=US`)).status).toBe(400); + }); + + it('returns exactly three products, priced in USD', async () => { + const result = await productsOf(TOKEN); + expectCanonical('get_products', result); + expect(result.products.map((product: Structured) => product.product_id).sort()).toEqual(['harbor_guaranteed', 'meridian_guaranteed', 'northstar_auction']); + for (const product of result.products as Structured[]) { + for (const option of product.pricing_options) expect(option.currency).toBe('USD'); + } + const byId = (id: string) => result.products.find((product: Structured) => product.product_id === id); + expect(byId('meridian_guaranteed').delivery_type).toBe('guaranteed'); + expect(byId('meridian_guaranteed').pricing_options[0].fixed_price).toBe(5); + expect(byId('harbor_guaranteed').delivery_type).toBe('guaranteed'); + expect(byId('harbor_guaranteed').pricing_options[0].fixed_price).toBe(6); + expect(byId('northstar_auction').delivery_type).toBe('non_guaranteed'); + expect(byId('northstar_auction').pricing_options[0].floor_price).toBe(2); + }); + }); + + describe('booking', () => { + const TOKEN = 'demo-adserver-us-booking-v1'; + beforeAll(() => provision(TOKEN)); + + it('books a guaranteed and an auction package, runs the market forward and reads delivery', async () => { + const { guaranteed, auction } = await bookBoth(TOKEN); + expect(guaranteed.packages[0].impressions).toBe(100_000); + expect(guaranteed.packages[0].budget).toBe(1000); + + const listed = await call(TENANT, 'get_media_buys', { account: ACCOUNT, media_buy_ids: [guaranteed.media_buy_id, auction.media_buy_id] }, TOKEN); + expectCanonical('get_media_buys', listed); + expect(listed.media_buys).toHaveLength(2); + + const advanced = await advanceTo(TOKEN, new Date(flightStart.getTime() + 5 * DAY_MS).toISOString()); + expect(advanced.success, JSON.stringify(advanced)).toBe(true); + expect(advanced.simulated.seed_id).toBe('adserver-us-2027'); + expect(advanced.simulated.season_fingerprint).toBe(seasonFingerprint(ADSERVER_US_SEASON)); + + const delivery = await call(TENANT, 'get_media_buy_delivery', { + account: ACCOUNT, media_buy_ids: [guaranteed.media_buy_id, auction.media_buy_id], + }, TOKEN); + expectCanonical('get_media_buy_delivery', delivery); + const [g, a] = delivery.media_buy_deliveries; + expect(g.totals.impressions).toBeGreaterThan(0); + expect(g.totals.impressions).toBeLessThanOrEqual(100_000); + expect(a.totals.impressions).toBeGreaterThan(0); + // The guaranteed line bills at its fixed rate and the auction line at the bid. + expect(g.totals.spend).toBeCloseTo((g.totals.impressions * 5) / 1000, 0); + expect(a.totals.spend).toBeCloseTo((a.totals.impressions * 3) / 1000, 0); + }); + + it('wins nothing for a bid below the Northstar floor', async () => { + const token = 'demo-adserver-us-floor-v1'; + await provision(token); + const products = await productsOf(token); + const low = await call(TENANT, 'create_media_buy', { + idempotency_key: key('low-bid'), account: ACCOUNT, brand: BRAND, + start_time: flightStart.toISOString(), end_time: flightEnd.toISOString(), + packages: [{ product_id: 'northstar_auction', pricing_option_id: pricingOptionOf(products, 'northstar_auction'), budget: 1000, bid_price: 1 }], + }, token); + expectCanonical('create_media_buy', low); + expect((await advanceTo(token, new Date(flightStart.getTime() + 3 * DAY_MS).toISOString())).success).toBe(true); + const delivery = await call(TENANT, 'get_media_buy_delivery', { account: ACCOUNT, media_buy_ids: [low.media_buy_id] }, token); + expectCanonical('get_media_buy_delivery', delivery); + expect(delivery.media_buy_deliveries[0].totals.impressions).toBe(0); + }); + }); + + describe('controller scenarios', () => { + it('lists the same scenarios as the other inventory tenants', async () => { + const token = 'demo-adserver-us-scenarios-v1'; + await provision(token); + const listed = await call(TENANT, 'comply_test_controller', { scenario: 'list_scenarios', account: ACCOUNT }, token); + expect([...listed.scenarios].sort()).toEqual([...INVENTORY_COMPLY_SCENARIOS].sort()); + const first = await call(FIRST_TENANT, 'comply_test_controller', { scenario: 'list_scenarios', account: ACCOUNT }, token); + expect([...listed.scenarios].sort()).toEqual([...first.scenarios].sort()); + }); + + describe('win_share_cut', () => { + let counter = 0; + const afterFirstDay = new Date(flightStart.getTime() + DAY_MS).toISOString(); + const cut = (token: string, params: Record = {}) => + control(token, 'win_share_cut', { + operation: 'set', cut_id: 'outbid-1', win_share: 0.5, start_date: day(flightStart), end_date: day(flightEnd), ...params, + }); + /** A fresh principal's two buys after the first serving day. */ + const firstDay = async (withCut: boolean) => { + const token = `demo-adserver-us-cut-t${++counter}-v1`; + await provision(token); + const { guaranteed, auction } = await bookBoth(token); + if (withCut) expect((await cut(token)).success).toBe(true); + expect((await advanceTo(token, afterFirstDay)).success).toBe(true); + const truth = await control(token, 'simulation_truth', {}); + expect(truth.success, JSON.stringify(truth).slice(0, 400)).toBe(true); + const delivered = (packageId: string) => truth.packages.find((pkg: Structured) => pkg.package_id === packageId).delivered.impressions as number; + return { + truth, + guaranteed: delivered(guaranteed.packages[0].package_id), + auction: delivered(auction.packages[0].package_id), + }; + }; + + it('halves what the auction line wins and reports the cut, leaving the guaranteed line alone', async () => { + const plain = await firstDay(false); + const cutRun = await firstDay(true); + expect(plain.auction).toBeGreaterThan(10_000); + expect(cutRun.auction / plain.auction).toBeGreaterThan(0.49); + expect(cutRun.auction / plain.auction).toBeLessThan(0.51); + expect(cutRun.guaranteed).toBe(plain.guaranteed); + + expect(plain.truth).not.toHaveProperty('win_share_cuts'); + expect(cutRun.truth.win_share_cuts).toEqual([{ + cut_id: 'outbid-1', win_share: 0.5, start_date: day(flightStart), end_date: day(flightEnd), + withheld_impressions: plain.auction - cutRun.auction, + }]); + expect(cutRun.truth.win_share_cuts[0].withheld_impressions).toBeGreaterThan(0); + expectCanonicalAll('comply_test_controller', cutRun.truth); + }); + }); + + it('keeps its market apart from the first ad server, and reset_state clears both', async () => { + const token = 'demo-adserver-us-markets-v1'; + await provision(token); + const { guaranteed } = await bookBoth(token); + + const firstBuys = await call(FIRST_TENANT, 'get_media_buys', { account: ACCOUNT }, token); + expect(firstBuys.media_buys).toHaveLength(0); + const buys = await call(TENANT, 'get_media_buys', { account: ACCOUNT }, token); + expect(buys.media_buys).toHaveLength(2); + expect(buys.media_buys.map((buy: Structured) => buy.media_buy_id)).toContain(guaranteed.media_buy_id); + + const firstProducts = await productsOf(token, ACCOUNT, FIRST_TENANT); + const booked = await call(FIRST_TENANT, 'create_media_buy', { + idempotency_key: key('first'), account: ACCOUNT, brand: BRAND, + start_time: flightStart.toISOString(), end_time: flightEnd.toISOString(), + packages: [{ product_id: 'ros_display_guaranteed', pricing_option_id: pricingOptionOf(firstProducts, 'ros_display_guaranteed'), budget: 1000, impressions: 40_000 }], + }, token); + expectCanonical('create_media_buy', booked); + const firstAfter = await call(FIRST_TENANT, 'get_media_buys', { account: ACCOUNT }, token); + expect(firstAfter.media_buys).toHaveLength(1); + const usAfter = await call(TENANT, 'get_media_buys', { account: ACCOUNT }, token); + const productsIn = (buys: Structured[]) => buys.flatMap(buy => buy.packages.map((pkg: Structured) => pkg.product_id)).sort(); + expect(productsIn(usAfter.media_buys)).toEqual(['meridian_guaranteed', 'northstar_auction']); + expect(productsIn(firstAfter.media_buys)).toEqual(['ros_display_guaranteed']); + + const reset = await call(TENANT, 'comply_test_controller', { scenario: 'reset_state', account: ACCOUNT }, token); + expect(reset.success, JSON.stringify(reset).slice(0, 500)).toBe(true); + expect((await call(TENANT, 'get_media_buys', { account: ACCOUNT }, token)).media_buys).toHaveLength(0); + expect((await call(FIRST_TENANT, 'get_media_buys', { account: ACCOUNT }, token)).media_buys).toHaveLength(0); + }); + + it('starts the clock of an unused sandbox on the tenant, then refuses while it holds a buy', async () => { + const fresh = 'demo-adserver-us-start-fresh-v1'; + await provision(fresh); + const started = await control(fresh, 'sandbox_clock', { operation: 'start', to: '2026-11-05T00:00:00Z' }); + expect(started).toMatchObject({ success: true, simulated: { simulated_now: '2026-11-05T00:00:00.000Z', pinned: true } }); + expect(started.simulated.seed_id).toBe('adserver-us-2027'); + expect(started.simulated.season_fingerprint).toBe(seasonFingerprint(ADSERVER_US_SEASON)); + expect(started.simulated.engine_version).toBe(ENGINE_VERSION); + + const held = 'demo-adserver-us-start-held-v1'; + await provision(held); + await bookBoth(held); + for (const on of [TENANT, FIRST_TENANT]) { + const refused = await control(held, 'sandbox_clock', { operation: 'start', to: '2026-11-05T00:00:00Z' }, on); + expect(refused.success, on).toBe(false); + expect(refused.error, on).toBe('INVALID_TRANSITION'); + expect(refused.error_detail, on).toContain('adserver-us holds your media buys, creatives or seeded products'); + } + }); + }); + + describe('what a buyer can read', () => { + const TOKEN = 'demo-adserver-us-wording-v1'; + const HOST = /test-agent\.adcontextprotocol\.org/g; + /** Platform-owned names: the controller tool, its capability block and the + * scenario names every inventory tenant declares. */ + const PLATFORM_NAMES = new RegExp( + ['compliance_testing', 'comply_test_controller', ...INVENTORY_COMPLY_SCENARIOS].map(name => name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|'), + 'g', + ); + const scrub = (text: string) => text.replace(HOST, '').replace(PLATFORM_NAMES, '').replace(PUBLISHER_DOMAIN_PATTERN, ''); + const hits = (text: string) => [...scrub(text).matchAll(new RegExp(BANNED.source, 'gi'))].map(match => match[0]); + + const initialize = async (): Promise => { + const response = await fetch(`${baseUrl}/${TENANT}/mcp`, { + method: 'POST', + headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', authorization: `Bearer ${TOKEN}` }, + body: JSON.stringify({ + jsonrpc: '2.0', id: 1, method: 'initialize', + params: { protocolVersion: '2025-03-26', clientInfo: { name: 'buyer-agent', version: '1.0.0' }, capabilities: {} }, + }), + }); + const text = await response.text(); + const data = text.startsWith('{') ? text : text.split('\n').find(line => line.startsWith('data:'))?.slice(5) ?? '{}'; + return JSON.parse(data) as Structured; + }; + + beforeAll(() => provision(TOKEN, PLAIN_ACCOUNT)); + + it('scans for what it should, and strips only the platform names', () => { + expect(hits('a simulated example, scenario one')).toEqual(['simulated', 'example', 'scenario']); + expect(hits('https://test-agent.adcontextprotocol.org/x comply_test_controller sandbox_clock simulation_truth')).toEqual([]); + expect(hits('a test of the tenant')).toEqual(['test']); + }); + + it('allows the three publisher domains as whole strings and no other example', () => { + expect(hits('northstar.example meridian.example harbor.example')).toEqual([]); + expect(hits('"domain":"harbor.example"')).toEqual([]); + for (const other of ['other.example', 'northstar.example.com', 'www.northstar.example', 'xmeridian.example', 'harbor.examples', 'inventory-buyer.example', 'example']) { + expect(hits(other), other).not.toEqual([]); + } + }); + + it('keeps the season, tenant id and label free of the banned words', () => { + expect(hits(JSON.stringify(ADSERVER_US_SEASON))).toEqual([]); + for (const text of stringsOf(ADSERVER_US_SEASON)) { + if (PUBLISHER_DOMAINS.includes(text)) continue; + expect(text, text).not.toMatch(BANNED); + } + expect(ADSERVER_US_SEASON.properties.map(property => property.domain).sort()).toEqual([...PUBLISHER_DOMAINS].sort()); + for (const product of ADSERVER_US_SEASON.products) expect(product.product_id).not.toMatch(BANNED); + expect(TENANT).not.toMatch(BANNED); + expect(INVENTORY_ADSERVER_US_TENANT_ID).not.toMatch(BANNED); + expect(INVENTORY_TENANT_PROFILES[TENANT].seed.seed_id).not.toMatch(BANNED); + }); + + it('keeps the label free of the banned words', () => { + // The label is configuration, not a response: read it through the tenant config builder. + const { config } = buildInventoryTenantConfig(TENANT, 'https://tenant.invalid'); + expect(config.label).toBeDefined(); + expect(config.label).not.toMatch(BANNED); + }); + + it('serves clean initialize, capabilities, products, formats and resolver bodies', async () => { + const init = await initialize(); + expect(init.result?.serverInfo, JSON.stringify(init).slice(0, 400)).toBeDefined(); + expect(init.result.serverInfo.name).not.toBe('adcp-training-agent'); + expect(hits(JSON.stringify(init.result.serverInfo))).toEqual([]); + + const capabilities = await call(TENANT, 'get_adcp_capabilities', {}, TOKEN); + // The controller's capability block is the platform's own: its key and + // the scenario names every inventory tenant declares. + const { compliance_testing: _controller, ...declared } = capabilities; + expect(hits(JSON.stringify(declared))).toEqual([]); + + const products = await productsOf(TOKEN, PLAIN_ACCOUNT); + expectCanonical('get_products', products); + expect(hits(JSON.stringify(products))).toEqual([]); + + const formats = await call(TENANT, 'list_creative_formats', {}, TOKEN); + expect(formats.adcp_error ?? formats.__envelope).toBeUndefined(); + expect(hits(JSON.stringify(formats))).toEqual([]); + + const resolver = await (await fetch(`${baseUrl}/${TENANT}/geo-places?q=us&country=US`)).text(); + expect(hits(resolver)).toEqual([]); + }); + + it('serves clean booking, listing and delivery bodies', async () => { + // The buyer is the plain one: the main buyer's own strings would trip the scan when echoed. + const { guaranteed, auction } = await bookBoth(TOKEN, PLAIN_ACCOUNT); + const ids = [guaranteed.media_buy_id, auction.media_buy_id]; + expect(hits(JSON.stringify(guaranteed))).toEqual([]); + expect(hits(JSON.stringify(auction))).toEqual([]); + + const listed = await call(TENANT, 'get_media_buys', { account: PLAIN_ACCOUNT, media_buy_ids: ids }, TOKEN); + expectCanonical('get_media_buys', listed); + expect(hits(JSON.stringify(listed))).toEqual([]); + + const advanced = await control(TOKEN, 'sandbox_clock', { operation: 'advance_time', to: new Date(flightStart.getTime() + 5 * DAY_MS).toISOString() }, TENANT, PLAIN_ACCOUNT); + expect(advanced.success, JSON.stringify(advanced)).toBe(true); + const delivery = await call(TENANT, 'get_media_buy_delivery', { account: PLAIN_ACCOUNT, media_buy_ids: ids }, TOKEN); + expectCanonical('get_media_buy_delivery', delivery); + expect(hits(JSON.stringify(delivery))).toEqual([]); + }); + + it('has a signing key id without the platform prefix', async () => { + const kid = buildInventoryTenantConfig(TENANT, 'http://localhost').config.signingKey.keyId; + expect(kid).toBeTruthy(); + expect(kid).not.toContain('training'); + expect(kid).not.toMatch(BANNED); + const jwks = await (await fetch(`${baseUrl}/.well-known/jwks.json`)).json() as { keys: Array<{ kid?: string }> }; + expect(jwks.keys.map(entry => entry.kid)).toContain(kid); + }); + }); +});