{"version":3,"file":"index.cjs","names":["VALIDATED_INPUT_CONTEXT_KEY","HonoRequest","buildInertiaPage","serializePage","acceptsJson","initialPageElement","mergeInertiaVary","withDefaultHeaders","asRecord","parseRequestBody","RuntimeController","AuthenticationException","readInitialPage","getNestedValue","resolveJobName","getJob","getTestLifecycleHooks","runtimePromise"],"sources":["../src/auth.ts","../src/controller.ts","../src/testing-header.ts","../src/http.ts","../src/queue.ts","../src/mail.ts","../src/database.ts","../src/event.ts","../src/agent.ts","../src/ai.ts","../src/test-app.ts","../src/plugin-test-utils.ts"],"sourcesContent":["export interface MockUser {\n  id: number\n  email: string\n  password: string\n  emailVerifiedAt?: Date | null\n  getAuthIdentifier(): number\n  getAuthPassword(): string\n}\n\nexport interface MockUserProvider<T extends MockUser = MockUser> {\n  retrieveById: (id: unknown) => Promise<T | null>\n  retrieveByCredentials: (credentials: Record<string, unknown>) => Promise<T | null>\n  validateCredentials: (user: T, credentials: Record<string, unknown>) => Promise<boolean>\n  getId: (user: T) => unknown\n}\n\nexport interface MockAuthContext<User = { id: number; name: string }> {\n  check: () => Promise<boolean>\n  guest: () => Promise<boolean>\n  user: <T = User>() => Promise<T | null>\n  userOrFail: <T = User>() => Promise<T>\n  id: () => Promise<unknown>\n  login: <T = User>(user: T, remember?: boolean) => Promise<void>\n  logout: () => Promise<void>\n  attempt: (credentials: Record<string, unknown>, remember?: boolean) => Promise<boolean>\n  // oxlint-disable-next-line no-unused-vars -- phantom type parameter, kept because it is part of the public signature\n  guard: <T = User>(name?: string) => any\n  session: <T = unknown>() => T | undefined\n}\n\nexport function createMockUser(data: {\n  id: number\n  email: string\n  password: string\n  emailVerifiedAt?: Date | null\n}): MockUser {\n  return {\n    ...data,\n    getAuthIdentifier() {\n      return this.id\n    },\n    getAuthPassword() {\n      return this.password\n    },\n  }\n}\n\nexport function createMockProvider<T extends MockUser>(users: T[]): MockUserProvider<T> {\n  return {\n    retrieveById: async (id) => users.find((u) => u.id === id) ?? null,\n    retrieveByCredentials: async (credentials) => {\n      return users.find((u) => u.email === credentials.email) ?? null\n    },\n    validateCredentials: async (user, credentials) => {\n      return user.password === credentials.password\n    },\n    getId: (user) => user.id,\n  }\n}\n\nexport function createMockAuthContext(options: {\n  isAuthenticated: boolean\n  user?: { id: number; name: string }\n}): MockAuthContext {\n  const defaultUser = { id: 1, name: 'Test User' }\n  const user = options.user ?? defaultUser\n\n  return {\n    check: async () => options.isAuthenticated,\n    guest: async () => !options.isAuthenticated,\n    user: async <T = typeof user>() => (options.isAuthenticated ? (user as T) : null),\n    userOrFail: async <T = typeof user>() => {\n      if (!options.isAuthenticated) throw new Error('Unauthenticated.')\n      return user as T\n    },\n    id: async () => (options.isAuthenticated ? user.id : null),\n    login: async <_T = typeof user>(_userValue: _T, _remember?: boolean) => {},\n    logout: async () => {},\n    attempt: async (_credentials: Record<string, unknown>, _remember?: boolean) => false,\n    guard: <_T = typeof user>(_name?: string) => ({}),\n    session: <_T = unknown>() => undefined,\n  }\n}\n","import { HonoRequest } from 'hono/request'\nimport type {\n  Context,\n  InertiaPagePayload,\n  InertiaPropsInput,\n  InertiaResponse,\n  ResolvedInertiaProps,\n  ResolvedSharedInertiaProps,\n} from '@guren/server'\nimport {\n  asRecord,\n  parseRequestBody,\n  type RequestBodyContext,\n  VALIDATED_INPUT_CONTEXT_KEY,\n  type ValidatedInputRecord,\n} from '@guren/server/internal/request'\nimport { initialPageElement, readInitialPage } from '@guren/server/internal/inertia-page'\nimport {\n  AuthenticationException,\n  Controller as RuntimeController,\n  type InertiaPageContractLike,\n  type InertiaResponseOptions,\n  JsonResource,\n  Resource,\n  ServiceProvider,\n  ValidationException,\n  acceptsJson,\n  always,\n  collect,\n  defer,\n  defineModule,\n  definePlugin,\n  formatValidationErrors,\n  buildInertiaPage,\n  live,\n  mergeInertiaVary,\n  serializePage,\n  withDefaultHeaders,\n} from '@guren/server/internal/testing'\n\nexport interface ControllerContext {\n  var?: {\n    container?: {\n      make: <T = unknown>(key: string) => T\n      has?: (key: string) => boolean\n    }\n    [key: string]: unknown\n  }\n  req: {\n    raw: Request\n    path: string\n    url: string\n    method: string\n    query: (key?: string) => string | undefined | Record<string, string>\n    queries: () => Record<string, string[]>\n    param: (key?: string) => string | Record<string, string> | undefined\n    header: (name: string) => string | undefined\n    json: HonoRequest['json']\n    parseBody: HonoRequest['parseBody']\n  }\n  get: (key: string) => unknown\n  set: (key: string, value: unknown) => void\n  header: (name: string, value: string) => void\n  status: (code: number) => void\n}\n\nexport type InertiaPayload = InertiaPagePayload\n\n/**\n * Context values that stand in for the route contract middleware, for a controller\n * action reading `this.validated()`: spread into `createControllerContext`'s\n * `contextValues`. Values are passed through as the schemas would have parsed them.\n */\nexport function contractInput(input: {\n  route?: string\n  params?: Record<string, unknown>\n  query?: Record<string, unknown>\n  body?: unknown\n}): Record<string, unknown> {\n  return { [VALIDATED_INPUT_CONTEXT_KEY]: { route: undefined, ...input } satisfies ValidatedInputRecord }\n}\n\nexport function createControllerContext(\n  url: string,\n  init: RequestInit = {},\n  contextValues: Record<string, unknown> = {},\n): ControllerContext {\n  const request = new Request(url, init)\n  const parsedUrl = new URL(request.url)\n  const store = new Map<string, unknown>(Object.entries(contextValues))\n  // Context values double as bindings. An unbound key is `undefined` rather than the\n  // Container's throw; `has()` is what lets `gate` or `i18n` seeded here resolve.\n  const container = {\n    make: <T = unknown>(key: string) => store.get(key) as T,\n    has: (key: string) => store.has(key),\n  }\n\n  // One HonoRequest per request, as a live one has: its body cache is what lets\n  // `validateBody()` and `file()` read the same body in one action.\n  const honoRequest = new HonoRequest(request)\n\n  const req = {\n    raw: request,\n    path: parsedUrl.pathname,\n    url: request.url,\n    method: request.method,\n    query: (key?: string) => (key === undefined ? honoRequest.query() : honoRequest.query(key)),\n    queries: () => honoRequest.queries(),\n    // Hono answers `{}` on a route with no parameters, and `validateParams()` hands it on as is.\n    param: () => ({}),\n    header: (name: string) => request.headers.get(name) ?? undefined,\n    json: honoRequest.json.bind(honoRequest),\n    parseBody: honoRequest.parseBody.bind(honoRequest),\n  }\n\n  return {\n    // Hono's `c.var` reads the same store `c.set()` writes.\n    get var() {\n      return { ...Object.fromEntries(store), container }\n    },\n    req,\n    get: (key: string) => store.get(key),\n    set: (key: string, value: unknown) => { store.set(key, value) },\n    header: () => {},\n    status: () => {},\n  }\n}\n\n/**\n * `@guren/server` is loaded lazily and memoized: this module is the factory behind\n * `vi.mock('@guren/core', …)`, so a top-level import of either specifier is circular\n * under vitest's hoisting (TDZ on the hoisted binding). A suite that mocks\n * `@guren/server` itself gets a mock without `view()`/`viteAsset`.\n */\ntype ServerModule = typeof import('@guren/server')\nlet loadedServer: ServerModule | undefined\nlet serverModulePromise: Promise<ServerModule> | undefined\n\nfunction loadServer(): Promise<ServerModule> {\n  serverModulePromise ??= import('@guren/server').then((mod) => {\n    loadedServer = mod\n    return mod\n  })\n  return serverModulePromise\n}\n\n/**\n * The Inertia response without a booted app: no shared props, root document, asset\n * version or SSR, which is why the mock keeps it. The page object (prop\n * resolution included), the JSON-or-HTML choice and the payload escaping are the\n * engine's own.\n */\nasync function renderInertia(\n  request: Request,\n  componentOrPage: string | InertiaPageContractLike,\n  props: Record<string, unknown>,\n  options: InertiaResponseOptions,\n): Promise<InertiaResponse<string, Record<string, unknown>>> {\n  const component =\n    typeof componentOrPage === 'string'\n      ? componentOrPage\n      : componentOrPage.component ?? componentOrPage.id\n  const payload = await buildInertiaPage(component, props, { url: options.url, version: options.version, request })\n  const serialized = serializePage(payload)\n  const prefersJson = request.headers.has('X-Inertia') || acceptsJson(request)\n\n  const response = new Response(\n    prefersJson ? serialized : `${initialPageElement(serialized)}<div id=\"app\"></div>`,\n    {\n      status: options.status ?? 200,\n      headers: mergeInertiaVary(withDefaultHeaders(options.headers, {\n        'Content-Type': prefersJson ? 'application/json; charset=utf-8' : 'text/html; charset=utf-8',\n        'X-Inertia': 'true',\n      })),\n    },\n  )\n\n  return Object.assign(response, { __gurenInertia: { component, props: payload.props } })\n}\n\nexport function createGurenControllerModule() {\n  // Prime the memo now: continuations on one promise run in registration order, so\n  // the memo is populated before an awaited view() render reaches the sync viteAsset.\n  void loadServer()\n\n  class Controller {\n    public context: ControllerContext | undefined\n\n    setContext(context: ControllerContext): void {\n      this.context = context\n    }\n\n    public get ctx(): ControllerContext {\n      if (!this.context) {\n        throw new Error('Controller context has not been set.')\n      }\n\n      return this.context\n    }\n\n    make<T = unknown>(key: string): T {\n      return this.ctx.var?.container?.make<T>(key) as T\n    }\n\n    text(body: string, init: ResponseInit = {}): Response {\n      return new Response(body, {\n        ...init,\n        headers: withDefaultHeaders(init.headers, { 'Content-Type': 'text/plain; charset=utf-8' }),\n      })\n    }\n\n    inertia(\n      componentOrPage: string | { id: string; component?: string },\n      props: Record<string, unknown>,\n      options: Record<string, unknown> = {},\n    ): Promise<Response> {\n      return renderInertia(this.ctx.req.raw, componentOrPage, props, options as InertiaResponseOptions)\n    }\n\n    /**\n     * Delegates to the real `renderDocument()` — the same engine `Controller.view()`\n     * uses — so the mock cannot drift on escaping, the fragment guard or shaping.\n     */\n    async view(\n      component: ((props: never) => unknown) & { displayName?: string; name?: string },\n      props: unknown,\n      options: ResponseInit & { doctype?: boolean } = {},\n    ): Promise<Response> {\n      const { renderDocument } = await loadServer()\n      return renderDocument(component as never, props as never, options)\n    }\n  }\n\n  return {\n    Controller,\n    /**\n     * The real `viteAsset()`: under vitest it takes the dev branch, while a test that\n     * forces production gets the real manifest lookup and its missing-entry throw.\n     * Sync by contract, so it reads the lazily-primed memo (see `loadServer`).\n     */\n    viteAsset: (entry: string, options?: { manifestPaths?: string[] }): string => {\n      if (!loadedServer) {\n        throw new Error(\n          'viteAsset(): the mock resolves @guren/server lazily — render through ' +\n            'view(), or `await Promise.resolve()` once after creating the mock, ' +\n            'before calling viteAsset() directly.',\n        )\n      }\n      return loadedServer.viteAsset(entry, options)\n    },\n    parseRequestPayload: async (ctx: ControllerContext) =>\n      asRecord(await parseRequestBody(ctx as unknown as RequestBodyContext)),\n    formatValidationErrors,\n    always,\n    defer,\n    live,\n  }\n}\n\n/**\n * The runtime's own `Controller`, so every request, validation and response helper is\n * the one production runs. Overridden only where the runtime needs a booted app.\n * Top-level rather than inside the factory: the declaration then names the base\n * class, which is what lets it keep its private members (TS4094).\n */\nclass TestController extends RuntimeController {\n  // Also takes the context `createControllerContext()` is typed as, whose container\n  // stands in for the one the router would pass to `setContainer()`.\n  override setContext(context: Context | ControllerContext): void {\n    super.setContext(context as unknown as Context)\n    const container = (context as ControllerContext).var?.container\n    if (container) {\n      this.setContainer(container)\n    }\n  }\n\n  protected override inertia<Component extends string, Props extends Record<string, unknown>>(\n    component: Component,\n    props: Props,\n    options?: InertiaResponseOptions,\n  ): Promise<InertiaResponse<Component, ResolvedInertiaProps<Props> & ResolvedSharedInertiaProps>>\n  protected override inertia<TPage extends InertiaPageContractLike>(\n    page: TPage,\n    props: InertiaPropsInput<NonNullable<TPage['__props']>>,\n    options?: InertiaResponseOptions,\n  ): Promise<InertiaResponse<TPage['id'], NonNullable<TPage['__props']> & ResolvedSharedInertiaProps>>\n  protected override async inertia(\n    componentOrPage: string | InertiaPageContractLike,\n    props: Record<string, unknown>,\n    options: InertiaResponseOptions = {},\n  ): Promise<Response> {\n    return renderInertia(this.ctx.req.raw, componentOrPage, props, options)\n  }\n}\n\nexport function createControllerModuleMock() {\n  const module = createGurenControllerModule()\n\n  class Event {}\n  class Listener {}\n  class Job {}\n  class AuthenticatableModel {\n    static table: unknown = null\n    static recordType: unknown = {}\n    static relationTypes: unknown = {}\n\n    static async find(): Promise<unknown> {\n      return null\n    }\n\n    static async where(): Promise<unknown[]> {\n      return []\n    }\n\n    static async update(): Promise<void> {}\n\n    // Relation registrars are no-ops so model modules that declare\n    // relations at import time load cleanly under the mock.\n    static hasMany(): void {}\n    static hasOne(): void {}\n    static belongsTo(): void {}\n    static belongsToMany(): void {}\n    static hasManyThrough(): void {}\n    static morphMany(): void {}\n    static morphTo(): void {}\n\n    static async with(): Promise<unknown[]> {\n      return []\n    }\n\n    static async withCount(): Promise<unknown[]> {\n      return []\n    }\n\n    static async findWith(): Promise<unknown> {\n      return null\n    }\n\n    // Inert, but they have to exist: tests drive model behaviour by spying on them,\n    // and a spy cannot replace a method that was never defined.\n    static async all(): Promise<unknown[]> {\n      return []\n    }\n\n    static async create(): Promise<unknown> {\n      return {}\n    }\n\n    static async findOrFail(): Promise<unknown> {\n      return {}\n    }\n\n    static async first(): Promise<unknown> {\n      return null\n    }\n\n    static async delete(): Promise<void> {}\n\n    /** Chainable like the real query builder, and awaitable at any point. */\n    static select(): Record<string, unknown> {\n      const query: Record<string, unknown> = {\n        get: async () => [],\n        first: async () => null,\n        then: (resolve: (value: unknown[]) => unknown) => resolve([]),\n      }\n      for (const method of ['where', 'whereNotNull', 'whereNull', 'orderBy', 'limit', 'offset']) {\n        query[method] = () => query\n      }\n      return query\n    }\n  }\n  /**\n   * The function form of a model declaration, reachable through any model module a\n   * controller imports. Returns the same inert stub, named after the table.\n   */\n  function defineModel(table: unknown, config: Record<string, unknown> = {}) {\n    return class DefinedModel extends AuthenticatableModel {\n      static override table = table\n      static config = config\n    }\n  }\n\n  const getApiTokenOrFail = (\n    ctx: ControllerContext,\n  ): { token: unknown; userId: string | number; abilities: string[] } => {\n    const result = ctx.get('guren:api-token') as {\n      token: unknown\n      userId: string | number\n      abilities: string[]\n    } | undefined\n    if (!result) {\n      throw new AuthenticationException('Unauthenticated.')\n    }\n    return result\n  }\n\n  class MemoryApiTokenStore {\n    clear(): void {}\n  }\n\n  const createApiToken = async (\n    _store: unknown,\n    options: { name: string; userId: number | string; abilities: string[]; expiresIn?: number | null },\n  ): Promise<{\n    plainTextToken: string\n    token: {\n      id: string\n      name: string\n      userId: number | string\n      abilities: string[]\n      createdAt: Date\n      lastUsedAt: Date | null\n      expiresAt: Date | null\n    }\n  }> => {\n    const expiresAt =\n      typeof options.expiresIn === 'number' ? new Date(Date.now() + options.expiresIn) : null\n\n    return {\n      plainTextToken: 'test-token',\n      token: {\n        id: 'token-id',\n        name: options.name,\n        userId: options.userId,\n        abilities: options.abilities,\n        createdAt: new Date(),\n        lastUsedAt: null,\n        expiresAt,\n      },\n    }\n  }\n\n  const revokeApiToken = async (): Promise<void> => {}\n\n  const getUserApiTokens = async (): Promise<\n    Array<{\n      id: string\n      name: string\n      abilities: string[]\n      createdAt: Date\n      lastUsedAt: Date | null\n      expiresAt: Date | null\n    }>\n  > => {\n    return []\n  }\n\n  const getApiToken = (): { userId: number | string; abilities: string[] } | null => {\n    return null\n  }\n  const createEventManager = () => ({\n    on: () => {},\n    emit: async () => {},\n  })\n  const createMailManager = () => ({})\n  const setMailManager = () => {}\n  const setQueueDriver = () => {}\n  const registerJob = () => {}\n  class MemoryDriver {}\n  const createCacheManager = () => ({\n    store: () => ({\n      remember: async (_key: string, _ttl: number, callback: () => Promise<unknown>) => callback(),\n      delete: async () => {},\n      clear: async () => {},\n    }),\n  })\n\n  return {\n    ...module,\n    Controller: TestController,\n    Event,\n    Listener,\n    Job,\n    AuthenticatableModel,\n    defineModel,\n    Resource,\n    JsonResource,\n    collect,\n    ValidationException,\n    AuthenticationException,\n    ServiceProvider,\n    defineModule,\n    definePlugin,\n    MemoryApiTokenStore,\n    createApiToken,\n    revokeApiToken,\n    getUserApiTokens,\n    getApiToken,\n    getApiTokenOrFail,\n    createEventManager,\n    createMailManager,\n    setMailManager,\n    setQueueDriver,\n    registerJob,\n    MemoryDriver,\n    createCacheManager,\n  }\n}\n\nexport async function readInertiaResponse(response: Response): Promise<{\n  format: 'json' | 'html'\n  payload: InertiaPayload\n  body?: string\n}> {\n  const contentType = response.headers.get('content-type') ?? ''\n\n  if (contentType.includes('application/json')) {\n    return {\n      format: 'json',\n      payload: (await response.json()) as InertiaPayload,\n    }\n  }\n\n  const body = await response.text()\n  const payload = readInitialPage(body) as InertiaPayload | undefined\n  if (payload === undefined) {\n    throw new Error('Unable to find Inertia payload in HTML response.')\n  }\n\n  return {\n    format: 'html',\n    payload,\n    body,\n  }\n}\n","/**\n * JSON for an `X-Testing-*` header, every character past `~` written as a `\\uXXXX`\n * escape: a header value is a byte string, so Bun throws on `浦田` and a Latin-1 `é`\n * arrives byte-mangled. The result is still plain JSON, which every server's\n * `JSON.parse` reads, so no `@guren/server` release needs a decoder for it.\n */\nexport function testingHeaderValue(value: unknown): string {\n  return JSON.stringify(value).replace(\n    /[\\u007f-\\uffff]/g,\n    (char) => `\\\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`,\n  )\n}\n","import type { Authenticatable } from '@guren/server'\n\nimport { testingHeaderValue } from './testing-header'\n\n/**\n * Test response wrapper with assertion methods.\n */\nexport class TestResponse {\n  private response: Response\n  private _body: string | null = null\n  private _json: unknown = null\n\n  constructor(response: Response) {\n    this.response = response\n  }\n\n  /**\n   * Get the raw response.\n   */\n  get raw(): Response {\n    return this.response\n  }\n\n  /**\n   * Get the status code.\n   */\n  get status(): number {\n    return this.response.status\n  }\n\n  /**\n   * Get response headers.\n   */\n  get headers(): Headers {\n    return this.response.headers\n  }\n\n  /**\n   * Get the response body as text.\n   */\n  async text(): Promise<string> {\n    if (this._body === null) {\n      this._body = await this.response.clone().text()\n    }\n    return this._body\n  }\n\n  /**\n   * Get the response body as JSON.\n   */\n  async json<T = unknown>(): Promise<T> {\n    if (this._json === null) {\n      this._json = await this.response.clone().json()\n    }\n    return this._json as T\n  }\n\n  /**\n   * Assert the response status code.\n   */\n  assertStatus(status: number): this {\n    if (this.response.status !== status) {\n      throw new Error(\n        `Expected status ${status}, got ${this.response.status}`\n      )\n    }\n    return this\n  }\n\n  /**\n   * Assert the response is OK (200).\n   */\n  assertOk(): this {\n    return this.assertStatus(200)\n  }\n\n  /**\n   * Assert the response is Created (201).\n   */\n  assertCreated(): this {\n    return this.assertStatus(201)\n  }\n\n  /**\n   * Assert the response is No Content (204).\n   */\n  assertNoContent(): this {\n    return this.assertStatus(204)\n  }\n\n  /**\n   * Assert the response is Bad Request (400).\n   */\n  assertBadRequest(): this {\n    return this.assertStatus(400)\n  }\n\n  /**\n   * Assert the response is Unauthorized (401).\n   */\n  assertUnauthorized(): this {\n    return this.assertStatus(401)\n  }\n\n  /**\n   * Assert the response is Forbidden (403).\n   */\n  assertForbidden(): this {\n    return this.assertStatus(403)\n  }\n\n  /**\n   * Assert the response is Not Found (404).\n   */\n  assertNotFound(): this {\n    return this.assertStatus(404)\n  }\n\n  /**\n   * Assert the response is Unprocessable Entity (422).\n   */\n  assertUnprocessable(): this {\n    return this.assertStatus(422)\n  }\n\n  /**\n   * Assert the response is Internal Server Error (500).\n   */\n  assertServerError(): this {\n    return this.assertStatus(500)\n  }\n\n  /**\n   * Assert the response is a redirect.\n   */\n  assertRedirect(url?: string): this {\n    const status = this.response.status\n    if (status < 300 || status >= 400) {\n      throw new Error(`Expected redirect status, got ${status}`)\n    }\n\n    if (url !== undefined) {\n      const location = this.response.headers.get('Location')\n      if (location !== url) {\n        throw new Error(`Expected redirect to ${url}, got ${location}`)\n      }\n    }\n\n    return this\n  }\n\n  /**\n   * Assert the response has a specific header.\n   */\n  assertHeader(name: string, value?: string): this {\n    const headerValue = this.response.headers.get(name)\n\n    if (headerValue === null) {\n      throw new Error(`Expected header ${name} to exist`)\n    }\n\n    if (value !== undefined && headerValue !== value) {\n      throw new Error(\n        `Expected header ${name} to be ${value}, got ${headerValue}`\n      )\n    }\n\n    return this\n  }\n\n  /**\n   * Assert the response does not have a specific header.\n   */\n  assertHeaderMissing(name: string): this {\n    const headerValue = this.response.headers.get(name)\n\n    if (headerValue !== null) {\n      throw new Error(`Expected header ${name} to be missing`)\n    }\n\n    return this\n  }\n\n  /**\n   * Assert the response body contains the expected JSON.\n   */\n  async assertJson(expected: unknown): Promise<this> {\n    const json = await this.json()\n    const expectedStr = JSON.stringify(expected)\n    const actualStr = JSON.stringify(json)\n\n    if (expectedStr !== actualStr) {\n      throw new Error(\n        `Expected JSON ${expectedStr}, got ${actualStr}`\n      )\n    }\n\n    return this\n  }\n\n  /**\n   * Assert the response JSON has a value at the given path.\n   */\n  async assertJsonPath(path: string, expected: unknown): Promise<this> {\n    const json = await this.json()\n    const value = getNestedValue(json, path)\n\n    if (!deepEqual(value, expected)) {\n      throw new Error(\n        `Expected ${path} to be ${JSON.stringify(expected)}, got ${JSON.stringify(value)}`\n      )\n    }\n\n    return this\n  }\n\n  /**\n   * Assert the response JSON contains the expected data (partial match).\n   */\n  async assertJsonContains(expected: Record<string, unknown>): Promise<this> {\n    const json = await this.json() as Record<string, unknown>\n\n    for (const [key, value] of Object.entries(expected)) {\n      if (!deepEqual(json[key], value)) {\n        throw new Error(\n          `Expected ${key} to be ${JSON.stringify(value)}, got ${JSON.stringify(json[key])}`\n        )\n      }\n    }\n\n    return this\n  }\n\n  /**\n   * Assert the response body contains the expected text.\n   */\n  async assertBodyContains(text: string): Promise<this> {\n    const body = await this.text()\n\n    if (!body.includes(text)) {\n      throw new Error(`Expected body to contain \"${text}\"`)\n    }\n\n    return this\n  }\n\n  /**\n   * Assert the response is successful (2xx).\n   */\n  assertSuccessful(): this {\n    const status = this.response.status\n    if (status < 200 || status >= 300) {\n      throw new Error(`Expected successful status (2xx), got ${status}`)\n    }\n    return this\n  }\n}\n\n/**\n * Test request builder for fluent API.\n */\nexport class TestRequestBuilder {\n  private url: string\n  private method: string\n  private _headers: Record<string, string> = {}\n  private _body: BodyInit | null = null\n  private _cookies: Record<string, string> = {}\n  private _session: Record<string, unknown> = {}\n  private _user: Authenticatable | null = null\n  private fetchFn: (request: Request) => Promise<Response>\n\n  constructor(\n    url: string,\n    method: string,\n    fetchFn: (request: Request) => Promise<Response>\n  ) {\n    this.url = url\n    this.method = method\n    this.fetchFn = fetchFn\n  }\n\n  /**\n   * Set a header.\n   */\n  withHeader(name: string, value: string): this {\n    this._headers[name] = value\n    return this\n  }\n\n  /**\n   * Set multiple headers.\n   */\n  withHeaders(headers: Record<string, string>): this {\n    Object.assign(this._headers, headers)\n    return this\n  }\n\n  /**\n   * Set a cookie.\n   */\n  withCookie(name: string, value: string): this {\n    this._cookies[name] = value\n    return this\n  }\n\n  /**\n   * Set multiple cookies.\n   */\n  withCookies(cookies: Record<string, string>): this {\n    Object.assign(this._cookies, cookies)\n    return this\n  }\n\n  /**\n   * Set session data.\n   */\n  withSession(data: Record<string, unknown>): this {\n    Object.assign(this._session, data)\n    return this\n  }\n\n  /**\n   * Set JSON body.\n   */\n  withJson(data: unknown): this {\n    this._body = JSON.stringify(data)\n    this._headers['Content-Type'] = 'application/json'\n    return this\n  }\n\n  /**\n   * Set form data body.\n   */\n  withForm(data: Record<string, string>): this {\n    this._body = new URLSearchParams(data).toString()\n    this._headers['Content-Type'] = 'application/x-www-form-urlencoded'\n    return this\n  }\n\n  /**\n   * Set raw body.\n   */\n  withBody(body: BodyInit, contentType?: string): this {\n    this._body = body\n    if (contentType) {\n      this._headers['Content-Type'] = contentType\n    }\n    return this\n  }\n\n  /**\n   * Set the authenticated user.\n   */\n  actingAs(user: Authenticatable): this {\n    this._user = user\n    return this\n  }\n\n  /**\n   * Accept JSON responses.\n   */\n  acceptJson(): this {\n    this._headers['Accept'] = 'application/json'\n    return this\n  }\n\n  /**\n   * Set as Inertia request.\n   */\n  asInertia(version?: string): this {\n    this._headers['X-Inertia'] = 'true'\n    if (version) {\n      this._headers['X-Inertia-Version'] = version\n    }\n    return this\n  }\n\n  /**\n   * Get request details for testing.\n   */\n  getRequestDetails(): {\n    user: Authenticatable | null\n    session: Record<string, unknown>\n  } {\n    return {\n      user: this._user,\n      session: this._session,\n    }\n  }\n\n  /**\n   * Send the request.\n   */\n  async send(): Promise<TestResponse> {\n    if (Object.keys(this._cookies).length > 0) {\n      const cookieStr = Object.entries(this._cookies)\n        .map(([k, v]) => `${k}=${v}`)\n        .join('; ')\n      this._headers['Cookie'] = cookieStr\n    }\n\n    if (this._user) {\n      const userData = typeof this._user.getAuthIdentifier === 'function'\n        ? { ...this._user, __authId: this._user.getAuthIdentifier() }\n        : this._user\n      this._headers['X-Testing-User'] = testingHeaderValue(userData)\n    }\n    if (Object.keys(this._session).length > 0) {\n      this._headers['X-Testing-Session'] = testingHeaderValue(this._session)\n    }\n\n    const request = new Request(this.url, {\n      method: this.method,\n      headers: this._headers,\n      body: this._body,\n    })\n\n    const response = await this.fetchFn(request)\n    return new TestResponse(response)\n  }\n}\n\n/**\n * Test client for making requests.\n */\nexport class TestClient {\n  private baseUrl: string\n  private fetchFn: (request: Request) => Promise<Response>\n  private defaultHeaders: Record<string, string> = {}\n\n  constructor(\n    baseUrl: string,\n    fetchFn: (request: Request) => Promise<Response>\n  ) {\n    this.baseUrl = baseUrl.replace(/\\/$/, '')\n    this.fetchFn = fetchFn\n  }\n\n  /**\n   * Set default headers for all requests.\n   */\n  setDefaultHeaders(headers: Record<string, string>): this {\n    Object.assign(this.defaultHeaders, headers)\n    return this\n  }\n\n  /**\n   * Create a GET request.\n   */\n  get(path: string): TestRequestBuilder {\n    return this.request('GET', path)\n  }\n\n  /**\n   * Create a POST request.\n   */\n  post(path: string): TestRequestBuilder {\n    return this.request('POST', path)\n  }\n\n  /**\n   * Create a PUT request.\n   */\n  put(path: string): TestRequestBuilder {\n    return this.request('PUT', path)\n  }\n\n  /**\n   * Create a PATCH request.\n   */\n  patch(path: string): TestRequestBuilder {\n    return this.request('PATCH', path)\n  }\n\n  /**\n   * Create a DELETE request.\n   */\n  delete(path: string): TestRequestBuilder {\n    return this.request('DELETE', path)\n  }\n\n  /**\n   * Create a QUERY request (RFC 10008): safe and idempotent like GET, but\n   * carries a request body like POST.\n   */\n  query(path: string): TestRequestBuilder {\n    return this.request('QUERY', path)\n  }\n\n  /**\n   * Create a request with any method.\n   */\n  request(method: string, path: string): TestRequestBuilder {\n    const url = path.startsWith('http') ? path : `${this.baseUrl}${path}`\n    const builder = new TestRequestBuilder(url, method, this.fetchFn)\n    builder.withHeaders(this.defaultHeaders)\n    return builder\n  }\n}\n\n/**\n * Create a test client from an application fetch function.\n */\nexport function createTestClient(\n  fetchFn: (request: Request) => Promise<Response>,\n  baseUrl = 'http://localhost'\n): TestClient {\n  return new TestClient(baseUrl, fetchFn)\n}\n\nfunction getNestedValue(obj: unknown, path: string): unknown {\n  const parts = path.split('.')\n  let current = obj\n\n  for (const part of parts) {\n    if (current === null || current === undefined) {\n      return undefined\n    }\n    if (typeof current !== 'object') {\n      return undefined\n    }\n    current = (current as Record<string, unknown>)[part]\n  }\n\n  return current\n}\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n  if (a === b) return true\n  if (a === null || b === null) return a === b\n  if (typeof a !== typeof b) return false\n  if (typeof a !== 'object') return a === b\n\n  if (Array.isArray(a) && Array.isArray(b)) {\n    if (a.length !== b.length) return false\n    return a.every((v, i) => deepEqual(v, b[i]))\n  }\n\n  if (Array.isArray(a) || Array.isArray(b)) return false\n\n  const aObj = a as Record<string, unknown>\n  const bObj = b as Record<string, unknown>\n  const aKeys = Object.keys(aObj)\n  const bKeys = Object.keys(bObj)\n\n  if (aKeys.length !== bKeys.length) return false\n\n  return aKeys.every((key) => deepEqual(aObj[key], bObj[key]))\n}\n","import { getJob, resolveJobName } from '@guren/server'\nimport type { FailedJob, QueuedJob, QueueDriver, JobClass } from '@guren/server'\n\n/**\n * Recorded job for testing.\n */\nexport interface RecordedJob<T = unknown> {\n  jobClass?: JobClass<T>\n  jobName: string\n  payload: T\n  options: {\n    queue: string\n    delay: number\n  }\n  timestamp: Date\n  queuedJob: QueuedJob<T>\n}\n\n/**\n * Fake queue driver for testing.\n */\nexport class FakeQueueDriver implements QueueDriver {\n  private jobs: RecordedJob[] = []\n  private failedJobs: FailedJob[] = []\n  private jobClasses = new Map<string, JobClass>()\n\n  registerJobClass<T>(jobClass: JobClass<T>): void {\n    this.jobClasses.set(resolveJobName(jobClass), jobClass as JobClass)\n  }\n\n  async push(job: QueuedJob): Promise<void> {\n    const delay = Math.max(0, job.availableAt.getTime() - job.createdAt.getTime())\n    const jobClass = this.jobClasses.get(job.name) ?? getJob(job.name)\n\n    this.jobs.push({\n      jobClass: jobClass as JobClass | undefined,\n      jobName: job.name,\n      payload: job.payload,\n      options: {\n        queue: job.queue,\n        delay,\n      },\n      timestamp: new Date(),\n      queuedJob: job,\n    })\n  }\n\n  async pop(queue: string): Promise<QueuedJob | null> {\n    const index = this.jobs.findIndex((job) => job.options.queue === queue)\n    if (index === -1) {\n      return null\n    }\n\n    const [record] = this.jobs.splice(index, 1)\n    return record.queuedJob\n  }\n\n  async release(job: QueuedJob, delayMs: number = 0): Promise<void> {\n    const now = new Date()\n    const released: QueuedJob = {\n      ...job,\n      availableAt: new Date(now.getTime() + delayMs),\n      reservedAt: null,\n    }\n    await this.push(released)\n  }\n\n  async delete(jobId: string): Promise<void> {\n    this.jobs = this.jobs.filter((job) => job.queuedJob.id !== jobId)\n    this.failedJobs = this.failedJobs.filter((job) => job.id !== jobId)\n  }\n\n  async fail(job: QueuedJob, error: Error): Promise<void> {\n    this.failedJobs.push({\n      ...job,\n      failedAt: new Date(),\n      error: error.message,\n      stack: error.stack,\n    })\n  }\n\n  async size(queue: string): Promise<number> {\n    return this.jobs.filter((job) => job.options.queue === queue).length\n  }\n\n  async getFailedJobs(queue?: string): Promise<FailedJob[]> {\n    if (!queue) {\n      return [...this.failedJobs]\n    }\n\n    return this.failedJobs.filter((job) => job.queue === queue)\n  }\n\n  async retryFailedJob(jobId: string): Promise<void> {\n    const index = this.failedJobs.findIndex((job) => job.id === jobId)\n    if (index === -1) {\n      return\n    }\n\n    const [failed] = this.failedJobs.splice(index, 1)\n    const { failedAt, error, stack, ...queuedJob } = failed\n    void failedAt\n    void error\n    void stack\n    await this.push(queuedJob as QueuedJob)\n  }\n\n  async deleteFailedJob(jobId: string): Promise<void> {\n    this.failedJobs = this.failedJobs.filter((job) => job.id !== jobId)\n  }\n\n  async clear(): Promise<void> {\n    this.jobs = []\n    this.failedJobs = []\n  }\n\n  /**\n   * Get all recorded jobs.\n   */\n  getJobs(): RecordedJob[] {\n    return [...this.jobs]\n  }\n\n  /**\n   * Get jobs of a specific type.\n   */\n  getJobsOf<T>(jobClass: JobClass<T>): RecordedJob<T>[] {\n    const name = resolveJobName(jobClass)\n    return this.jobs.filter(\n      (j) => j.jobClass === jobClass || j.jobName === name\n    ) as RecordedJob<T>[]\n  }\n}\n\n/**\n * Fake queue for testing job dispatches.\n */\nexport class FakeQueue {\n  private driver: FakeQueueDriver\n\n  constructor() {\n    this.driver = new FakeQueueDriver()\n  }\n\n  /**\n   * Get the underlying driver.\n   */\n  getDriver(): FakeQueueDriver {\n    return this.driver\n  }\n\n  /**\n   * Record a job dispatch.\n   */\n  record<T>(jobClass: JobClass<T>, payload: T, options: { queue?: string; delay?: number } = {}): void {\n    this.driver.registerJobClass(jobClass)\n    const now = new Date()\n    const delay = options.delay ?? 0\n    const queuedJob: QueuedJob<T> = {\n      id: `fake-job-${Date.now()}-${Math.random().toString(36).slice(2)}`,\n      name: resolveJobName(jobClass),\n      payload,\n      queue: options.queue ?? jobClass.queue,\n      attempts: 0,\n      maxAttempts: jobClass.maxAttempts,\n      availableAt: new Date(now.getTime() + delay),\n      createdAt: now,\n      reservedAt: null,\n    }\n\n    void this.driver.push(queuedJob)\n  }\n\n  /**\n   * Assert a job was pushed.\n   */\n  assertPushed<T>(\n    jobClass: JobClass<T>,\n    callback?: (payload: T) => boolean\n  ): void {\n    const jobs = this.driver.getJobsOf(jobClass)\n    const name = resolveJobName(jobClass)\n\n    if (jobs.length === 0) {\n      throw new Error(`Expected job [${name}] to be pushed`)\n    }\n\n    if (callback) {\n      const match = jobs.some((j) => callback(j.payload))\n      if (!match) {\n        throw new Error(\n          `Expected job [${name}] to match callback, but none did`\n        )\n      }\n    }\n  }\n\n  /**\n   * Assert a job was pushed a specific number of times.\n   */\n  assertPushedTimes<T>(jobClass: JobClass<T>, times: number): void {\n    const jobs = this.driver.getJobsOf(jobClass)\n    const name = resolveJobName(jobClass)\n\n    if (jobs.length !== times) {\n      throw new Error(\n        `Expected job [${name}] to be pushed ${times} times, got ${jobs.length}`\n      )\n    }\n  }\n\n  /**\n   * Assert a job was not pushed.\n   */\n  assertNotPushed<T>(jobClass: JobClass<T>): void {\n    const jobs = this.driver.getJobsOf(jobClass)\n    const name = resolveJobName(jobClass)\n\n    if (jobs.length > 0) {\n      throw new Error(\n        `Expected job [${name}] not to be pushed, but it was pushed ${jobs.length} times`\n      )\n    }\n  }\n\n  /**\n   * Assert no jobs were pushed.\n   */\n  assertNothingPushed(): void {\n    const jobs = this.driver.getJobs()\n\n    if (jobs.length > 0) {\n      const names = [...new Set(jobs.map((j) => j.jobName))]\n      throw new Error(\n        `Expected no jobs to be pushed, but found: ${names.join(', ')}`\n      )\n    }\n  }\n\n  /**\n   * Assert a job was pushed to a specific queue.\n   */\n  assertPushedOn<T>(queue: string, jobClass: JobClass<T>): void {\n    const jobs = this.driver.getJobsOf(jobClass)\n    const name = resolveJobName(jobClass)\n    const match = jobs.some((j) => j.options.queue === queue)\n\n    if (!match) {\n      throw new Error(\n        `Expected job [${name}] to be pushed to queue [${queue}]`\n      )\n    }\n  }\n\n  /**\n   * Assert a job was pushed with a delay.\n   */\n  assertPushedWithDelay<T>(jobClass: JobClass<T>, delay: number): void {\n    const jobs = this.driver.getJobsOf(jobClass)\n    const name = resolveJobName(jobClass)\n    const match = jobs.some((j) => j.options.delay === delay)\n\n    if (!match) {\n      throw new Error(\n        `Expected job [${name}] to be pushed with delay [${delay}]`\n      )\n    }\n  }\n\n  /**\n   * Get pushed jobs of a specific type.\n   */\n  pushed<T>(jobClass: JobClass<T>): RecordedJob<T>[] {\n    return this.driver.getJobsOf(jobClass)\n  }\n\n  /**\n   * Get all pushed jobs.\n   */\n  all(): RecordedJob[] {\n    return this.driver.getJobs()\n  }\n\n  /**\n   * Clear all recorded jobs.\n   */\n  clear(): void {\n    void this.driver.clear()\n  }\n}\n\n/**\n * Create a fake queue for testing.\n */\nexport function fakeQueue(): FakeQueue {\n  return new FakeQueue()\n}\n","import type { MailMessage, SendResult, MailTransport } from '@guren/server'\n\n/**\n * Recorded mail for testing.\n */\nexport interface RecordedMail {\n  message: MailMessage\n  timestamp: Date\n}\n\n/**\n * Fake mail transport for testing.\n */\nexport class FakeMailTransport implements MailTransport {\n  readonly name = 'fake'\n  private mails: RecordedMail[] = []\n\n  async send(message: MailMessage): Promise<SendResult> {\n    this.mails.push({\n      message,\n      timestamp: new Date(),\n    })\n\n    return {\n      success: true,\n      messageId: `fake-mail-${Date.now()}-${Math.random().toString(36).slice(2)}`,\n    }\n  }\n\n  /**\n   * Get all recorded mails.\n   */\n  getMails(): RecordedMail[] {\n    return [...this.mails]\n  }\n\n  /**\n   * Clear recorded mails.\n   */\n  clear(): void {\n    this.mails = []\n  }\n}\n\n/**\n * Fake mail for testing mail sending.\n */\nexport class FakeMail {\n  private transport: FakeMailTransport\n\n  constructor() {\n    this.transport = new FakeMailTransport()\n  }\n\n  /**\n   * Get the underlying transport.\n   */\n  getTransport(): FakeMailTransport {\n    return this.transport\n  }\n\n  /**\n   * Record a mail send.\n   */\n  record(message: MailMessage): void {\n    void this.transport.send(message)\n  }\n\n  /**\n   * Assert a mail was sent.\n   */\n  assertSent(callback?: (message: MailMessage) => boolean): void {\n    const mails = this.transport.getMails()\n\n    if (mails.length === 0) {\n      throw new Error('Expected a mail to be sent')\n    }\n\n    if (callback) {\n      const match = mails.some((m) => callback(m.message))\n      if (!match) {\n        throw new Error('Expected a mail to match callback, but none did')\n      }\n    }\n  }\n\n  /**\n   * Assert a mail was sent a specific number of times.\n   */\n  assertSentTimes(times: number): void {\n    const mails = this.transport.getMails()\n\n    if (mails.length !== times) {\n      throw new Error(\n        `Expected ${times} mails to be sent, got ${mails.length}`\n      )\n    }\n  }\n\n  /**\n   * Assert no mails were sent.\n   */\n  assertNothingSent(): void {\n    const mails = this.transport.getMails()\n\n    if (mails.length > 0) {\n      throw new Error(\n        `Expected no mails to be sent, but ${mails.length} were sent`\n      )\n    }\n  }\n\n  /**\n   * Assert a mail was sent to a specific address.\n   */\n  assertSentTo(address: string): void {\n    const mails = this.transport.getMails()\n    const match = mails.some((m) => {\n      return m.message.to.some((addr) => addr.email === address)\n    })\n\n    if (!match) {\n      throw new Error(`Expected a mail to be sent to [${address}]`)\n    }\n  }\n\n  /**\n   * Assert a mail was sent from a specific address.\n   */\n  assertSentFrom(address: string): void {\n    const mails = this.transport.getMails()\n    const match = mails.some((m) => {\n      const from = m.message.from\n      if (!from) return false\n      return from.email === address\n    })\n\n    if (!match) {\n      throw new Error(`Expected a mail to be sent from [${address}]`)\n    }\n  }\n\n  /**\n   * Assert a mail with specific subject was sent.\n   */\n  assertSentWithSubject(subject: string): void {\n    const mails = this.transport.getMails()\n    const match = mails.some((m) => m.message.subject === subject)\n\n    if (!match) {\n      throw new Error(`Expected a mail with subject [${subject}] to be sent`)\n    }\n  }\n\n  /**\n   * Assert a mail body contains text.\n   */\n  assertSentWithBodyContaining(text: string): void {\n    const mails = this.transport.getMails()\n    const match = mails.some((m) => {\n      const html = m.message.html ?? ''\n      const textBody = m.message.text ?? ''\n      return html.includes(text) || textBody.includes(text)\n    })\n\n    if (!match) {\n      throw new Error(`Expected a mail body to contain [${text}]`)\n    }\n  }\n\n  /**\n   * Assert a mail was sent with CC.\n   */\n  assertSentWithCc(address: string): void {\n    const mails = this.transport.getMails()\n    const match = mails.some((m) => {\n      const cc = m.message.cc ?? []\n      return cc.some((addr) => addr.email === address)\n    })\n\n    if (!match) {\n      throw new Error(`Expected a mail to be sent with CC to [${address}]`)\n    }\n  }\n\n  /**\n   * Assert a mail was sent with BCC.\n   */\n  assertSentWithBcc(address: string): void {\n    const mails = this.transport.getMails()\n    const match = mails.some((m) => {\n      const bcc = m.message.bcc ?? []\n      return bcc.some((addr) => addr.email === address)\n    })\n\n    if (!match) {\n      throw new Error(`Expected a mail to be sent with BCC to [${address}]`)\n    }\n  }\n\n  /**\n   * Assert a mail was sent with attachment.\n   */\n  assertSentWithAttachment(filename: string): void {\n    const mails = this.transport.getMails()\n    const match = mails.some((m) => {\n      const attachments = m.message.attachments ?? []\n      return attachments.some((a) => a.filename === filename)\n    })\n\n    if (!match) {\n      throw new Error(`Expected a mail to be sent with attachment [${filename}]`)\n    }\n  }\n\n  /**\n   * Get sent mails.\n   */\n  sent(): RecordedMail[] {\n    return this.transport.getMails()\n  }\n\n  /**\n   * Get mails sent to a specific address.\n   */\n  sentTo(address: string): RecordedMail[] {\n    return this.transport.getMails().filter((m) => {\n      return m.message.to.some((addr) => addr.email === address)\n    })\n  }\n\n  /**\n   * Clear all recorded mails.\n   */\n  clear(): void {\n    this.transport.clear()\n  }\n}\n\n/**\n * Create a fake mail for testing.\n */\nexport function fakeMail(): FakeMail {\n  return new FakeMail()\n}\n","import type { TestLifecycleHooks } from './lifecycle'\nimport { getTestLifecycleHooks } from './lifecycle'\n\n/**\n * Database connection interface for testing.\n */\nexport interface DatabaseConnection {\n  query<T = unknown>(sql: string, params?: unknown[]): Promise<T[]>\n  execute(sql: string, params?: unknown[]): Promise<void>\n  beginTransaction(): Promise<void>\n  commit(): Promise<void>\n  rollback(): Promise<void>\n}\n\nlet globalDb: DatabaseConnection | null = null\n\n/**\n * Set the global database connection for testing.\n */\nexport function setTestDatabase(db: DatabaseConnection): void {\n  globalDb = db\n}\n\n/**\n * Get the global database connection.\n */\nexport function getTestDatabase(): DatabaseConnection {\n  if (!globalDb) {\n    throw new Error(\n      'Test database not configured. Call setTestDatabase() first.'\n    )\n  }\n  return globalDb\n}\n\n/**\n * Assert database has a record matching the criteria.\n */\nexport async function assertDatabaseHas(\n  table: string,\n  data: Record<string, unknown>,\n  db?: DatabaseConnection\n): Promise<void> {\n  const connection = db ?? getTestDatabase()\n  const { where, params } = buildWhereClause(data)\n  const sql = `SELECT COUNT(*) as count FROM ${table} WHERE ${where}`\n  const result = await connection.query<{ count: number }>(sql, params)\n\n  if (!result[0] || result[0].count === 0) {\n    throw new Error(\n      `Expected database table [${table}] to have record matching ${JSON.stringify(data)}`\n    )\n  }\n}\n\n/**\n * Assert database does not have a record matching the criteria.\n */\nexport async function assertDatabaseMissing(\n  table: string,\n  data: Record<string, unknown>,\n  db?: DatabaseConnection\n): Promise<void> {\n  const connection = db ?? getTestDatabase()\n  const { where, params } = buildWhereClause(data)\n  const sql = `SELECT COUNT(*) as count FROM ${table} WHERE ${where}`\n  const result = await connection.query<{ count: number }>(sql, params)\n\n  if (result[0] && result[0].count > 0) {\n    throw new Error(\n      `Expected database table [${table}] not to have record matching ${JSON.stringify(data)}`\n    )\n  }\n}\n\n/**\n * Assert database table has a specific count.\n */\nexport async function assertDatabaseCount(\n  table: string,\n  count: number,\n  db?: DatabaseConnection\n): Promise<void> {\n  const connection = db ?? getTestDatabase()\n  const sql = `SELECT COUNT(*) as count FROM ${table}`\n  const result = await connection.query<{ count: number }>(sql)\n\n  const actualCount = result[0]?.count ?? 0\n  if (actualCount !== count) {\n    throw new Error(\n      `Expected database table [${table}] to have ${count} records, got ${actualCount}`\n    )\n  }\n}\n\n/**\n * Assert database table is empty.\n */\nexport async function assertDatabaseEmpty(\n  table: string,\n  db?: DatabaseConnection\n): Promise<void> {\n  await assertDatabaseCount(table, 0, db)\n}\n\n/**\n * Assert a record is soft deleted (has deleted_at set).\n */\nexport async function assertSoftDeleted(\n  table: string,\n  data: Record<string, unknown>,\n  deletedAtColumn = 'deleted_at',\n  db?: DatabaseConnection\n): Promise<void> {\n  const connection = db ?? getTestDatabase()\n  const { where, params } = buildWhereClause(data)\n  const sql = `SELECT ${deletedAtColumn} FROM ${table} WHERE ${where}`\n  const result = await connection.query<Record<string, unknown>>(sql, params)\n\n  if (!result[0]) {\n    throw new Error(\n      `Expected database table [${table}] to have record matching ${JSON.stringify(data)}`\n    )\n  }\n\n  if (result[0][deletedAtColumn] === null) {\n    throw new Error(\n      `Expected record in [${table}] to be soft deleted, but ${deletedAtColumn} is null`\n    )\n  }\n}\n\n/**\n * Assert a record is not soft deleted.\n */\nexport async function assertNotSoftDeleted(\n  table: string,\n  data: Record<string, unknown>,\n  deletedAtColumn = 'deleted_at',\n  db?: DatabaseConnection\n): Promise<void> {\n  const connection = db ?? getTestDatabase()\n  const { where, params } = buildWhereClause(data)\n  const sql = `SELECT ${deletedAtColumn} FROM ${table} WHERE ${where}`\n  const result = await connection.query<Record<string, unknown>>(sql, params)\n\n  if (!result[0]) {\n    throw new Error(\n      `Expected database table [${table}] to have record matching ${JSON.stringify(data)}`\n    )\n  }\n\n  if (result[0][deletedAtColumn] !== null) {\n    throw new Error(\n      `Expected record in [${table}] not to be soft deleted, but ${deletedAtColumn} is set`\n    )\n  }\n}\n\n/**\n * Run each test in a transaction that is rolled back afterwards. Lifecycle hooks are\n * resolved via `getTestLifecycleHooks()` unless passed explicitly.\n */\nexport function useDatabaseTransactions(\n  db?: DatabaseConnection,\n  hooks?: TestLifecycleHooks\n): void {\n  const { beforeEach, afterEach } = hooks ?? getTestLifecycleHooks()\n\n  beforeEach(async () => {\n    const connection = db ?? getTestDatabase()\n    await connection.beginTransaction()\n  })\n\n  afterEach(async () => {\n    const connection = db ?? getTestDatabase()\n    await connection.rollback()\n  })\n}\n\n/**\n * Truncate tables before each test. Lifecycle hooks are resolved via\n * `getTestLifecycleHooks()` unless passed explicitly.\n */\nexport function useTruncateTables(\n  tables: string[],\n  db?: DatabaseConnection,\n  hooks?: TestLifecycleHooks\n): void {\n  const { beforeEach } = hooks ?? getTestLifecycleHooks()\n\n  beforeEach(async () => {\n    const connection = db ?? getTestDatabase()\n    for (const table of tables) {\n      await connection.execute(`DELETE FROM ${table}`)\n    }\n  })\n}\n\n/**\n * Refresh database (run migrations) before tests.\n */\nexport async function refreshDatabase(\n  migrateFn: () => Promise<void>\n): Promise<void> {\n  await migrateFn()\n}\n\n/**\n * Seed database with data.\n */\nexport async function seedDatabase(\n  seedFn: () => Promise<void>\n): Promise<void> {\n  await seedFn()\n}\n\nfunction buildWhereClause(data: Record<string, unknown>): {\n  where: string\n  params: unknown[]\n} {\n  const conditions: string[] = []\n  const params: unknown[] = []\n\n  for (const [key, value] of Object.entries(data)) {\n    if (value === null) {\n      conditions.push(`${key} IS NULL`)\n    } else {\n      conditions.push(`${key} = ?`)\n      params.push(value)\n    }\n  }\n\n  return {\n    where: conditions.join(' AND '),\n    params,\n  }\n}\n\n/**\n * Database assertion helper class.\n */\nexport class DatabaseAssertions {\n  private db: DatabaseConnection\n\n  constructor(db: DatabaseConnection) {\n    this.db = db\n  }\n\n  /**\n   * Assert database has a record.\n   */\n  async assertHas(table: string, data: Record<string, unknown>): Promise<void> {\n    await assertDatabaseHas(table, data, this.db)\n  }\n\n  /**\n   * Assert database is missing a record.\n   */\n  async assertMissing(table: string, data: Record<string, unknown>): Promise<void> {\n    await assertDatabaseMissing(table, data, this.db)\n  }\n\n  /**\n   * Assert database table has count.\n   */\n  async assertCount(table: string, count: number): Promise<void> {\n    await assertDatabaseCount(table, count, this.db)\n  }\n\n  /**\n   * Assert database table is empty.\n   */\n  async assertEmpty(table: string): Promise<void> {\n    await assertDatabaseEmpty(table, this.db)\n  }\n\n  /**\n   * Assert record is soft deleted.\n   */\n  async assertSoftDeleted(\n    table: string,\n    data: Record<string, unknown>,\n    deletedAtColumn = 'deleted_at'\n  ): Promise<void> {\n    await assertSoftDeleted(table, data, deletedAtColumn, this.db)\n  }\n\n  /**\n   * Assert record is not soft deleted.\n   */\n  async assertNotSoftDeleted(\n    table: string,\n    data: Record<string, unknown>,\n    deletedAtColumn = 'deleted_at'\n  ): Promise<void> {\n    await assertNotSoftDeleted(table, data, deletedAtColumn, this.db)\n  }\n}\n\n/**\n * Create database assertions helper.\n */\nexport function createDatabaseAssertions(db: DatabaseConnection): DatabaseAssertions {\n  return new DatabaseAssertions(db)\n}\n","import type { Event, EventClass, EventListener, ListenerOptions, EventSubscription } from '@guren/server'\n\n/**\n * Recorded event for testing.\n */\nexport interface RecordedEvent<T extends Event = Event> {\n  eventClass: EventClass<T>\n  event: T\n  timestamp: Date\n}\n\n/**\n * Fake event manager for testing.\n * Captures all emitted events for assertions.\n */\nexport class FakeEventManager {\n  private events: RecordedEvent[] = []\n  private listeners = new Map<string, EventListener[]>()\n\n  /**\n   * Register a listener for an event.\n   */\n  on<T extends Event>(\n    event: EventClass<T> | string,\n    listener: EventListener<T>,\n    _options: ListenerOptions = {}\n  ): EventSubscription {\n    const eventName = typeof event === 'string' ? event : event.eventName\n    const eventListeners = this.listeners.get(eventName) ?? []\n    eventListeners.push(listener as EventListener)\n    this.listeners.set(eventName, eventListeners)\n\n    return {\n      unsubscribe: () => this.off(event, listener),\n    }\n  }\n\n  /**\n   * Register a one-time listener for an event.\n   */\n  once<T extends Event>(\n    event: EventClass<T> | string,\n    listener: EventListener<T>,\n    options: Omit<ListenerOptions, 'once'> = {}\n  ): EventSubscription {\n    return this.on(event, listener, { ...options, once: true })\n  }\n\n  /**\n   * Remove a listener for an event.\n   */\n  off<T extends Event>(event: EventClass<T> | string, listener?: EventListener<T>): void {\n    const eventName = typeof event === 'string' ? event : event.eventName\n    if (!listener) {\n      this.listeners.delete(eventName)\n      return\n    }\n\n    const eventListeners = this.listeners.get(eventName)\n    if (eventListeners) {\n      const index = eventListeners.indexOf(listener as EventListener)\n      if (index !== -1) {\n        eventListeners.splice(index, 1)\n      }\n    }\n  }\n\n  /**\n   * Emit an event (records it but does not call listeners by default).\n   */\n  async emit<T extends Event>(event: T): Promise<void> {\n    this.events.push({\n      eventClass: event.constructor as EventClass<T>,\n      event,\n      timestamp: new Date(),\n    })\n  }\n\n  /**\n   * Emit an event in parallel (records it but does not call listeners by default).\n   */\n  async emitParallel<T extends Event>(event: T): Promise<void> {\n    await this.emit(event)\n  }\n\n  /**\n   * Check if an event has any listeners registered.\n   */\n  hasListeners(event: EventClass | string): boolean {\n    const eventName = typeof event === 'string' ? event : event.eventName\n    const listeners = this.listeners.get(eventName)\n    return listeners !== undefined && listeners.length > 0\n  }\n\n  /**\n   * Get all listeners for an event.\n   */\n  getListeners<T extends Event>(event: EventClass<T> | string): EventListener<T>[] {\n    const eventName = typeof event === 'string' ? event : event.eventName\n    return (this.listeners.get(eventName) ?? []) as EventListener<T>[]\n  }\n\n  /**\n   * Get the count of listeners for an event.\n   */\n  listenerCount(event: EventClass | string): number {\n    const eventName = typeof event === 'string' ? event : event.eventName\n    return this.listeners.get(eventName)?.length ?? 0\n  }\n\n  /**\n   * Get all registered event names.\n   */\n  eventNames(): string[] {\n    return Array.from(this.listeners.keys())\n  }\n\n  /**\n   * Remove all listeners for all events.\n   */\n  removeAllListeners(): void {\n    this.listeners.clear()\n  }\n\n  /**\n   * Get all recorded events.\n   */\n  getEvents(): RecordedEvent[] {\n    return [...this.events]\n  }\n\n  /**\n   * Get events of a specific type.\n   */\n  getEventsOf<T extends Event>(eventClass: EventClass<T>): RecordedEvent<T>[] {\n    return this.events.filter(\n      (e) => e.eventClass === eventClass || e.eventClass.name === eventClass.name\n    ) as RecordedEvent<T>[]\n  }\n\n  /**\n   * Clear all recorded events.\n   */\n  clear(): void {\n    this.events = []\n  }\n}\n\n/**\n * Fake event for testing event dispatches.\n */\nexport class FakeEvent {\n  private manager: FakeEventManager\n\n  constructor() {\n    this.manager = new FakeEventManager()\n  }\n\n  /**\n   * Get the underlying manager.\n   */\n  getManager(): FakeEventManager {\n    return this.manager\n  }\n\n  /**\n   * Record an event dispatch.\n   */\n  record<T extends Event>(event: T): void {\n    void this.manager.emit(event)\n  }\n\n  /**\n   * Assert an event was dispatched.\n   */\n  assertDispatched<T extends Event>(\n    eventClass: EventClass<T>,\n    callback?: (event: T) => boolean\n  ): void {\n    const events = this.manager.getEventsOf(eventClass)\n\n    if (events.length === 0) {\n      throw new Error(`Expected event [${eventClass.name}] to be dispatched`)\n    }\n\n    if (callback) {\n      const match = events.some((e) => callback(e.event))\n      if (!match) {\n        throw new Error(\n          `Expected event [${eventClass.name}] to match callback, but none did`\n        )\n      }\n    }\n  }\n\n  /**\n   * Assert an event was dispatched a specific number of times.\n   */\n  assertDispatchedTimes<T extends Event>(eventClass: EventClass<T>, times: number): void {\n    const events = this.manager.getEventsOf(eventClass)\n\n    if (events.length !== times) {\n      throw new Error(\n        `Expected event [${eventClass.name}] to be dispatched ${times} times, got ${events.length}`\n      )\n    }\n  }\n\n  /**\n   * Assert an event was not dispatched.\n   */\n  assertNotDispatched<T extends Event>(eventClass: EventClass<T>): void {\n    const events = this.manager.getEventsOf(eventClass)\n\n    if (events.length > 0) {\n      throw new Error(\n        `Expected event [${eventClass.name}] not to be dispatched, but it was dispatched ${events.length} times`\n      )\n    }\n  }\n\n  /**\n   * Assert no events were dispatched.\n   */\n  assertNothingDispatched(): void {\n    const events = this.manager.getEvents()\n\n    if (events.length > 0) {\n      const names = [...new Set(events.map((e) => e.eventClass.name))]\n      throw new Error(\n        `Expected no events to be dispatched, but found: ${names.join(', ')}`\n      )\n    }\n  }\n\n  /**\n   * Assert multiple events were dispatched in a specific order.\n   */\n  assertDispatchedInOrder(eventClasses: EventClass[]): void {\n    const events = this.manager.getEvents()\n\n    if (events.length < eventClasses.length) {\n      throw new Error(\n        `Expected ${eventClasses.length} events in order, but only ${events.length} were dispatched`\n      )\n    }\n\n    let eventIndex = 0\n    for (const eventClass of eventClasses) {\n      let found = false\n      while (eventIndex < events.length) {\n        if (\n          events[eventIndex].eventClass === eventClass ||\n          events[eventIndex].eventClass.name === eventClass.name\n        ) {\n          found = true\n          eventIndex++\n          break\n        }\n        eventIndex++\n      }\n\n      if (!found) {\n        throw new Error(\n          `Expected event [${eventClass.name}] to be dispatched in order, but it was not found`\n        )\n      }\n    }\n  }\n\n  /**\n   * Assert an event was dispatched with specific data.\n   */\n  assertDispatchedWith<T extends Event>(\n    eventClass: EventClass<T>,\n    data: Partial<T>\n  ): void {\n    const events = this.manager.getEventsOf(eventClass)\n\n    if (events.length === 0) {\n      throw new Error(`Expected event [${eventClass.name}] to be dispatched`)\n    }\n\n    const match = events.some((e) => {\n      for (const [key, value] of Object.entries(data)) {\n        // eslint-disable-next-line @typescript-eslint/no-explicit-any\n        if ((e.event as any)[key] !== value) {\n          return false\n        }\n      }\n      return true\n    })\n\n    if (!match) {\n      throw new Error(\n        `Expected event [${eventClass.name}] to be dispatched with matching data, but none matched`\n      )\n    }\n  }\n\n  /**\n   * Get dispatched events of a specific type.\n   */\n  dispatched<T extends Event>(eventClass: EventClass<T>): RecordedEvent<T>[] {\n    return this.manager.getEventsOf(eventClass)\n  }\n\n  /**\n   * Get all dispatched events.\n   */\n  all(): RecordedEvent[] {\n    return this.manager.getEvents()\n  }\n\n  /**\n   * Clear all recorded events.\n   */\n  clear(): void {\n    this.manager.clear()\n  }\n}\n\n/**\n * Create a fake event for testing.\n */\nexport function fakeEvent(): FakeEvent {\n  return new FakeEvent()\n}\n\n/**\n * Create a fake event manager for testing.\n * Can be used as a drop-in replacement for EventManager.\n */\nexport function fakeEventManager(): FakeEventManager {\n  return new FakeEventManager()\n}\n","/**\n * Agent tool calls in tests (RFC 0016 §6).\n *\n * Goes through the framework's own dispatch contract (`deriveAgentTools`,\n * `buildToolRequest`, `mapToolResponse`) and out through the same `fetch` every\n * other `TestApp` request uses; nothing here re-implements any of it, or a test\n * would pass while the tool an agent actually sees did something else.\n */\nimport type { DerivedAgentTool, RouteDefinition, ToolCallOutcome } from '@guren/server'\n\n/**\n * What a tool dispatch needs from the `TestApp` it belongs to. `routeDefinitions`\n * answers `undefined` (not an empty list) for a `TestApp` built from a bare\n * `fetch`, so {@link TestAgent} can name the constructor to use instead.\n */\nexport interface AgentTestBridge {\n  routeDefinitions(): readonly RouteDefinition[] | undefined\n  /** Origin the synthesized request is built on — the app's own `baseUrl`. */\n  baseUrl: string\n  /** Headers this `TestApp` sends on every request, `X-Testing-User` included. */\n  headers(): Record<string, string>\n  dispatch(request: Request): Promise<Response>\n  /** A bridge for the same app authenticating as `user` — see `TestApp.actingAs`. */\n  actingAs(user: unknown): AgentTestBridge\n}\n\n/** The three dispatch functions plus the predicate that reads a result. */\ninterface AgentRuntime {\n  deriveAgentTools(definitions: RouteDefinition[]): { tools: DerivedAgentTool[]; warnings: string[] }\n  buildToolRequest(\n    tool: DerivedAgentTool,\n    args: Record<string, unknown>,\n    options?: { origin?: string; preflight?: boolean },\n  ): { request: Request } | { missing: string[] } | { invalidPath: string[] }\n  mapToolResponse(tool: DerivedAgentTool, response: Response): Promise<ToolCallOutcome>\n  advertisesStructuredOutput(tool: DerivedAgentTool): boolean\n}\n\nlet runtimePromise: Promise<AgentRuntime> | undefined\n\n/**\n * `@guren/core` is an *optional* peer, so the import can fail — or succeed against\n * a version predating the agent interface, leaving every name `undefined` and\n * throwing a `TypeError` at call time. Hence the symbols are checked, not assumed.\n */\nasync function loadAgentRuntime(): Promise<AgentRuntime> {\n  runtimePromise ??= (async () => {\n    let loaded: Partial<AgentRuntime> | undefined\n    try {\n      loaded = (await import('@guren/core')) as Partial<AgentRuntime>\n    } catch {\n      try {\n        loaded = (await import('@guren/server')) as Partial<AgentRuntime>\n      } catch {\n        throw new Error(\n          'agent() needs the Guren framework installed: neither @guren/core nor @guren/server could be imported.',\n        )\n      }\n    }\n\n    const missing = (['deriveAgentTools', 'buildToolRequest', 'mapToolResponse', 'advertisesStructuredOutput'] as const)\n      .filter((name) => typeof loaded?.[name] !== 'function')\n\n    if (missing.length > 0) {\n      throw new Error(\n        // Names the capability, not a version number: which release first carries\n        // these exports is decided by `changeset version`.\n        `The installed @guren/core predates the agent dispatch contract (missing ${missing.join(', ')}). `\n          + 'agent() needs a @guren/core with the agent interface (RFC 0016) — upgrade it and try again.',\n      )\n    }\n\n    return loaded as AgentRuntime\n  })()\n\n  return runtimePromise\n}\n\n/** Options for one tool call. */\nexport interface AgentCallOptions {\n  /**\n   * Authenticate the call as this user, exactly as `TestApp.actingAs(user)` does.\n   * No token is involved, so bearer scopes are not part of this surface.\n   */\n  as?: unknown\n  /**\n   * Ask for a verdict instead of an execution (RFC 0016 §5.4): the request runs the\n   * route's middleware and validates the contract, then stops before the handler.\n   * MCP reaches the same seam through the `guren_preflight` companion tool instead.\n   */\n  preflight?: boolean\n}\n\n/**\n * The result of one tool call. Assertions here are synchronous;\n * {@link PendingAgentToolResult} carries the chainable spellings.\n */\nexport class AgentToolResult {\n  constructor(\n    /** The derived tool this call dispatched to. */\n    readonly tool: DerivedAgentTool,\n    /** The mapped outcome: content, structured content, error flag, status. */\n    readonly outcome: ToolCallOutcome,\n    /** The raw HTTP response, for assertions this class does not cover. */\n    readonly response: Response,\n    private readonly advertisesStructuredOutput: (tool: DerivedAgentTool) => boolean,\n  ) {}\n\n  /** The HTTP status the dispatch resolved to. */\n  get status(): number {\n    return this.outcome.status\n  }\n\n  /** True when the call came back as an MCP error result (4xx/5xx, mostly). */\n  get isError(): boolean {\n    return Boolean(this.outcome.isError)\n  }\n\n  /** Every text part of the result, joined — what an agent would read. */\n  get text(): string {\n    return this.outcome.content.map((part) => part.text).join('\\n')\n  }\n\n  /** The structured result, when the tool advertises an object output schema. */\n  get structuredContent(): Record<string, unknown> | undefined {\n    return this.outcome.structuredContent\n  }\n\n  assertStatus(code: number): this {\n    if (this.status !== code) {\n      throw new Error(\n        `Expected tool \"${this.tool.toolName}\" to answer ${code}, got ${this.status}: ${truncate(this.text)}`,\n      )\n    }\n    return this\n  }\n\n  /**\n   * Assert the call succeeded — not an error result. Deliberately not\n   * `assertStatus(200)` (which is what `PendingTestResponse.assertOk()` means): a\n   * 201 or 204 is a success, and MCP models the outcome as a boolean `isError`.\n   */\n  assertOk(): this {\n    if (this.isError) {\n      throw new Error(\n        `Expected tool \"${this.tool.toolName}\" to succeed, got HTTP ${this.status}: ${truncate(this.text)}`,\n      )\n    }\n    return this\n  }\n\n  /**\n   * Assert the application answered 401 or 403. Not a scope denial: this surface\n   * carries no bearer token, so assert scopes against the App MCP plugin's gate.\n   *\n   * A CSRF 403 is indistinguishable from a policy 403 — dispatch through\n   * `(await app.withCsrf()).agent()` or this can pass with no policy consulted.\n   */\n  assertDenied(): this {\n    if (this.status !== 401 && this.status !== 403) {\n      throw new Error(\n        `Expected tool \"${this.tool.toolName}\" to be denied (401 or 403), got ${this.status}: ${truncate(this.text)}`,\n      )\n    }\n    return this\n  }\n\n  /**\n   * Assert the call produced a structured result, and return it typed. The type\n   * parameter is the author's assertion; the route's `output` schema is the check.\n   */\n  assertStructured<T = Record<string, unknown>>(): T {\n    if (!this.advertisesStructuredOutput(this.tool)) {\n      throw new Error(\n        `Tool \"${this.tool.toolName}\" advertises no object output schema, so it can never return structured `\n          + 'content. Bind an `output` schema to the route (a Zod object) to make its result structured.',\n      )\n    }\n    if (!this.outcome.structuredContent) {\n      throw new Error(\n        `Expected tool \"${this.tool.toolName}\" to return structured content, got HTTP ${this.status}: `\n          + truncate(this.text),\n      )\n    }\n    return this.outcome.structuredContent as T\n  }\n\n  /** The result body parsed as JSON — for a tool with no output schema. */\n  json<T = unknown>(): T {\n    try {\n      return JSON.parse(this.text) as T\n    } catch {\n      throw new Error(\n        `Tool \"${this.tool.toolName}\" did not answer with JSON (HTTP ${this.status}): ${truncate(this.text)}`,\n      )\n    }\n  }\n}\n\n/** A promise-like {@link AgentToolResult}, so assertions chain on the call. */\nexport class PendingAgentToolResult implements PromiseLike<AgentToolResult> {\n  constructor(private readonly promise: Promise<AgentToolResult>) {}\n\n  then<TResult1 = AgentToolResult, TResult2 = never>(\n    onfulfilled?: ((value: AgentToolResult) => TResult1 | PromiseLike<TResult1>) | null,\n    onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n  ): PromiseLike<TResult1 | TResult2> {\n    return this.promise.then(onfulfilled, onrejected)\n  }\n\n  private chain(assert: (result: AgentToolResult) => void): PendingAgentToolResult {\n    return new PendingAgentToolResult(\n      this.promise.then((result) => {\n        assert(result)\n        return result\n      }),\n    )\n  }\n\n  assertStatus(code: number): PendingAgentToolResult {\n    return this.chain((result) => result.assertStatus(code))\n  }\n\n  assertOk(): PendingAgentToolResult {\n    return this.chain((result) => result.assertOk())\n  }\n\n  assertDenied(): PendingAgentToolResult {\n    return this.chain((result) => result.assertDenied())\n  }\n\n  /**\n   * Chainable form of {@link AgentToolResult.assertStructured}: returns the pending\n   * result, not the payload. `await` the call to get the value.\n   */\n  assertStructured(): PendingAgentToolResult {\n    return this.chain((result) => result.assertStructured())\n  }\n}\n\n/** The agent surface of a `TestApp` — reached through `app.agent()`. */\nexport class TestAgent {\n  constructor(private readonly bridge: AgentTestBridge) {}\n\n  /** Every tool this app exposes, as an agent would see them. */\n  async tools(): Promise<DerivedAgentTool[]> {\n    const { deriveAgentTools } = await loadAgentRuntime()\n    return deriveAgentTools([...this.requireDefinitions()]).tools\n  }\n\n  /** Call one tool by name, with a flat argument object. */\n  call(\n    name: string,\n    input: Record<string, unknown> = {},\n    options: AgentCallOptions = {},\n  ): PendingAgentToolResult {\n    return new PendingAgentToolResult(this.dispatch(name, input, options))\n  }\n\n  private requireDefinitions(): readonly RouteDefinition[] {\n    const definitions = this.bridge.routeDefinitions()\n    if (!definitions) {\n      throw new Error(\n        'This TestApp has no route registry, so no agent tool can be derived from it. '\n          + 'agent() needs an app whose routes it can see: build it with TestApp.create({ routes }) or '\n          + 'TestApp.fromApp(app). TestApp.fromFetch()/fromWorkers() are handed a bare fetch function, '\n          + 'which carries no route definitions.',\n      )\n    }\n    return definitions\n  }\n\n  private async dispatch(\n    name: string,\n    input: Record<string, unknown>,\n    options: AgentCallOptions,\n  ): Promise<AgentToolResult> {\n    const runtime = await loadAgentRuntime()\n    const definitions = this.requireDefinitions()\n\n    const { tools } = runtime.deriveAgentTools([...definitions])\n    const tool = tools.find((candidate) => candidate.toolName === name)\n    if (!tool) {\n      const available = tools.map((candidate) => candidate.toolName).sort()\n      throw new Error(\n        `No agent tool named \"${name}\".`\n          + (available.length > 0\n            ? ` This app exposes: ${available.join(', ')}.`\n            : ' This app exposes no agent tools — declare .agent() on a named route.'),\n      )\n    }\n\n    // Routed through `TestApp.actingAs` rather than spelling the `X-Testing-User`\n    // envelope a second time. Order matters: the tool was derived above from *this*\n    // bridge, so `{ as }` works even on a copy that lost its route definitions.\n    const bridge = options.as === undefined ? this.bridge : this.bridge.actingAs(options.as)\n\n    const built = runtime.buildToolRequest(tool, input, {\n      // The app's own baseUrl, not the dispatch default: `fromWorkers`/`fromApp` may\n      // serve another origin, and host authorization reads the Host header this sets.\n      origin: bridge.baseUrl,\n      preflight: options.preflight,\n    })\n\n    if ('missing' in built) {\n      throw new Error(\n        `Tool \"${name}\" needs path parameter${built.missing.length === 1 ? '' : 's'} `\n          + `${built.missing.join(', ')} for ${tool.method} ${tool.path}, which the input did not supply.`,\n      )\n    }\n    if ('invalidPath' in built) {\n      throw new Error(\n        `Tool \"${name}\" was given a URL dot-segment (\".\" or \"..\") for ${built.invalidPath.join(', ')}, `\n          + `which would resolve to a different path than ${tool.path}.`,\n      )\n    }\n\n    // The dispatch headers win; `X-Testing-User` and `withCsrf()`'s `Cookie` +\n    // `X-XSRF-TOKEN` fill in beneath them, or CSRF refuses a mutating call.\n    // Set on the built object: a copy loses the dispatcher's mark and force-https redirects it.\n    for (const [key, value] of Object.entries(bridge.headers())) {\n      if (!built.request.headers.has(key)) built.request.headers.set(key, value)\n    }\n\n    const response = await bridge.dispatch(built.request)\n    const outcome = await runtime.mapToolResponse(tool, response.clone())\n\n    return new AgentToolResult(tool, outcome, response, runtime.advertisesStructuredOutput)\n  }\n}\n\nfunction truncate(text: string, limit = 500): string {\n  return text.length > limit ? `${text.slice(0, limit)}…` : text\n}\n","/**\n * `app.fakeAi()` (RFC 0029 §7). Replaces the `ai` binding so every model an agent\n * resolves is scripted, while its tools still run for real through `appTools()`\n * and the invocation pipeline. Type-only imports: `@guren/plugin-ai` and `ai` are\n * optional peers, loaded by {@link loadFakeAiRuntime} when an app binds `ai`.\n */\nimport type { Container } from '@guren/server'\nimport type {\n  Agent,\n  AgentClass,\n  AgentPrincipalInput,\n  AgentResponse,\n  AiEvaluationModel,\n  AiEvaluationQuestion,\n  AiEvaluationQuestions,\n  AiManager,\n  AiProviderConfig,\n  BoundAgent,\n  BoundAgentFactory,\n  ConversationStore,\n  bindAgent,\n  resolveAgentName,\n} from '@guren/plugin-ai'\nimport type {\n  EmbeddingModel,\n  ImageModel,\n  LanguageModel,\n  StepResult,\n  ToolSet,\n  experimental_evaluate,\n  simulateStreamingMiddleware,\n  wrapLanguageModel,\n} from 'ai'\nimport type { Experimental_EvaluationMockModelV4, MockEmbeddingModelV4, MockImageModelV4, MockLanguageModelV4 } from 'ai/test'\n\n/** The model's final answer: plain text, or the value an agent's `output` schema parses. */\nexport type FakeAiAnswer = string | { text: string } | { output: unknown }\n\n/** One scripted prompt: an answer, or tool calls the model requests before answering. */\nexport type FakeAiResponse = FakeAiAnswer | { toolCalls: FakeAiToolCall[]; then: FakeAiResponse }\n\nexport interface FakeAiToolCall {\n  /** The tool's key in the agent's `tools()`. */\n  name: string\n  input?: Record<string, unknown>\n}\n\n/** A tool call the model made during a prompt, with what the real tool returned. */\nexport interface FakeAiRecordedToolCall {\n  name: string\n  input: unknown\n  /** Present when the tool returned. */\n  output?: unknown\n  /** Present when the tool threw, or its input failed validation: the error for `prompt()`, its message for `stream()`. */\n  error?: unknown\n}\n\nexport interface FakeAiCall {\n  input: string\n  principal: AgentPrincipalInput\n  /** Empty until the prompt settles (for `stream()`, until its body is read), and when no step finished. */\n  toolCalls: FakeAiRecordedToolCall[]\n  /** Set by `prompt()`; a `stream()` call answers with a `Response` instead. */\n  response?: AgentResponse<unknown>\n  error?: unknown\n}\n\n/** One value's vector. `respondEmbeddings` takes a queue of them, or a function answering every value. */\nexport type FakeAiEmbeddings = ReadonlyArray<readonly number[]> | ((value: string) => readonly number[])\n\n/**\n * What one `image()` call answers with: one image, or the several an `n > 1` call\n * asks for. A string is base64, which the SDK decodes to sniff the media type.\n */\nexport type FakeAiImages = string | Uint8Array | readonly string[] | readonly Uint8Array[]\n\nexport interface FakeAiEmbedCall {\n  /** One for `embed()`, the batch for `embedMany()`; empty when the fake refused the call. */\n  values: string[]\n  /** The provider name resolved for the call, the config's `default` included. */\n  provider: string\n}\n\nexport interface FakeAiImageCall {\n  /** Absent when the call passed only input images, or when the fake refused it. */\n  prompt?: string\n  /** How many images were asked for; `0` when the fake refused the call. */\n  n: number\n  provider: string\n}\n\nexport type FakeAiEvaluationAnswer =\n  | { type: 'choice'; choice: string; probabilities: Record<string, number> }\n  | { type: 'score'; score: number; probabilities?: Record<string, number> }\n  | { type: 'boolean'; probability: number }\n\n/**\n * One scripted evaluation, a value per question: a string is that choice at probability 1, a\n * number a boolean's probability or a score's position, an answer object passes through.\n * Checked against the questions when consumed, so a fake cannot answer what the real model could not.\n */\nexport type FakeAiEvaluation = Record<string, string | number | FakeAiEvaluationAnswer>\n\nexport interface FakeAiEvaluationCall {\n  /** Absent when the fake refused the call before the SDK handed it the state (a provider with no `evaluationModel`). */\n  state?: Parameters<typeof experimental_evaluate>[0]['state']\n  questions: AiEvaluationQuestions\n  /** The provider name resolved for the call, `defaultEvaluation` and `default` included. */\n  provider: string\n  answers?: Record<string, FakeAiEvaluationAnswer>\n  error?: unknown\n}\n\nexport interface FakeAiRuntime {\n  bindAgent: typeof bindAgent\n  resolveAgentName: typeof resolveAgentName\n  MockLanguageModelV4: typeof MockLanguageModelV4\n  MockEmbeddingModelV4: typeof MockEmbeddingModelV4\n  MockImageModelV4: typeof MockImageModelV4\n  EvaluationMockModelV4: typeof Experimental_EvaluationMockModelV4\n  wrapLanguageModel: typeof wrapLanguageModel\n  simulateStreamingMiddleware: typeof simulateStreamingMiddleware\n}\n\nlet runtimePromise: Promise<FakeAiRuntime | Error> | undefined\nlet loadedRuntime: FakeAiRuntime | Error | undefined\n\n/**\n * Import the optional peers once, so {@link createFakeAi} can stay synchronous. Settles to an\n * Error when either is missing or is a version without the names used here.\n */\nexport async function preloadFakeAiRuntime(): Promise<void> {\n  runtimePromise ??= loadFakeAiRuntime().catch((error: unknown) =>\n    error instanceof Error ? error : new Error(String(error)))\n  loadedRuntime = await runtimePromise\n}\n\nasync function loadFakeAiRuntime(): Promise<FakeAiRuntime> {\n  const [plugin, sdk, test] = await Promise.all([import('@guren/plugin-ai'), import('ai'), import('ai/test')])\n  const runtime: Partial<FakeAiRuntime> = {\n    bindAgent: plugin.bindAgent,\n    resolveAgentName: plugin.resolveAgentName,\n    MockLanguageModelV4: test.MockLanguageModelV4,\n    MockEmbeddingModelV4: test.MockEmbeddingModelV4,\n    MockImageModelV4: test.MockImageModelV4,\n    EvaluationMockModelV4: test.Experimental_EvaluationMockModelV4,\n    wrapLanguageModel: sdk.wrapLanguageModel,\n    simulateStreamingMiddleware: sdk.simulateStreamingMiddleware,\n  }\n  // An optional peer can resolve to an older copy, whose missing names import as `undefined`.\n  const missing = (Object.keys(runtime) as Array<keyof FakeAiRuntime>).filter((name) => typeof runtime[name] !== 'function')\n  if (missing.length > 0) {\n    throw new Error(\n      `the installed @guren/plugin-ai or ai does not export ${missing.join(', ')}; `\n      + 'upgrade @guren/plugin-ai to a release with fakeAi() support and ai to ^7.0.106.',\n    )\n  }\n  return runtime as FakeAiRuntime\n}\n\n/** `TestApp.fakeAi()` once the TestApp knows its container. */\nexport function createFakeAi(container: Container): FakeAi {\n  if (!container.has('ai')) {\n    throw new Error(\n      'This app binds no `ai` manager to fake. Add config/ai.ts (defineAiConfig from @guren/plugin-ai) '\n      + 'to createApp({ config }).',\n    )\n  }\n  if (!loadedRuntime || loadedRuntime instanceof Error) {\n    throw new Error(\n      'fakeAi() needs @guren/plugin-ai and ai installed, and could not import them'\n      + (loadedRuntime ? `: ${loadedRuntime.message}` : '.'),\n    )\n  }\n  return new FakeAi(container, loadedRuntime)\n}\n\nconst USAGE = {\n  inputTokens: { total: 0, noCache: 0, cacheRead: 0, cacheWrite: 0 },\n  outputTokens: { total: 0, text: 0, reasoning: 0 },\n}\n\n/**\n * The `ai` binding while faked. Scripts are keyed by agent wire name\n * (`resolveAgentName`), the identity audit lines and queued runs use.\n */\nexport class FakeAi implements AiManager, Disposable {\n  readonly config: AiManager['config']\n  private readonly scripts = new Map<string, FakeAiResponse[]>()\n  private readonly recorded = new Map<string, FakeAiCall[]>()\n  private readonly failures: string[] = []\n  /** Consumed one vector per value; a function answers every value and is never exhausted. */\n  private readonly embeddings: Array<readonly number[]> = []\n  private embedder?: (value: string) => readonly number[]\n  private readonly images: FakeAiImages[] = []\n  private readonly embedRecords: FakeAiEmbedCall[] = []\n  private readonly imageRecords: FakeAiImageCall[] = []\n  private readonly evaluationScripts: FakeAiEvaluation[] = []\n  private readonly evaluationRecords: FakeAiEvaluationCall[] = []\n  /** One per scripted prompt, read on dispose: a loop `stopWhen` ended early never asks for the rest. */\n  private readonly progress: Array<{ name: string; consumed: () => number; total: number }> = []\n  private readonly restore: Disposable\n  private readonly real: AiManager\n\n  constructor(\n    private readonly container: Container,\n    private readonly runtime: FakeAiRuntime,\n  ) {\n    this.real = container.make<AiManager>('ai')\n    this.config = this.real.config\n    this.restore = container.fake('ai', this)\n  }\n\n  /** Queue one response per future prompt of `cls`, consumed in order. */\n  respond(cls: AgentClass, responses: FakeAiResponse[]): this {\n    listFor(this.scripts, this.nameOf(cls)).push(...responses)\n    return this\n  }\n\n  calls(cls: AgentClass): readonly FakeAiCall[] {\n    return this.recorded.get(this.nameOf(cls)) ?? []\n  }\n\n  assertPrompted(cls: AgentClass, predicate?: (input: string, call: FakeAiCall) => boolean): void {\n    const name = this.nameOf(cls)\n    const calls = this.calls(cls)\n    if (calls.length === 0) {\n      throw new Error(`Expected agent [${name}] to be prompted, but it was not.${this.failureSuffix()}`)\n    }\n    if (predicate && !calls.some((call) => predicate(call.input, call))) {\n      throw new Error(\n        `Expected agent [${name}] to be prompted with matching input. It was prompted with: `\n        + `${calls.map((call) => JSON.stringify(call.input)).join(', ')}.${this.failureSuffix()}`,\n      )\n    }\n  }\n\n  /** No prompt of `cls` matches `predicate`; use {@link assertNeverPrompted} for none at all. */\n  assertNotPrompted(cls: AgentClass, predicate: (input: string, call: FakeAiCall) => boolean): void {\n    const match = this.calls(cls).find((call) => predicate(call.input, call))\n    if (match) {\n      throw new Error(`Unexpected prompt of agent [${this.nameOf(cls)}] with matching input: ${JSON.stringify(match.input)}.`)\n    }\n  }\n\n  assertNeverPrompted(cls: AgentClass): void {\n    const count = this.calls(cls).length\n    if (count > 0) {\n      throw new Error(`Expected agent [${this.nameOf(cls)}] never to be prompted, but it was prompted ${count} time(s).`)\n    }\n  }\n\n  /**\n   * Answer future `embed()` / `embedMany()` calls. An array is a queue drawn one\n   * vector per *value*, so a script does not depend on how the SDK batches a\n   * large `embedMany()`; a function answers every value instead.\n   */\n  respondEmbeddings(embeddings: FakeAiEmbeddings): this {\n    if (typeof embeddings === 'function') this.embedder = embeddings\n    else this.embeddings.push(...embeddings)\n    return this\n  }\n\n  /** Queue one entry per future `image()` call, consumed in order. */\n  respondImages(images: readonly FakeAiImages[]): this {\n    this.images.push(...images)\n    return this\n  }\n\n  embedCalls(): readonly FakeAiEmbedCall[] {\n    return this.embedRecords\n  }\n\n  imageCalls(): readonly FakeAiImageCall[] {\n    return this.imageRecords\n  }\n\n  assertEmbedded(predicate?: (call: FakeAiEmbedCall) => boolean): void {\n    this.assertCalled(EMBED_CALLS, this.embedRecords, predicate)\n  }\n\n  assertNeverEmbedded(): void {\n    this.assertNeverCalled(EMBED_CALLS, this.embedRecords)\n  }\n\n  assertGeneratedImage(predicate?: (call: FakeAiImageCall) => boolean): void {\n    this.assertCalled(IMAGE_CALLS, this.imageRecords, predicate)\n  }\n\n  assertNeverGeneratedImage(): void {\n    this.assertNeverCalled(IMAGE_CALLS, this.imageRecords)\n  }\n\n  /** Queue one answer set per future `evaluate()` call, consumed in order. */\n  respondEvaluations(evaluations: readonly FakeAiEvaluation[]): this {\n    this.evaluationScripts.push(...evaluations)\n    return this\n  }\n\n  evaluationCalls(): readonly FakeAiEvaluationCall[] {\n    return this.evaluationRecords\n  }\n\n  assertEvaluated(predicate?: (call: FakeAiEvaluationCall) => boolean): void {\n    this.assertCalled(EVALUATION_CALLS, this.evaluationRecords, predicate)\n  }\n\n  assertNeverEvaluated(): void {\n    this.assertNeverCalled(EVALUATION_CALLS, this.evaluationRecords)\n  }\n\n  agent<T extends Agent>(cls: AgentClass<T>): BoundAgentFactory<T> {\n    const name = this.nameOf(cls)\n    return {\n      as: (principal) => {\n        // A manager per agent, because `model()` is told the provider and never the class.\n        const manager: AiManager = {\n          config: this.config,\n          agent: (other) => this.agent(other),\n          model: (provider) => this.scriptedModel(name, provider),\n          embeddingModel: (provider) => this.embeddingModel(provider),\n          imageModel: (provider) => this.imageModel(provider),\n          evaluationModel: (provider) => this.evaluationModel(provider),\n          conversations: () => this.conversations(),\n        }\n        const bound = this.runtime.bindAgent(cls, principal, { container: this.container, manager })\n        return this.recording(name, principal, bound)\n      },\n    }\n  }\n\n  model(provider?: string): LanguageModel {\n    return this.fail(\n      `ai.model(${provider === undefined ? '' : JSON.stringify(provider)}) was called outside an agent. `\n      + 'fakeAi() scripts agents: prompt through ai.agent(Class).as(...) and script it with ai.respond(Class, [...]).',\n    )\n  }\n\n  embeddingModel(provider?: string): EmbeddingModel {\n    const record = this.recordCall(EMBED_CALLS, this.embedRecords, { values: [], provider: provider ?? this.config.default })\n    if (this.embedder === undefined && this.embeddings.length === 0) this.fail(unscripted(EMBED_CALLS))\n    return new this.runtime.MockEmbeddingModelV4({\n      modelId: `fake:${record.provider}`,\n      // Infinity is the SDK's \"no limit\": without it the mock's default of 1 splits\n      // an embedMany() into one doEmbed per value.\n      maxEmbeddingsPerCall: Number.POSITIVE_INFINITY,\n      doEmbed: async ({ values }) => {\n        record.values.push(...values)\n        return { embeddings: values.map((value) => this.vectorFor(value)), warnings: [] }\n      },\n    })\n  }\n\n  imageModel(provider?: string): ImageModel {\n    const record = this.recordCall(IMAGE_CALLS, this.imageRecords, { n: 0, provider: provider ?? this.config.default })\n    const scripted = this.images.shift()\n    if (scripted === undefined) this.fail(unscripted(IMAGE_CALLS))\n    const images = scriptedImages(scripted)\n    const modelId = `fake:${record.provider}`\n    return new this.runtime.MockImageModelV4({\n      modelId,\n      // No limit of the model's own, so `n` alone never splits the call. A caller\n      // passing generateImage's own maxImagesPerCall still can, which is why `n` sums.\n      maxImagesPerCall: Number.MAX_SAFE_INTEGER,\n      doGenerate: async ({ prompt, n }) => {\n        record.n += n\n        if (prompt !== undefined) record.prompt = prompt\n        return {\n          images,\n          warnings: [],\n          // A scripted empty array is the test's choice; the SDK would otherwise retry it.\n          isRetryable: false,\n          response: { timestamp: new Date(0), modelId, headers: undefined },\n        }\n      },\n    })\n  }\n\n  evaluationModel(provider?: string): AiEvaluationModel {\n    const selected = provider ?? this.config.defaultEvaluation ?? this.config.default\n    // The state arrives only in doEvaluate, so a refused call is recorded without one.\n    const record = this.recordCall(EVALUATION_CALLS, this.evaluationRecords, { questions: {}, provider: selected })\n    return new this.runtime.EvaluationMockModelV4({\n      provider: 'fake',\n      modelId: `fake:${selected}`,\n      supportedQuestionTypes: ['choice', 'score', 'boolean'],\n      doEvaluate: async ({ state, questions }) => {\n        record.state = state\n        record.questions = questions\n        try {\n          const script = this.evaluationScripts.shift()\n          if (script === undefined) throw new Error(unscripted(EVALUATION_CALLS, ` (state ${JSON.stringify(state).slice(0, 80)})`))\n          record.answers = expandEvaluation(script, questions)\n          return { answers: record.answers, warnings: [] }\n        } catch (error) {\n          record.error = error\n          return this.fail(error instanceof Error ? error.message : String(error))\n        }\n      },\n    })\n  }\n\n  /**\n   * Recorded before anything can refuse the call, as a prompt is: a call the fake\n   * rejected was still a call, and an assertion saying it never happened would lie.\n   */\n  private recordCall<C extends { provider: string }>(kind: ModelCallKind<C>, records: C[], record: C): C {\n    records.push(record)\n    this.checkProvider(kind.caller, kind.factory, record.provider)\n    return record\n  }\n\n  private assertCalled<C>(kind: ModelCallKind<C>, records: readonly C[], predicate?: (call: C) => boolean): void {\n    if (records.length === 0) {\n      throw new Error(`Expected ${kind.caller} to be called, but it was not.${this.failureSuffix()}`)\n    }\n    if (predicate && !records.some((call) => predicate(call))) {\n      throw new Error(\n        `Expected ${kind.caller} to be called with ${kind.matching}. It was called with: `\n        + `${records.map((call) => JSON.stringify(kind.describe(call))).join(', ')}.${this.failureSuffix()}`,\n      )\n    }\n  }\n\n  private assertNeverCalled<C>(kind: ModelCallKind<C>, records: readonly C[]): void {\n    if (records.length > 0) {\n      throw new Error(`Expected ${kind.never} ${records.length} time(s).`)\n    }\n  }\n\n  private vectorFor(value: string): number[] {\n    if (this.embedder) return [...this.embedder(value)]\n    const next = this.embeddings.shift()\n    if (next === undefined) {\n      this.fail(\n        `embed() or embedMany() asked for the embedding of ${JSON.stringify(value)}, and the script is exhausted. `\n        + 'Script one vector per value with ai.respondEmbeddings([...]), or pass a function.',\n      )\n    }\n    return [...next]\n  }\n\n  /** Refuse a provider name config/ai.ts does not configure; shared with the prompt path. */\n  private checkConfigured(subject: string, selected: string): void {\n    if (!Object.hasOwn(this.config.providers, selected)) {\n      this.fail(\n        `${subject} names the AI provider \"${selected}\", which config/ai.ts does not configure `\n        + `(it configures: ${Object.keys(this.config.providers).join(', ') || '(none)'}).`,\n      )\n    }\n  }\n\n  private checkProvider(caller: string, kind: Exclude<keyof AiProviderConfig, 'pricing'>, selected: string): void {\n    this.checkConfigured(caller, selected)\n    // Checked, never called: the fake answers the call, but a provider with no factory\n    // would throw outside the fake, and a test that passes there is measuring nothing.\n    if (!this.config.providers[selected]?.[kind]) {\n      this.fail(`${caller} resolves the AI provider \"${selected}\", which configures no ${kind} in config/ai.ts.`)\n    }\n  }\n\n  /** The real manager's store: fakeAi() scripts the model, and conversations persist as configured. */\n  conversations(): ConversationStore {\n    return this.real.conversations()\n  }\n\n  /** Restores the binding, then fails on any prompt that found nothing scripted or left steps unused. */\n  [Symbol.dispose](): void {\n    this.restore[Symbol.dispose]()\n    const unused = this.progress\n      .filter((prompt) => prompt.consumed() < prompt.total)\n      .map((prompt) =>\n        `Agent [${prompt.name}] stopped after ${prompt.consumed()} of its ${prompt.total} scripted steps; `\n        + 'the loop ended before the scripted answer (check the agent\\'s stopWhen).')\n    if (this.failures.length + unused.length > 0) {\n      throw new Error(`fakeAi() found calls its script did not answer:${formatList([...this.failures, ...unused])}`)\n    }\n  }\n\n  private recording<T extends Agent>(name: string, principal: AgentPrincipalInput, bound: BoundAgent<T>): BoundAgent<T> {\n    const record = async <R>(input: string, run: (call: FakeAiCall) => Promise<R>): Promise<R> => {\n      const call: FakeAiCall = { input, principal, toolCalls: [] }\n      // Recorded on entry: a call that throws was still made.\n      listFor(this.recorded, name).push(call)\n      try {\n        return await run(call)\n      } catch (error) {\n        call.error = error\n        throw error\n      }\n    }\n    return {\n      agent: bound.agent,\n      continue: (id) => this.recording(name, principal, bound.continue(id)),\n      history: (id) => bound.history(id),\n      prompt: (input, options) => record(input, async (call) => {\n        const response = await bound.prompt(input, options)\n        call.response = response\n        call.toolCalls = recordedToolCalls(response.steps)\n        return response\n      }),\n      stream: (input, options) => record(input, async (call) => tapToolCalls(await bound.stream(input, options), call)),\n      // Not recorded here: the worker's run comes back through agent() and records then.\n      queue: (input, options) => bound.queue(input, options),\n      broadcast: (input, channel, options) => bound.broadcast(input, channel, options),\n    }\n  }\n\n  private scriptedModel(name: string, provider: string | undefined): LanguageModel {\n    const selected = provider ?? this.config.default\n    this.checkProvider(`Agent [${name}]`, 'model', selected)\n    const response = this.scripts.get(name)?.shift()\n    if (response === undefined) {\n      return this.fail(\n        `Agent [${name}] was prompted, but nothing is scripted for it. `\n        + `Script it with ai.respond(${name}, [...]) before the prompt.`,\n      )\n    }\n\n    const steps = flatten(response)\n    let step = 0\n    this.progress.push({ name, consumed: () => step, total: steps.length })\n    const model = new this.runtime.MockLanguageModelV4({\n      modelId: `fake:${name}`,\n      doGenerate: async () => {\n        const index = step++\n        const current = steps[index]\n        // Unreachable while `bindAgent` resolves a model per prompt; guards a memoized one.\n        if (current === undefined) {\n          return this.fail(`Agent [${name}] asked the model for step ${index + 1}, but its scripted response has ${steps.length}.`)\n        }\n        if ('text' in current) {\n          return { content: [{ type: 'text', text: current.text }], finishReason: { unified: 'stop', raw: undefined }, usage: USAGE, warnings: [] }\n        }\n        return {\n          content: current.toolCalls.map((toolCall, callIndex) => ({\n            type: 'tool-call',\n            toolCallId: `fake-${index}-${callIndex}`,\n            toolName: toolCall.name,\n            input: JSON.stringify(toolCall.input ?? {}),\n          })),\n          finishReason: { unified: 'tool-calls', raw: undefined },\n          usage: USAGE,\n          warnings: [],\n        }\n      },\n    })\n    // `stream()` reaches the same script: the middleware answers doStream from doGenerate.\n    return this.runtime.wrapLanguageModel({ model, middleware: this.runtime.simulateStreamingMiddleware() })\n  }\n\n  private fail(message: string): never {\n    this.failures.push(message)\n    throw new Error(message)\n  }\n\n  private failureSuffix(): string {\n    return this.failures.length > 0 ? `\\nUnscripted model calls:${formatList(this.failures)}` : ''\n  }\n\n  private nameOf(cls: AgentClass): string {\n    return this.runtime.resolveAgentName(cls)\n  }\n}\n\n/** The wording one family of model calls contributes to the fake's failure messages. */\ninterface ModelCallKind<C> {\n  caller: string\n  factory: Exclude<keyof AiProviderConfig, 'pricing'>\n  /** The `assertNever*` clause up to the count; embed's is plural, so it is not derived from `caller`. */\n  never: string\n  matching: string\n  script: string\n  describe: (call: C) => unknown\n}\n\nconst EMBED_CALLS: ModelCallKind<FakeAiEmbedCall> = {\n  caller: 'embed() or embedMany()',\n  factory: 'embeddingModel',\n  never: 'embed() and embedMany() never to be called, but they were called',\n  matching: 'matching values',\n  script: 'ai.respondEmbeddings([...])',\n  describe: (call) => call.values,\n}\n\nconst IMAGE_CALLS: ModelCallKind<FakeAiImageCall> = {\n  caller: 'image()',\n  factory: 'imageModel',\n  never: 'image() never to be called, but it was called',\n  matching: 'a matching prompt',\n  script: 'ai.respondImages([...])',\n  describe: (call) => call.prompt,\n}\n\nconst EVALUATION_CALLS: ModelCallKind<FakeAiEvaluationCall> = {\n  caller: 'evaluate()',\n  factory: 'evaluationModel',\n  never: 'evaluate() never to be called, but it was called',\n  matching: 'a matching state',\n  script: 'ai.respondEvaluations([{ ... }])',\n  describe: (call) => call.state,\n}\n\nfunction unscripted(kind: ModelCallKind<never>, detail = ''): string {\n  return `${kind.caller} was called${detail}, but nothing is scripted for it. Script it with ${kind.script} before the call.`\n}\n\n/** One script entry's images, keeping the homogeneous array the SDK's result type wants. */\nfunction scriptedImages(scripted: FakeAiImages): string[] | Uint8Array[] {\n  if (typeof scripted === 'string') return [scripted]\n  if (scripted instanceof Uint8Array) return [scripted]\n  return scripted.slice()\n}\n\nfunction oneHot(keys: readonly string[], hit: string): Record<string, number> {\n  return Object.fromEntries(keys.map((key) => [key, key === hit ? 1 : 0]))\n}\n\nfunction expandAnswer(id: string, question: AiEvaluationQuestion, value: FakeAiEvaluation[string]): FakeAiEvaluationAnswer {\n  if (typeof value === 'object') return value\n  const given = `ai.respondEvaluations() gives question \"${id}\" ${JSON.stringify(value)}`\n  switch (question.type) {\n    case 'choice': {\n      const options = Object.keys(question.criteria)\n      if (typeof value !== 'string' || !options.includes(value)) throw new Error(`${given}, not one of its options: ${options.join(', ')}.`)\n      return { type: 'choice', choice: value, probabilities: oneHot(options, value) }\n    }\n    case 'score': {\n      const top = question.criteria.length - 1\n      if (typeof value !== 'number' || value < 0 || value > top) throw new Error(`${given}; a score is a number from 0 to ${top}.`)\n      const levels = question.criteria.map((_, index) => String(index))\n      return { type: 'score', score: value, ...(Number.isInteger(value) ? { probabilities: oneHot(levels, String(value)) } : {}) }\n    }\n    case 'boolean': {\n      if (typeof value !== 'number' || value < 0 || value > 1) throw new Error(`${given}; a boolean answer is a probability from 0 to 1.`)\n      return { type: 'boolean', probability: value }\n    }\n  }\n}\n\n/** One answer per question. The SDK validates the result too; these messages name the script, which its would not. */\nfunction expandEvaluation(script: FakeAiEvaluation, questions: AiEvaluationQuestions): Record<string, FakeAiEvaluationAnswer> {\n  const unknown = Object.keys(script).filter((id) => !Object.hasOwn(questions, id))\n  if (unknown.length > 0) {\n    throw new Error(`ai.respondEvaluations() scripts ${unknown.map((id) => JSON.stringify(id)).join(', ')}, which the evaluation does not ask (it asks: ${Object.keys(questions).join(', ')}).`)\n  }\n  return Object.fromEntries(Object.entries(questions).map(([id, question]) => {\n    const value = script[id]\n    if (value === undefined) throw new Error(`ai.respondEvaluations() scripts no value for question \"${id}\".`)\n    return [id, expandAnswer(id, question, value)]\n  }))\n}\n\nfunction listFor<T>(lists: Map<string, T[]>, key: string): T[] {\n  let list = lists.get(key)\n  if (!list) lists.set(key, (list = []))\n  return list\n}\n\nfunction formatList(lines: readonly string[]): string {\n  return lines.map((line) => `\\n- ${line}`).join('')\n}\n\ntype FakeAiStep = { toolCalls: FakeAiToolCall[] } | { text: string }\n\nfunction flatten(response: FakeAiResponse): FakeAiStep[] {\n  if (typeof response === 'string') return [{ text: response }]\n  if ('toolCalls' in response) return [{ toolCalls: response.toolCalls }, ...flatten(response.then)]\n  if ('output' in response) return [{ text: JSON.stringify(response.output) }]\n  return [{ text: response.text }]\n}\n\n/** Fill `call.toolCalls` from the UI-message chunks as the body is read, passing every byte through. */\nfunction tapToolCalls(response: Response, call: FakeAiCall): Response {\n  if (!response.body) return response\n  const decoder = new TextDecoder()\n  const byId = new Map<string, FakeAiRecordedToolCall>()\n  let pending = ''\n  const tap = new TransformStream<Uint8Array, Uint8Array>({\n    transform(bytes, controller) {\n      controller.enqueue(bytes)\n      pending += decoder.decode(bytes, { stream: true })\n      const lines = pending.split('\\n')\n      pending = lines.pop() ?? ''\n      for (const line of lines) {\n        if (!line.startsWith('data: {\"type\":\"tool-')) continue\n        const chunk = JSON.parse(line.slice('data: '.length)) as { type: string; toolCallId?: string; toolName?: string; input?: unknown; output?: unknown; errorText?: string }\n        if ((chunk.type === 'tool-input-available' || chunk.type === 'tool-input-error') && chunk.toolCallId) {\n          const recorded: FakeAiRecordedToolCall = {\n            name: chunk.toolName ?? '',\n            input: chunk.input,\n            ...(chunk.type === 'tool-input-error' ? { error: chunk.errorText } : {}),\n          }\n          byId.set(chunk.toolCallId, recorded)\n          call.toolCalls.push(recorded)\n        } else if (chunk.type === 'tool-output-available' && chunk.toolCallId) {\n          const recorded = byId.get(chunk.toolCallId)\n          if (recorded) recorded.output = chunk.output\n        } else if (chunk.type === 'tool-output-error' && chunk.toolCallId) {\n          const recorded = byId.get(chunk.toolCallId)\n          if (recorded) recorded.error = chunk.errorText\n        }\n      }\n    },\n  })\n  return new Response(response.body.pipeThrough(tap), response)\n}\n\nfunction recordedToolCalls(steps: ReadonlyArray<StepResult<ToolSet>>): FakeAiRecordedToolCall[] {\n  return steps.flatMap((step) =>\n    step.toolCalls.map((toolCall) => {\n      const settled = step.content.find(\n        (part) => (part.type === 'tool-result' || part.type === 'tool-error') && part.toolCallId === toolCall.toolCallId,\n      )\n      return {\n        name: toolCall.toolName,\n        input: toolCall.input,\n        ...(settled?.type === 'tool-result' ? { output: settled.output } : {}),\n        ...(settled?.type === 'tool-error' ? { error: settled.error } : {}),\n      }\n    }))\n}\n","import type { Hono } from 'hono'\nimport type {\n  Container,\n  EnvSchema,\n  I18nPluginOptions,\n  RouteDefinition,\n  Router,\n  ServiceProviderConstructor,\n} from '@guren/server'\nimport { TestResponse } from './http'\nimport { testingHeaderValue } from './testing-header'\nimport { TestAgent, type AgentTestBridge } from './agent'\nimport { createFakeAi, preloadFakeAiRuntime, type FakeAi } from './ai'\n\ntype BootCallback = (app: Hono) => void | Promise<void>\ntype ProviderLike = { register?(): unknown; boot?(): unknown }\n/**\n * Constructor shape for a provider class passed to `TestApp.create()`. `any[]`, not\n * `unknown[]`: constructor parameters are contravariant, and every real\n * `ServiceProvider` subclass inherits a constructor taking a concrete `Container`.\n * Structural, so the published `.d.ts` resolves for an app depending only on\n * `@guren/core` instead of widening to `any` under `skipLibCheck`.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype ProviderConstructor = new (...args: any[]) => ProviderLike\ntype RouteRegistration = (router: Router) => void | Promise<void>\ntype ApplicationLike = {\n  boot(): Promise<void>\n  fetch(request: Request): Response | Promise<Response>\n  /**\n   * The app-local route registry, read after `boot()` so `agent()` derives tools from\n   * the graph this app serves. Optional: a `@guren/core` without the agent interface\n   * has none, and `agent()` must say so rather than throw on an internal.\n   */\n  readonly router?: { definitions(): RouteDefinition[] }\n  /** What `fakeAi()` swaps the `ai` binding in. Optional for the same reason as `router`. */\n  readonly container?: Container\n}\n/**\n * The `Application` constructor as this file calls it — structural for the same\n * reason as {@link ProviderConstructor}, but faithful to the real signature so the\n * dynamic imports stay type-checked. `providers` names `ServiceProviderConstructor`,\n * not the looser shape `TestAppOptions` accepts; they meet at the `new Application()`.\n */\ntype ApplicationConstructor = new (options: {\n  boot?: BootCallback\n  providers?: ServiceProviderConstructor[]\n  routes?: RouteRegistration\n  auth?: Record<string, unknown>\n  i18n?: I18nPluginOptions\n  env?: EnvSchema\n}) => ApplicationLike & { readonly container: Container }\n\n/**\n * Options for creating a TestApp instance.\n */\nexport interface TestAppOptions {\n  readonly boot?: BootCallback\n  readonly providers?: ProviderConstructor[]\n  readonly routes?: RouteRegistration\n  /**\n   * Mirrors `createApp({ auth })`: pass `{}` (or full auth options) to mount\n   * session + CSRF middleware so tests exercise production-like behavior.\n   * Required for `withCsrf()` to work. Ignored by the Hono fallback used when\n   * `@guren/server` is not installed.\n   */\n  readonly auth?: Record<string, unknown>\n  /**\n   * Mirrors `createApp({ i18n })`: required when controllers under test use\n   * `this.t()`/`this.tc()`. Ignored by the Hono fallback.\n   */\n  readonly i18n?: I18nPluginOptions\n  /** Mirrors `createApp({ env })`: the schema `config/env.ts` exports, validated when the app boots. */\n  readonly env?: EnvSchema\n  /**\n   * Values the schema reads ahead of `process.env`, bound as `env.source` before\n   * boot, so a test overrides one variable without mutating the process. `''`\n   * makes a variable unset; a missing key falls back to `process.env`.\n   */\n  readonly envSource?: Readonly<Record<string, string>>\n}\n\n/**\n * Fake ExecutionContext exposed by `TestApp.fromWorkers()`, so tests can\n * await promises the handler passed to `ctx.waitUntil()`.\n */\nexport interface WorkersTestContext {\n  /** Promises passed to ctx.waitUntil by the handler, for tests to await. */\n  readonly waitUntilPromises: Promise<unknown>[]\n}\n\ntype WorkersExecutionContext = {\n  waitUntil(promise: Promise<unknown>): void\n  passThroughOnException?(): void\n}\n\ntype WorkersHandler = {\n  fetch(\n    request: Request,\n    env: unknown,\n    ctx: WorkersExecutionContext,\n  ): Response | Promise<Response>\n}\n\nexport interface WorkersTestAppOptions {\n  readonly env?: unknown\n  readonly baseUrl?: string\n}\n\n/** A promise-like TestResponse, so assertions chain on an HTTP method call. */\nexport class PendingTestResponse implements PromiseLike<TestResponse> {\n  private promise: Promise<TestResponse>\n\n  constructor(promise: Promise<TestResponse>) {\n    this.promise = promise\n  }\n\n  then<TResult1 = TestResponse, TResult2 = never>(\n    onfulfilled?: ((value: TestResponse) => TResult1 | PromiseLike<TResult1>) | null,\n    onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n  ): PromiseLike<TResult1 | TResult2> {\n    return this.promise.then(onfulfilled, onrejected)\n  }\n\n  /**\n   * Assert the response status code.\n   */\n  assertStatus(code: number): PendingTestResponse {\n    return new PendingTestResponse(\n      this.promise.then((r) => {\n        r.assertStatus(code)\n        return r\n      }),\n    )\n  }\n\n  /**\n   * Assert the response is OK (200).\n   */\n  assertOk(): PendingTestResponse {\n    return this.assertStatus(200)\n  }\n\n  /**\n   * Assert the response is Created (201).\n   */\n  assertCreated(): PendingTestResponse {\n    return this.assertStatus(201)\n  }\n\n  /**\n   * Assert the response is No Content (204).\n   */\n  assertNoContent(): PendingTestResponse {\n    return this.assertStatus(204)\n  }\n\n  /**\n   * Assert the response is a redirect.\n   */\n  assertRedirect(url?: string): PendingTestResponse {\n    return new PendingTestResponse(\n      this.promise.then((r) => {\n        r.assertRedirect(url)\n        return r\n      }),\n    )\n  }\n\n  /**\n   * Assert the response is Not Found (404).\n   */\n  assertNotFound(): PendingTestResponse {\n    return this.assertStatus(404)\n  }\n\n  /**\n   * Assert the response is Forbidden (403).\n   */\n  assertForbidden(): PendingTestResponse {\n    return this.assertStatus(403)\n  }\n\n  /**\n   * Assert the response is Unauthorized (401).\n   */\n  assertUnauthorized(): PendingTestResponse {\n    return this.assertStatus(401)\n  }\n\n  /**\n   * Assert the response is Unprocessable Entity (422).\n   */\n  assertUnprocessable(): PendingTestResponse {\n    return this.assertStatus(422)\n  }\n\n  /**\n   * Assert the response JSON matches the expected value.\n   */\n  assertJson(expected: Record<string, unknown>): PendingTestResponse {\n    return new PendingTestResponse(\n      this.promise.then(async (r) => {\n        await r.assertJson(expected)\n        return r\n      }),\n    )\n  }\n\n  /**\n   * Assert the response JSON array (or a nested key) has the expected count.\n   */\n  assertJsonCount(count: number, key?: string): PendingTestResponse {\n    return new PendingTestResponse(\n      this.promise.then(async (r) => {\n        const json = await r.json()\n        const target = key ? getNestedValue(json, key) : json\n\n        if (!Array.isArray(target)) {\n          throw new Error(\n            `Expected ${key ? `\"${key}\"` : 'response'} to be an array, got ${typeof target}`,\n          )\n        }\n\n        if (target.length !== count) {\n          throw new Error(\n            `Expected ${key ? `\"${key}\"` : 'response'} to have ${count} items, got ${target.length}`,\n          )\n        }\n\n        return r\n      }),\n    )\n  }\n\n  /**\n   * Assert the response JSON has the given keys.\n   */\n  assertJsonStructure(keys: string[]): PendingTestResponse {\n    return new PendingTestResponse(\n      this.promise.then(async (r) => {\n        const json = (await r.json()) as Record<string, unknown>\n\n        for (const key of keys) {\n          if (!(key in json)) {\n            throw new Error(`Expected JSON to have key \"${key}\"`)\n          }\n        }\n\n        return r\n      }),\n    )\n  }\n\n  /**\n   * Assert a value at a dot-notation path in the JSON response.\n   */\n  assertJsonPath(path: string, value: unknown): PendingTestResponse {\n    return new PendingTestResponse(\n      this.promise.then(async (r) => {\n        await r.assertJsonPath(path, value)\n        return r\n      }),\n    )\n  }\n\n  /**\n   * Assert the response is an Inertia response with the given component.\n   */\n  assertInertia(component: string, props?: Record<string, unknown>): PendingTestResponse {\n    return new PendingTestResponse(\n      this.promise.then(async (r) => {\n        const json = (await r.json()) as Record<string, unknown>\n\n        const inertiaComponent = json.component\n        if (inertiaComponent !== component) {\n          throw new Error(\n            `Expected Inertia component \"${component}\", got \"${String(inertiaComponent)}\"`,\n          )\n        }\n\n        if (props) {\n          const inertiaProps = json.props as Record<string, unknown> | undefined\n          if (!inertiaProps) {\n            throw new Error('Expected Inertia response to have props')\n          }\n\n          for (const [key, expectedValue] of Object.entries(props)) {\n            const actual = inertiaProps[key]\n            const expectedStr = JSON.stringify(expectedValue)\n            const actualStr = JSON.stringify(actual)\n\n            if (expectedStr !== actualStr) {\n              throw new Error(\n                `Expected Inertia prop \"${key}\" to be ${expectedStr}, got ${actualStr}`,\n              )\n            }\n          }\n        }\n\n        return r\n      }),\n    )\n  }\n\n  /**\n   * Assert the response has a specific cookie.\n   */\n  assertCookie(name: string, value?: string): PendingTestResponse {\n    return new PendingTestResponse(\n      this.promise.then((r) => {\n        const cookies = r.headers.getSetCookie()\n        const found = cookies.some((c) => {\n          const [pair] = c.split(';')\n          const [cookieName, cookieValue] = pair.split('=')\n          if (cookieName.trim() !== name) return false\n          if (value !== undefined && cookieValue?.trim() !== value) return false\n          return true\n        })\n\n        if (!found) {\n          throw new Error(\n            value !== undefined\n              ? `Expected cookie \"${name}\" with value \"${value}\"`\n              : `Expected cookie \"${name}\" to exist`,\n          )\n        }\n\n        return r\n      }),\n    )\n  }\n\n  /**\n   * Assert the response does not have a specific cookie.\n   */\n  assertCookieMissing(name: string): PendingTestResponse {\n    return new PendingTestResponse(\n      this.promise.then((r) => {\n        const cookies = r.headers.getSetCookie()\n        const found = cookies.some((c) => {\n          const [pair] = c.split(';')\n          const [cookieName] = pair.split('=')\n          return cookieName.trim() === name\n        })\n\n        if (found) {\n          throw new Error(`Expected cookie \"${name}\" to be missing`)\n        }\n\n        return r\n      }),\n    )\n  }\n\n  /**\n   * Assert the response has a specific header.\n   */\n  assertHeader(name: string, value?: string): PendingTestResponse {\n    return new PendingTestResponse(\n      this.promise.then((r) => {\n        r.assertHeader(name, value)\n        return r\n      }),\n    )\n  }\n\n  /**\n   * Assert the response does not have a specific header.\n   */\n  assertHeaderMissing(name: string): PendingTestResponse {\n    return new PendingTestResponse(\n      this.promise.then((r) => {\n        r.assertHeaderMissing(name)\n        return r\n      }),\n    )\n  }\n}\n\n/**\n * Integrated HTTP test client wrapping the Application class. Uses `app.fetch()`\n * internally, so no running HTTP server is needed.\n * @example\n * await app.get('/posts').assertOk().assertJsonCount(1)\n * await app.actingAs(user).get('/dashboard').assertOk()\n */\nexport class TestApp {\n  private baseUrl: string\n  private fetchFn: (request: Request) => Promise<Response>\n  private defaultHeaders: Record<string, string> = {}\n  private authenticatedUser: unknown = null\n  /**\n   * The app's route definitions when built from an Application. Undefined — never an\n   * empty list — for `fromFetch`/`fromWorkers`, so `agent()` can tell \"no tools\" from\n   * \"this construction cannot see any routes\".\n   */\n  private routeDefinitions?: readonly RouteDefinition[]\n  /** The booted app's container; undefined for `fromFetch`/`fromWorkers`, like `routeDefinitions`. */\n  private container?: Container\n  /** Present when created via fromWorkers(); propagated across builder copies. */\n  workers?: WorkersTestContext\n\n  private constructor(\n    fetchFn: (request: Request) => Promise<Response>,\n    baseUrl = 'http://localhost',\n  ) {\n    this.baseUrl = baseUrl.replace(/\\/$/, '')\n    this.fetchFn = fetchFn\n  }\n\n  /**\n   * Create a new TestApp by booting an Application instance. The Application is\n   * imported dynamically; without `@guren/server` a Hono-based fallback is used.\n   */\n  static async create(options: TestAppOptions = {}): Promise<TestApp> {\n    // Enable test mode so that attachAuthContext() accepts the X-Testing-User header.\n    if (typeof process !== 'undefined') {\n      process.env.GUREN_TESTING = '1'\n    }\n\n    let Application: ApplicationConstructor | undefined\n    // Claims this app as the ambient one (RFC 0023 §3). Without it, the second\n    // TestApp of a run reads as a rival live app and the next ambient helper in\n    // the suite under test warns about an ambiguous choice.\n    let claimAmbient: ((app: unknown) => void) | undefined\n\n    try {\n      const core = await import('@guren/core')\n      Application = core.Application as unknown as ApplicationConstructor\n      claimAmbient = core.useAsDefaultApplication as unknown as (app: unknown) => void\n    } catch {\n      try {\n        // @guren/core is not always installed (it aggregates @guren/server);\n        // fall back to the peer dependency, which exports the same Application.\n        const server = await import('@guren/server')\n        Application = server.Application as unknown as ApplicationConstructor\n        claimAmbient = server.useAsDefaultApplication as unknown as (app: unknown) => void\n      } catch {\n        // Fallback: use a plain Hono app when @guren/server is not available.\n        const { Hono } = await import('hono')\n        const hono = new Hono()\n        if (options.boot) {\n          await options.boot(hono)\n        }\n\n        const fetchFn = (request: Request) => Promise.resolve(hono.fetch(request))\n        return new TestApp(fetchFn)\n      }\n    }\n\n    const application = new Application({\n      boot: options.boot,\n      // `TestAppOptions` accepts the structural `ProviderConstructor` where\n      // `ApplicationOptions` demands a `ServiceProvider` subclass. Every real provider\n      // satisfies both, and the widening stays confined to this one property.\n      providers: options.providers as ServiceProviderConstructor[] | undefined,\n      routes: options.routes,\n      auth: options.auth,\n      i18n: options.i18n,\n      env: options.env,\n    })\n    if (options.envSource) {\n      application.container.instance('env.source', options.envSource)\n    }\n    claimAmbient?.(application)\n    await application.boot()\n\n    const fetchFn = (request: Request) => Promise.resolve(application.fetch(request))\n    const app = new TestApp(fetchFn)\n    // After boot(), because that is when the app mounts its routes.\n    app.routeDefinitions = application.router?.definitions()\n    await app.attachContainer(application.container)\n    return app\n  }\n\n  // oxlint-disable-next-line guren/comment-length -- public API whose @example is the documented entry point\n  /**\n   * Create a TestApp from an existing Application instance (typically `src/app.ts`'s\n   * default export), booting it if it has not yet. `fetch` is bound internally, so no\n   * `TestApp.fromFetch((request) => app.fetch(request))` wrapper is needed; `boot()` must\n   * be idempotent (@guren/server's Application reuses its first boot), so several test\n   * files may share one instance.\n   * @example\n   * import app from '../src/app'\n   * const http = await TestApp.fromApp(app)\n   * await http.get('/').assertOk()\n   */\n  static async fromApp(app: ApplicationLike, baseUrl = 'http://localhost'): Promise<TestApp> {\n    // Set before boot() so boot-time code sees test mode; fromFetch repeats it.\n    process.env.GUREN_TESTING = '1'\n    await app.boot()\n\n    const testApp = TestApp.fromFetch((request) => app.fetch(request), baseUrl)\n    // The one thing `fromFetch` cannot recover from a bare function: the route\n    // graph `agent()` derives tools from.\n    testApp.routeDefinitions = app.router?.definitions()\n    await testApp.attachContainer(app.container)\n    return testApp\n  }\n\n  /**\n   * Create a TestApp from an existing fetch function.\n   * Useful when you already have a Hono app or Application instance.\n   */\n  static fromFetch(\n    fetchFn: (request: Request) => Response | Promise<Response>,\n    baseUrl = 'http://localhost',\n  ): TestApp {\n    process.env.GUREN_TESTING = '1'\n    return new TestApp(\n      (req) => Promise.resolve(fetchFn(req)),\n      baseUrl,\n    )\n  }\n\n  /**\n   * Create a TestApp from a Cloudflare Workers-style fetch handler. One fake\n   * ExecutionContext is shared across every request; promises passed to\n   * `ctx.waitUntil()` are collected in `workers.waitUntilPromises` to await.\n   */\n  static fromWorkers(\n    handler: WorkersHandler,\n    options: WorkersTestAppOptions = {},\n  ): TestApp & { workers: WorkersTestContext } {\n    process.env.GUREN_TESTING = '1'\n\n    const waitUntilPromises: Promise<unknown>[] = []\n    const ctx: WorkersExecutionContext = {\n      waitUntil(promise) {\n        waitUntilPromises.push(promise)\n      },\n      passThroughOnException() {},\n    }\n\n    const app = new TestApp(\n      (req) => Promise.resolve(handler.fetch(req, options.env ?? {}, ctx)),\n      options.baseUrl,\n    )\n\n    app.workers = { waitUntilPromises }\n    // The assertion only narrows the optional `workers` field to required.\n    return app as TestApp & { workers: WorkersTestContext }\n  }\n\n  /**\n   * Return a new TestApp authenticated as this user, injected through a header the\n   * auth middleware recognizes in test mode.\n   */\n  actingAs(user: unknown): TestApp {\n    const copy = this.clone()\n    copy.authenticatedUser = user\n    return copy\n  }\n\n  /**\n   * A copy carrying everything this TestApp was configured with. One place, because\n   * every builder (`actingAs`, `withHeaders`, `withCsrf`) has to carry *all* of it —\n   * a field one copies and another does not vanishes silently on the next builder.\n   */\n  private clone(): TestApp {\n    const copy = new TestApp(this.fetchFn, this.baseUrl)\n    copy.defaultHeaders = { ...this.defaultHeaders }\n    copy.authenticatedUser = this.authenticatedUser\n    copy.routeDefinitions = this.routeDefinitions\n    copy.container = this.container\n    copy.workers = this.workers\n    return copy\n  }\n\n  /**\n   * The agent surface of this app (RFC 0016): the tools an MCP client would see, and a way\n   * to call them through the framework's own dispatch contract and this app's `fetch`.\n   * @example\n   * const result = await app.agent().call('posts.store', { title: 'x' }, { as: user })\n   */\n  agent(): TestAgent {\n    return new TestAgent(this.agentBridge())\n  }\n\n  // oxlint-disable-next-line guren/comment-length -- public API whose @example is the documented entry point\n  /**\n   * Replace the app's `ai` binding with a scripted fake (RFC 0029 §7). Models are scripted\n   * per agent with `respond()`; tools still run through `appTools()` and the pipeline.\n   * Disposing restores the binding and fails if any prompt found nothing scripted.\n   * @example\n   * using ai = app.fakeAi()\n   * ai.respond(SupportTriager, [{ output: { priority: 2 } }])\n   */\n  fakeAi(): FakeAi {\n    if (!this.container) {\n      throw new Error(\n        'This TestApp has no application container, so it has no `ai` binding to fake. '\n          + 'fakeAi() needs TestApp.fromApp(app); TestApp.fromFetch()/fromWorkers() '\n          + 'are handed a bare fetch function.',\n      )\n    }\n    return createFakeAi(this.container)\n  }\n\n  private async attachContainer(container: Container | undefined): Promise<void> {\n    this.container = container\n    // Only for an app that binds `ai`: the import is what keeps `fakeAi()` synchronous.\n    if (container?.has('ai')) await preloadFakeAiRuntime()\n  }\n\n  private agentBridge(): AgentTestBridge {\n    return {\n      baseUrl: this.baseUrl,\n      routeDefinitions: () => this.routeDefinitions,\n      headers: () => this.requestHeaders(),\n      // Through `fetchFn`, not an Application: `fromWorkers` closes over the env and\n      // ExecutionContext there, so a tool call inherits the bindings and `waitUntil`.\n      dispatch: (request) => this.fetchFn(request),\n      actingAs: (user) => this.actingAs(user).agentBridge(),\n    }\n  }\n\n  /**\n   * Prime the CSRF protection: GETs `path`, captures the session and XSRF-TOKEN\n   * cookies, and returns a TestApp that sends them (plus the `X-XSRF-TOKEN` header)\n   * on every later request, so mutating requests pass CSRF like a real browser.\n   */\n  async withCsrf(path = '/'): Promise<TestApp> {\n    const response = await this.request('GET', path)\n\n    const cookies = new Map<string, string>()\n    for (const setCookie of response.headers.getSetCookie()) {\n      const [pair] = setCookie.split(';')\n      const separator = pair.indexOf('=')\n      if (separator > 0) {\n        cookies.set(pair.slice(0, separator).trim(), pair.slice(separator + 1).trim())\n      }\n    }\n\n    const xsrfToken = cookies.get('XSRF-TOKEN')\n    if (!xsrfToken) {\n      throw new Error(\n        `withCsrf(): GET ${path} did not set an XSRF-TOKEN cookie. ` +\n          'Ensure session + CSRF middleware are enabled (auth option in createApp).',\n      )\n    }\n\n    const copy = this.clone()\n    copy.defaultHeaders = {\n      ...copy.defaultHeaders,\n      Cookie: [...cookies.entries()].map(([name, value]) => `${name}=${value}`).join('; '),\n      'X-XSRF-TOKEN': decodeURIComponent(xsrfToken),\n    }\n    return copy\n  }\n\n  /**\n   * Return a new TestApp that sends `Accept: application/json` on every request.\n   */\n  json(): TestApp {\n    return this.withHeaders({ Accept: 'application/json' })\n  }\n\n  /** Return a new TestApp that sends the given headers on every request. */\n  withHeaders(headers: Record<string, string>): TestApp {\n    const copy = this.clone()\n    copy.defaultHeaders = { ...copy.defaultHeaders, ...headers }\n    return copy\n  }\n\n  /**\n   * Return a new TestApp that sends the given header on every request.\n   */\n  withHeader(name: string, value: string): TestApp {\n    return this.withHeaders({ [name]: value })\n  }\n\n  /**\n   * Make a GET request.\n   */\n  get(path: string): PendingTestResponse {\n    return this.request('GET', path)\n  }\n\n  /**\n   * Make a HEAD request. The app answers it with the GET route's action and\n   * drops the body, so this shows what that action does for a monitor or a\n   * link checker.\n   */\n  head(path: string): PendingTestResponse {\n    return this.request('HEAD', path)\n  }\n\n  /**\n   * Make a POST request.\n   */\n  post(path: string, body?: unknown): PendingTestResponse {\n    return this.request('POST', path, body)\n  }\n\n  /**\n   * Make a PUT request.\n   */\n  put(path: string, body?: unknown): PendingTestResponse {\n    return this.request('PUT', path, body)\n  }\n\n  /**\n   * Make a PATCH request.\n   */\n  patch(path: string, body?: unknown): PendingTestResponse {\n    return this.request('PATCH', path, body)\n  }\n\n  /**\n   * Make a DELETE request.\n   */\n  delete(path: string, body?: unknown): PendingTestResponse {\n    return this.request('DELETE', path, body)\n  }\n\n  /**\n   * Make a QUERY request (RFC 10008): safe and idempotent like GET, but\n   * carries a request body like POST.\n   */\n  query(path: string, body?: unknown): PendingTestResponse {\n    return this.request('QUERY', path, body)\n  }\n\n  /**\n   * The headers every request carries: whatever `withHeaders`/`withCsrf` parked, plus\n   * the authenticated-user envelope. One spelling, shared with the agent dispatch.\n   */\n  private requestHeaders(): Record<string, string> {\n    const headers: Record<string, string> = { ...this.defaultHeaders }\n\n    if (this.authenticatedUser) {\n      // JSON-encoded header the test-aware auth middleware reads. The auth identifier\n      // is preserved so the deserialized object can reconstruct getAuthIdentifier().\n      const user = this.authenticatedUser as Record<string, unknown>\n      const authId =\n        typeof (user as { getAuthIdentifier?: unknown }).getAuthIdentifier === 'function'\n          ? (user as { getAuthIdentifier(): unknown }).getAuthIdentifier()\n          : user.id ?? null\n      headers['X-Testing-User'] = testingHeaderValue({ ...user, __authId: authId })\n    }\n\n    return headers\n  }\n\n  private request(method: string, path: string, body?: unknown): PendingTestResponse {\n    const url = path.startsWith('http') ? path : `${this.baseUrl}${path}`\n\n    const headers = this.requestHeaders()\n\n    // FormData bodies get their multipart boundary from fetch itself.\n    if (body !== undefined && body !== null && !(body instanceof FormData)) {\n      headers['Content-Type'] = 'application/json'\n    }\n\n    const init: RequestInit = {\n      method,\n      headers,\n    }\n\n    if (body !== undefined && body !== null) {\n      init.body = body instanceof FormData ? body : JSON.stringify(body)\n    }\n\n    const promise = (async () => {\n      const request = new Request(url, init)\n      const response = await this.fetchFn(request)\n      return new TestResponse(response)\n    })()\n\n    return new PendingTestResponse(promise)\n  }\n}\n\n/** Factory helper for creating test model instances. */\nexport async function factory<T>(\n  factoryClass: new () => { create(overrides?: Partial<T>): Promise<T> },\n  count?: number,\n): Promise<T | T[]> {\n  const instance = new factoryClass()\n  if (count !== undefined && count > 0) {\n    const results: T[] = []\n    for (let i = 0; i < count; i++) {\n      results.push(await instance.create())\n    }\n    return results\n  }\n\n  return instance.create()\n}\n\nfunction getNestedValue(obj: unknown, path: string): unknown {\n  const parts = path.split('.')\n  let current = obj\n\n  for (const part of parts) {\n    if (current === null || current === undefined) {\n      return undefined\n    }\n    if (typeof current !== 'object') {\n      return undefined\n    }\n    current = (current as Record<string, unknown>)[part]\n  }\n\n  return current\n}\n","import type { Application, ServiceProviderConstructor } from '@guren/server'\n\n/** Boot a minimal test application with the given providers. */\nexport async function createPluginTestApp(\n  providers: unknown[]\n): Promise<Application> {\n  const { createApp } = await import('@guren/core')\n  // Callers pass provider classes without having to name the framework type,\n  // which `createApp` does demand; a real provider satisfies both.\n  const app = createApp({ providers: providers as ServiceProviderConstructor[] })\n  await app.boot()\n  return app\n}\n\n/** Assert a plugin bound the expected services in the container. */\nexport function assertPluginRegisters(\n  app: Application,\n  services: string[]\n): void {\n  for (const service of services) {\n    const bound = app.container?.has(service) ?? false\n    if (!bound) {\n      throw new Error(\n        `Plugin did not register expected service: \"${service}\". ` +\n          `Verify that the provider calls this.container.singleton(\"${service}\", ...) ` +\n          `or this.container.bind(\"${service}\", ...) in its register() method.`\n      )\n    }\n  }\n}\n\n/** Assert a plugin bound none of these services — e.g. a deferred provider. */\nexport function assertPluginDoesNotRegister(\n  app: Application,\n  services: string[]\n): void {\n  for (const service of services) {\n    const bound = app.container?.has(service) ?? false\n    if (bound) {\n      throw new Error(\n        `Plugin unexpectedly registered service: \"${service}\". ` +\n          `If this is a deferred provider, the service should not be bound until first resolution.`\n      )\n    }\n  }\n}\n"],"mappings":";;;;;;;;AA8BA,SAAgB,eAAe,MAKlB;CACX,OAAO;EACL,GAAG;EACH,oBAAoB;GAClB,OAAO,KAAK;EACd;EACA,kBAAkB;GAChB,OAAO,KAAK;EACd;CACF;AACF;AAEA,SAAgB,mBAAuC,OAAiC;CACtF,OAAO;EACL,cAAc,OAAO,OAAO,MAAM,MAAM,MAAM,EAAE,OAAO,EAAE,KAAK;EAC9D,uBAAuB,OAAO,gBAAgB;GAC5C,OAAO,MAAM,MAAM,MAAM,EAAE,UAAU,YAAY,KAAK,KAAK;EAC7D;EACA,qBAAqB,OAAO,MAAM,gBAAgB;GAChD,OAAO,KAAK,aAAa,Y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