Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

69.9 KB
Raw Blame
/*
 * Copyright 2025 Daytona Platforms Inc.
 * Modified by BoxLite AI, 2025-2026
 * SPDX-License-Identifier: AGPL-3.0
 */

import { assertCpuAllocation } from '../utils/cpu-allocation'
import { requestedMemoryMib } from '../utils/memory-allocation'
import { ForbiddenException, Injectable, Logger, NotFoundException, ConflictException } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import {
  Not,
  Repository,
  LessThan,
  MoreThan,
  In,
  JsonContains,
  FindOptionsWhere,
  ILike,
  EntityManager,
  Raw,
} from 'typeorm'
import { BoxPublicStatus, publicBoxStatus } from '../utils/box-public-status'
import { reportedBoxState } from '../utils/box-state.util'
import { Box } from '../entities/box.entity'
import { persistWithGeneratedBoxName } from '../utils/box-name-generator'
import { boxImageIsOrgOwned } from '../utils/image-ownership.util'
import { boxVolumeForDispatch } from '../utils/box-volume.util'
import { isFilestoreVolume } from '../entities/volume.entity'
import { CreateBoxDto } from '../dto/create-box.dto'
import { appForEnvironment } from './app-environment'
import { BoxState } from '../enums/box-state.enum'
import { BoxClass } from '../enums/box-class.enum'
import { BoxDesiredState } from '../enums/box-desired-state.enum'
import { chargedNativeTombstone, pendingDeletionTarget } from '../constants/checkpoint-deletion'
import { GetRunnerParams, RunnerService } from './runner.service'
import { BoxExitCodeService } from './box-exit-code.service'
import { BoxError } from '../../exceptions/box-error.exception'
import { BadRequestError } from '../../exceptions/bad-request.exception'
import { BoxCreationLimitExceededError } from '../errors/box-creation-limit.error'
import { Cron, CronExpression } from '@nestjs/schedule'
import { BOX_WARM_POOL_UNASSIGNED_ORGANIZATION } from '../constants/box.constants'
import { ImageAdmissionService, type ColdPullTicket } from '../../image/services/image-admission.service'
import { ImagePreparationService } from '../../image/services/image-preparation.service'
import { ImagePullFailureService } from '../../image/services/image-pull-failure.service'
import { ImageResolverService } from '../../image/services/image-resolver.service'
import { ImageRegistrarService, ReportedImage } from '../../image/services/image-registrar.service'
import { BoxWarmPoolService } from './box-warm-pool.service'
import { EventEmitter2, OnEvent } from '@nestjs/event-emitter'
import { WarmPoolEvents } from '../constants/warmpool-events.constants'
import { WarmPoolTopUpRequested } from '../events/warmpool-topup-requested.event'
import { Runner } from '../entities/runner.entity'
import { Organization } from '../../organization/entities/organization.entity'
import { BoxEvents } from '../constants/box-events.constants'
import { BoxStateUpdatedEvent } from '../events/box-state-updated.event'
import { BoxDestroyedEvent } from '../events/box-destroyed.event'
import { BoxStartedEvent } from '../events/box-started.event'
import { BoxDesiredStateUpdatedEvent } from '../events/box-desired-state-updated.event'
import { BoxStoppedEvent } from '../events/box-stopped.event'
import { OrganizationService } from '../../organization/services/organization.service'
import { OrganizationEvents } from '../../organization/constants/organization-events.constant'
import { OrganizationSuspendedBoxStoppedEvent } from '../../organization/events/organization-suspended-box-stopped.event'
import { TypedConfigService } from '../../config/typed-config.service'
import { WarmPool } from '../entities/warm-pool.entity'
import { BoxDto, BoxDtoReads, BoxSecret, BoxVolume } from '../dto/box.dto'
import { RunnerAdapterFactory } from '../runner-adapter/runnerAdapter'
import {
  DISABLED_OUTBOUND_RULES_ERROR,
  hasDisabledOutboundRules,
  validateNetworkAllowList,
} from '../utils/network-validation.util'
import { NetworkMode } from '../enums/network-mode.enum'
import { networkMode } from '../utils/network-policy.util'
import { VolumeService } from './volume.service'
import { FilestoreInstanceResolver } from './filestore-instance.resolver'
import { PaginatedList } from '../../common/interfaces/paginated-list.interface'
import {
  BoxSortField,
  BoxSortDirection,
  DEFAULT_BOX_SORT_FIELD,
  DEFAULT_BOX_SORT_DIRECTION,
} from '../dto/list-boxes-query.dto'
import { createRangeFilter } from '../../common/utils/range-filter'
import { recordBoxRequested, recordWarmPoolClaim } from '../utils/box-business-event.util'
import { mutationFailureType, recordBusinessEvent } from '../../common/utils/business-event.util'
import { Context } from '../../common/context/context'
import { PlatformReason } from '../../common/context/platform-reason.enum'
import { LogExecution } from '../../common/decorators/log-execution.decorator'
import { nanoid } from 'nanoid'
import { WithInstrumentation } from '../../common/decorators/otel.decorator'
import { validateMountPaths, validateSubpaths } from '../utils/volume-mount-path-validation.util'
import { BoxRepository } from '../repositories/box.repository'
import { Job } from '../entities/job.entity'
import { JobService } from './job.service'
import { JobStatus, JobType, ResourceType } from '../dto/job.dto'
import { RegionService } from '../../region/services/region.service'
import { BoxCreatedEvent } from '../events/box-create.event'
import { InjectRedis } from '@nestjs-modules/ioredis'
import { Redis } from 'ioredis'
import {
  BOX_LOOKUP_CACHE_TTL_MS,
  BOX_ORG_ID_CACHE_TTL_MS,
  boxLookupCacheKeyById,
  boxLookupCacheKeyByName,
  boxOrgIdCacheKeyById,
  boxOrgIdCacheKeyByName,
} from '../utils/box-lookup-cache.util'
import { BoxLookupCacheInvalidationService } from './box-lookup-cache-invalidation.service'
import { Region } from '../../region/entities/region.entity'
import { BoxActivityService } from './box-activity.service'
import { assertWithinPerBoxLimits } from './per-box-limits'
import { OrganizationBoxLimitsService } from '../../organization/services/organization-box-limits.service'
import { requiresFreshBox } from '../utils/warm-pool-eligibility.util'
import { reserveBoxSecretTransfer } from './box-secret-cleanup.service'
import { SecretServerClient } from './secret-server-client'
import { OutboundPolicy, setRunnerOutbound } from '../runner-adapter/network-policy'
import { isCuratedSelector, withoutRegistryProxy } from '../../image/utils/image-ref.util'
import {
  AUTO_DELETE_DISABLED,
  AUTO_STOP_DISABLED,
  DEFAULT_AUTO_STOP_SECONDS,
  DEFAULT_AUTO_RESUME,
  MIN_AUTO_STOP_SECONDS,
} from '../constants/box-lifecycle.constants'

// An image does not decide how large a box is. These once stood in for values
// the removed image subsystem supplied, and resolution is back now without
// them changing hands — deliberately, because the alternative is that rotating
// an image silently resizes every box booted from it. They are the contract,
// not a stopgap.
const DEFAULT_BOX_CPU = 1
const DEFAULT_BOX_MEM = 1
const DEFAULT_BOX_DISK = 10
const DEFAULT_BOX_GPU = 0

// Leave room inside the proxy's two-second delivery timeout.
const PREVIEW_ACTIVITY_TIMEOUT_MS = 1500

export type BoxCreationOptions = {
  onStarted?: () => void
  maxCreatedBoxes?: number
  /** Authenticated creator, supplied by the caller rather than the request DTO. */
  createdBy?: string
  /** Internal transactional admission/ownership; never accepted from a public DTO. */
  onPersist?: (manager: EntityManager, box: Box) => Promise<void>
  /** Trusted Cloud App provisioning context, supplied independently of the public DTO. */
  appEnvironmentId?: string
}

export type ProxyAdmission = (box: Box, boxId: string) => void

export function validateSecrets(secrets: BoxSecret[] | undefined): void {
  const forbidden = new Set([
    'host',
    'connection',
    'proxy-connection',
    'proxy-authenticate',
    'proxy-authorization',
    'keep-alive',
    'te',
    'trailer',
    'upgrade',
    'content-length',
    'transfer-encoding',
  ])
  // RFC 9110 token syntax; the denied names are Go httputil hopHeaders
  // plus Host and Content-Length, matching the Rust create check.
  const token = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/
  // HTTP field values deliberately reject these control bytes, except HTAB.
  // eslint-disable-next-line no-control-regex
  const controls = /[\x00-\x08\x0a-\x1f\x7f]/
  const seen = new Set<string>()

  for (const secret of secrets ?? []) {
    if (!secret.hosts?.length || secret.hosts.some((host) => !host)) {
      throw new BadRequestError(`Secret ${secret.name} must list non-empty hosts`)
    }
    const headers = secret.headers
    if (!headers || typeof headers !== 'object' || Array.isArray(headers) || Object.keys(headers).length === 0) {
      throw new BadRequestError(`secret ${JSON.stringify(secret.name)} has no headers; recreate the box with headers`)
    }
    if (!secret.secretId && (typeof secret.value !== 'string' || controls.test(secret.value))) {
      throw new BadRequestError(`Secret ${secret.name} has an invalid header value`)
    }
    const ownHeaders = new Set<string>()
    const hosts = new Set(secret.hosts.map((value) => value.toLowerCase()))
    for (const [header, template] of Object.entries(headers)) {
      const normalizedHeader = header.toLowerCase()
      if (!token.test(header) || forbidden.has(normalizedHeader) || ownHeaders.has(normalizedHeader)) {
        throw new BadRequestError(`Secret ${secret.name} has an invalid or duplicate header name`)
      }
      ownHeaders.add(normalizedHeader)
      // Check template and value separately: braces in the value are literal,
      // and rendering cannot introduce a control byte absent from both inputs.
      if (typeof template !== 'string' || !/^[^{}]*\{value\}[^{}]*$/.test(template) || controls.test(template)) {
        throw new BadRequestError(`Secret ${secret.name} has an invalid header template`)
      }
      for (const host of hosts) {
        const key = `${host}\0${normalizedHeader}`
        if (seen.has(key)) {
          throw new BadRequestError(`Conflicting secrets on host ${host} for header ${header}`)
        }
        seen.add(key)
      }
    }
  }
}

@Injectable()
export class BoxService {
  private readonly logger = new Logger(BoxService.name)

  constructor(
    private readonly boxRepository: BoxRepository,
    @InjectRepository(Runner)
    private readonly runnerRepository: Repository<Runner>,
    private readonly runnerService: RunnerService,
    private readonly boxExitCodeService: BoxExitCodeService,
    private readonly volumeService: VolumeService,
    private readonly configService: TypedConfigService,
    private readonly warmPoolService: BoxWarmPoolService,
    private readonly eventEmitter: EventEmitter2,
    private readonly organizationService: OrganizationService,
    private readonly runnerAdapterFactory: RunnerAdapterFactory,
    @InjectRedis() private readonly redis: Redis,
    private readonly regionService: RegionService,
    private readonly boxLookupCacheInvalidationService: BoxLookupCacheInvalidationService,
    private readonly boxActivityService: BoxActivityService,
    @InjectRepository(Job)
    private readonly jobRepository: Repository<Job>,
    private readonly jobService: JobService,
    private readonly imageAdmissionService: ImageAdmissionService,
    private readonly imageResolverService: ImageResolverService,
    private readonly imageRegistrarService: ImageRegistrarService,
    private readonly imagePreparationService: ImagePreparationService,
    private readonly imagePullFailureService: ImagePullFailureService,
    private readonly organizationBoxLimits: OrganizationBoxLimitsService,
    private readonly secretServerClient: SecretServerClient,
    private readonly filestoreInstanceResolver: FilestoreInstanceResolver,
  ) {}

  protected getLockKey(id: string): string {
    return `box:${id}:state-change`
  }

  /**
   * Assigns `box` to a schedulable runner, then persists it.
   *
   * Nothing locks the runner row across the gap between the candidate query —
   * which already filters out draining, unschedulable and non-READY runners —
   * and the insert. A drain landing inside that gap therefore wins the row but
   * not the box: the runner ends up marked draining with this box assigned to
   * it. That is the deliberate trade, and it is how schedulers usually settle
   * it: Nomad re-checks node eligibility only when the plan is applied
   * (`evaluateNodePlan`, nomad/plan_apply.go:837-861, over a read-only memdb
   * snapshot), and Kubernetes lets the kubelet reject a pod the scheduler
   * already bound (`predicateAdmitHandler.Admit`,
   * pkg/kubelet/lifecycle/predicate.go:118-207). A lock here buys a fence over
   * milliseconds and charges every create for it — waiting behind runner
   * lifecycle writers, and unable to tell "busy" from "unusable" when it loses.
   *
   * Draining is not a hard exclusion, it is "no new work, wait out the boxes
   * already here". A box that slips in is one more box to wait out:
   * `handleCheckDecommissionRunners` counts assignments before each transition
   * and resets its counter while any remain, so the runner keeps draining and
   * the box keeps running.
   */
  private async persistOnAvailableRunner(
    box: Box,
    runnerParams: GetRunnerParams,
    persist: (runner: Runner) => Promise<Box>,
  ): Promise<Box> {
    const runner = await this.runnerService.getRandomAvailableRunner(
      box.privileged ? { ...runnerParams, requiresPrivileged: true } : runnerParams,
    )
    box.runnerId = runner.id
    return persist(runner)
  }

  private assertBoxNotErrored(box: Box): void {
    if (box.state === BoxState.ERROR) {
      throw new BoxError('Box is in an errored state')
    }
  }

  async createForWarmPool(warmPoolItem: WarmPool): Promise<Box> {
    assertCpuAllocation(warmPoolItem.cpu)
    // The far side of `requiresFreshBox`'s image rule. A warm box is created
    // with no organization and handed to whichever one claims it, so a pool row
    // naming a tenant's image would put that image's contents in front of
    // another tenant. Logged as well as thrown: a top-up arrives as an event, and
    // the loop that fires it collects rejections with `allSettled`, so a throw
    // alone would leave an operator with a pool that silently never fills.
    if (!isCuratedSelector(warmPoolItem.image)) {
      const message = `Warm pool ${warmPoolItem.id} names '${warmPoolItem.image}', which is not a curated image`
      this.logger.error(message)
      throw new BoxError(message)
    }

    const box = new Box(warmPoolItem.target)

    box.organizationId = BOX_WARM_POOL_UNASSIGNED_ORGANIZATION

    box.class = warmPoolItem.class
    box.image = warmPoolItem.image
    // Asserted curated a few lines up, so this is not a second opinion — it is
    // the same one, written down before the curated set can move under it.
    box.imageIsOrgOwned = false
    //  TODO: default user should be configurable
    box.osUser = 'boxlite'
    box.env = warmPoolItem.env || {}

    box.cpu = warmPoolItem.cpu
    box.gpu = warmPoolItem.gpu
    box.mem = warmPoolItem.mem
    box.memoryMib = warmPoolItem.mem * 1024
    box.disk = warmPoolItem.disk

    box.pending = true

    return this.persistOnAvailableRunner(box, { regions: [box.region], boxClass: box.class }, () =>
      this.boxRepository.insert(box),
    )
  }

  async create(
    createBoxDto: CreateBoxDto,
    organization: Organization,
    ctx: Context,
    options: BoxCreationOptions = {},
  ): Promise<BoxDto> {
    // Authentication caches organizations; admission must use the current policy.
    const nestedVirtualizationEnabled = await this.organizationService.isNestedVirtualizationEnabled(organization.id)
    organization = Object.assign(Object.create(Object.getPrototypeOf(organization)) as Organization, organization, {
      nestedVirtualizationEnabled,
    })
    const outboundEnabled = createBoxDto.outboundEnabled ?? !organization.boxLimitedNetworkEgress
    if (hasDisabledOutboundRules(outboundEnabled ? 'enabled' : 'disabled', createBoxDto.outboundAllowNet)) {
      throw new BadRequestError(DISABLED_OUTBOUND_RULES_ERROR)
    }
    const region = await this.getValidatedOrDefaultRegion(organization, createBoxDto.target)

    try {
      const boxClass = this.getValidatedOrDefaultClass(createBoxDto.class)

      const cpu = createBoxDto.cpu ?? DEFAULT_BOX_CPU
      const mem = createBoxDto.memory ?? DEFAULT_BOX_MEM
      const memoryMib = requestedMemoryMib(mem)
      const disk = createBoxDto.disk ?? DEFAULT_BOX_DISK
      const gpu = createBoxDto.gpu ?? DEFAULT_BOX_GPU
      // Reject over-limit requests at the boundary (the "security option"
      // per-box ceilings) rather than persisting out-of-range values.
      const limits = await this.organizationBoxLimits.resolve(organization)
      assertWithinPerBoxLimits(cpu, mem, disk, limits)
      this.organizationService.assertOrganizationIsNotSuspended(organization)

      const entries = createBoxDto.secrets ?? []
      const secrets = entries.length ? await this.secretServerClient.resolveForBox(organization.id, entries) : []
      validateSecrets(secrets)

      // Admission decides whether this organization may boot from this image at
      // all; it is the gate that replaced "curated images only". It runs after
      // the suspension check, and before the resolver, so a refused image never
      // reaches the catalog query.
      await this.imageAdmissionService.assert(organization, createBoxDto.image)
      // Resolution turns what the caller asked for into the ref a runner is
      // given: the curated set answers its own selectors without a query, and
      // anything else is looked up in this organization's catalog — pinned to
      // the digest its catalog tag points at if the catalog knows it, passed
      // through as typed if it does not, which is how an image gets pulled the
      // first time. A repository the organization registered a login for is
      // handed over either way as a registry proxy ref, so that is what
      // `box.image` records for a private image.
      const resolvedImage = await this.imageResolverService.resolve(organization, createBoxDto.image)
      const image = resolvedImage.ref
      const appId =
        options.appEnvironmentId === undefined
          ? null
          : await appForEnvironment(this.boxRepository.manager, organization.id, options.appEnvironmentId)
      const needsFreshBox =
        appId !== null || !!options.onPersist || requiresFreshBox(createBoxDto, organization, resolvedImage)

      if (createBoxDto.volumes && createBoxDto.volumes.length > 0) {
        const volumes = await this.volumeService.validateVolumes(
          organization.id,
          createBoxDto.volumes.map((v) => v.volumeId),
          options.appEnvironmentId,
        )
        // Replace the caller's selector with the volume it resolved to inside
        // this organization. A name is only unique per organization, but
        // everything downstream (the runner, the `boxlite-volume-<id>` bucket,
        // a filestore data directory `boxlite-filestore-<instance>/<id>`) reads
        // the stored value as a globally canonical id - see
        // VolumeService.validateVolumes. The filestore reference rides along
        // for the runner's mount dispatch with the address the API resolves
        // from its FILESTORE_INSTANCES configuration; the runner configures
        // no instances of its own. A name that left the configuration between
        // the volume's create and this dispatch fails loudly here.
        const resolvedVolumes = []
        for (const volume of createBoxDto.volumes) {
          const resolved = volumes.get(volume.volumeId)
          if (!resolved) {
            // validateVolumes keys every selector or throws, so this is
            // unreachable today. Fail closed anyway: the alternative fallback
            // is silently persisting the caller's own string, which is exactly
            // the tenant-controlled passthrough the resolution exists to stop.
            throw new BadRequestError(`Volume '${volume.volumeId}' could not be resolved`)
          }
          const instance = isFilestoreVolume(resolved)
            ? await this.filestoreInstanceResolver.resolve(resolved.instance, 'configured')
            : undefined
          resolvedVolumes.push(
            boxVolumeForDispatch({
              ...volume,
              volumeId: resolved.id,
              ...(instance
                ? { filestore: { instance: resolved.instance, server: instance.server, export: instance.export } }
                : {}),
            }),
          )
        }
        createBoxDto.volumes = resolvedVolumes
      } else if (image && !needsFreshBox) {
        //  No volumes requested — try to claim a pre-warmed box matching this image/spec
        //  before creating a fresh one.
        const skipWarmPool = (await this.redis.exists(`warm-pool:skip:${image}`)) === 1
        if (!skipWarmPool) {
          const warmPoolBox = await this.warmPoolService.fetchWarmPoolBox({
            organizationId: organization.id,
            image,
            target: region.id,
            class: boxClass,
            cpu,
            mem,
            disk,
            gpu,
            osUser: createBoxDto.user || 'boxlite',
            env: createBoxDto.env || {},
            state: BoxState.STARTED,
          })

          if (warmPoolBox) {
            return await this.assignWarmPoolBox(warmPoolBox, createBoxDto, organization, ctx, options)
          }
        }
      }

      const box = new Box(region.id, createBoxDto.name)

      box.organizationId = organization.id
      box.appId = appId
      box.environmentId = options.appEnvironmentId ?? null

      //  TODO: make configurable
      box.class = boxClass
      //  TODO: default user should be configurable
      box.osUser = createBoxDto.user || 'boxlite'
      // Only set when the caller actually asked. Collapsing "not supplied" into
      // a default here would hand every box a USER override its image may not
      // define — which is exactly what 16d9248bb removed.
      box.runAsUser = createBoxDto.runAsUser
      box.privileged = createBoxDto.privileged ?? false
      box.workingDir = createBoxDto.workingDir
      box.entrypoint = createBoxDto.entrypoint
      box.cmd = createBoxDto.cmd
      box.env = createBoxDto.env || {}
      box.labels = createBoxDto.labels || {}

      box.image = image
      // The resolver decided this, against the curated set as it stood when the
      // caller asked. Recomputing it later answers a different question.
      box.imageIsOrgOwned = resolvedImage.isOrgOwned
      box.cpu = cpu
      box.gpu = gpu
      box.mem = Math.ceil(mem)
      box.memoryMib = memoryMib
      box.disk = disk

      // POL-205: unset inbound access on the internal create DTO defaults disabled.
      box.inboundEnabled = createBoxDto.inboundEnabled ?? false

      // An explicit request wins; otherwise the organization's limited-egress
      // default decides.
      box.outboundEnabled = outboundEnabled

      if (createBoxDto.outboundAllowNet !== undefined) {
        box.outboundAllowNet = this.resolveOutboundAllowNet(createBoxDto.outboundAllowNet)
      }

      const lifecyclePolicy = this.resolveLifecyclePolicy({
        autoStop: createBoxDto.autoStop,
        autoDelete: createBoxDto.autoDelete,
        autoResume: createBoxDto.autoResume,
      })
      box.autoStop = lifecyclePolicy.autoStop
      box.autoDelete = lifecyclePolicy.autoDelete
      box.autoResume = lifecyclePolicy.autoResume

      if (createBoxDto.volumes !== undefined) {
        box.volumes = this.resolveVolumes(createBoxDto.volumes)
      }

      box.pending = true

      // Complete local validation before transferring values. Only references
      // may reach insertion, transactional callbacks, or creation events.
      const inline = secrets.filter((secret) => !secret.secretId)
      if (this.secretServerClient.enabled) this.secretServerClient.validateInline(inline)
      const claim =
        inline.length && this.secretServerClient.enabled
          ? await reserveBoxSecretTransfer(this.boxRepository.manager, organization.id, box.id)
          : undefined
      const initialize = claim
        ? async (manager: EntityManager) => {
            await claim(manager)
            const stored = await this.secretServerClient.storeBoxSecrets(
              box.id,
              organization.id,
              options.createdBy,
              inline,
            )
            let inlineIndex = 0
            box.secrets = secrets.map((secret) => (secret.secretId ? secret : stored[inlineIndex++]))
          }
        : undefined
      box.secrets = claim ? [] : secrets

      // No caller-provided name -> assign a fun default (e.g. "cozy-otter"),
      // falling back to "cozy-otter-{boxId}" if it collides with the per-org
      // @Unique(['organizationId', 'name']) constraint. Only the insert retries:
      // the chosen runner is still fine, it was the name that collided.
      //
      // The cold-pull budget is spent in here, once a runner is chosen and just
      // before the insert: it has no way to give a slot back, so a create its
      // own input or placement refuses must not spend one. Only the box limit
      // and a name collision, which the insert itself settles, come after it.
      // The limit is one of those, so a create it refuses hands its unit back
      // — with the ticket the spend returned, so the refund can only touch
      // the window that was actually charged. The replay layer marks the
      // rejection retryable, and retries must not drain the organization's
      // cold-pull window without a box to show for it.
      let coldPullTicket: ColdPullTicket | undefined
      const insertedBox = await this.persistOnAvailableRunner(box, { regions: [region.id], boxClass }, async () => {
        coldPullTicket = await this.imageAdmissionService.spendColdPullBudget(organization, resolvedImage)
        const insert = () =>
          initialize
            ? this.boxRepository.insert(box, options.maxCreatedBoxes, options.onPersist, initialize)
            : options.onPersist
              ? this.boxRepository.insert(box, options.maxCreatedBoxes, options.onPersist)
              : this.boxRepository.insert(box, options.maxCreatedBoxes)
        return createBoxDto.name
          ? insert()
          : persistWithGeneratedBoxName(box.id, (name) => {
              box.name = name
              return insert()
            })
      }).catch(async (error: unknown) => {
        if (error instanceof BoxCreationLimitExceededError && coldPullTicket) {
          await this.imageAdmissionService.refundColdPullBudget(organization, resolvedImage, coldPullTicket)
        }
        throw error
      })

      recordBoxRequested('box.create', insertedBox, ctx)

      this.eventEmitter
        .emitAsync(BoxEvents.CREATED, new BoxCreatedEvent(insertedBox))
        .catch((err) => this.logger.error('Failed to emit BoxCreatedEvent', err))

      if (insertedBox.state === BoxState.STARTED) options.onStarted?.()
      return this.toBoxDto(insertedBox)
    } catch (error) {
      if (error.code === 'BS001') throw new ConflictException('Referenced secret is being deleted or has been deleted')
      if (error.code === '23505') {
        throw new ConflictException(
          createBoxDto.name
            ? `Box with name ${createBoxDto.name} already exists`
            : 'Could not allocate a unique box name, please retry',
        )
      }

      throw error
    }
  }

  private async assignWarmPoolBox(
    warmPoolBox: Box,
    createBoxDto: CreateBoxDto,
    organization: Organization,
    ctx: Context,
    { maxCreatedBoxes, onStarted }: BoxCreationOptions,
  ): Promise<BoxDto> {
    const now = new Date()
    const updateData: Partial<Box> = {
      // POL-205: same default as the fresh-box path — see the comment there.
      inboundEnabled: createBoxDto.inboundEnabled ?? false,
      labels: createBoxDto.labels || {},
      organizationId: organization.id,
      createdAt: now,
    }

    const lifecyclePolicy = this.resolveLifecyclePolicy({
      autoStop: createBoxDto.autoStop,
      autoDelete: createBoxDto.autoDelete,
      autoResume: createBoxDto.autoResume,
    })
    updateData.autoStop = lifecyclePolicy.autoStop
    updateData.autoDelete = lifecyclePolicy.autoDelete
    updateData.autoResume = lifecyclePolicy.autoResume

    if (createBoxDto.outboundEnabled !== undefined) {
      updateData.outboundEnabled = createBoxDto.outboundEnabled
    }

    if (createBoxDto.outboundAllowNet !== undefined) {
      updateData.outboundAllowNet = this.resolveOutboundAllowNet(createBoxDto.outboundAllowNet)
    }

    if (!warmPoolBox.runnerId) {
      throw new BoxError('Runner not found for warm pool box')
    }

    // Resolve the name at persist time. A caller-provided name updates in one
    // shot (reusing the pre-fetched entity). A generated default falls back to
    // "{name}-{boxId}" on collision and omits `entity` so each attempt re-reads
    // the row — reusing the mutated entity would corrupt the optimistic-update
    // guard.
    const updatedBox = createBoxDto.name
      ? await this.boxRepository.update(warmPoolBox.id, {
          updateData: { ...updateData, name: createBoxDto.name },
          entity: warmPoolBox,
          maxCreatedBoxes,
        })
      : await persistWithGeneratedBoxName(warmPoolBox.id, (name) =>
          this.boxRepository.update(warmPoolBox.id, {
            updateData: { ...updateData, name },
            maxCreatedBoxes,
          }),
        )

    // Defensive invalidation of orgId cache since the box moved from unassigned to a real organization
    this.boxLookupCacheInvalidationService.invalidateOrgId({
      id: warmPoolBox.id,
      organizationId: organization.id,
      name: warmPoolBox.name,
      previousOrganizationId: BOX_WARM_POOL_UNASSIGNED_ORGANIZATION,
    })

    recordWarmPoolClaim(updatedBox, ctx)

    // Treat this as a newly started box
    this.eventEmitter.emit(
      BoxEvents.STATE_UPDATED,
      new BoxStateUpdatedEvent(updatedBox, BoxState.STARTED, BoxState.STARTED),
    )
    if (updatedBox.state === BoxState.STARTED) onStarted?.()
    return this.toBoxDto(updatedBox)
  }

  /** Return at most pageSize + 1 visible matches after an immutable ID, before enrichment. */
  async findInventory(
    organizationId: string,
    query: { pageSize: number; status?: BoxPublicStatus; after?: string },
  ): Promise<Box[]> {
    // Enumerate the persisted enum domains through the same projection the response uses.
    // An empty match (paused/failed today) must never become TypeORM's unfiltered where: [].
    const where: FindOptionsWhere<Box>[] = []
    for (const state of Object.values(BoxState)) {
      for (const desiredState of Object.values(BoxDesiredState)) {
        if (state === BoxState.DESTROYED || (state === BoxState.ERROR && desiredState === BoxDesiredState.DESTROYED))
          continue
        if (query.status && publicBoxStatus(reportedBoxState({ state, desiredState })) !== query.status) continue
        where.push({ organizationId, state, desiredState, ...(query.after ? { id: MoreThan(query.after) } : {}) })
      }
    }
    if (!where.length) return []
    return this.boxRepository.find({ where, order: { id: 'ASC' }, take: query.pageSize + 1 })
  }

  async findAllDeprecated(
    organizationId: string,
    labels?: { [key: string]: string },
    includeErroredDestroyed?: boolean,
  ): Promise<Box[]> {
    const baseFindOptions: FindOptionsWhere<Box> = {
      organizationId,
      ...(labels ? { labels: JsonContains(labels) } : {}),
    }

    const where: FindOptionsWhere<Box>[] = [
      {
        ...baseFindOptions,
        state: Not(In([BoxState.DESTROYED, BoxState.ERROR])),
      },
      {
        ...baseFindOptions,
        state: BoxState.ERROR,
        ...(includeErroredDestroyed ? {} : { desiredState: Not(BoxDesiredState.DESTROYED) }),
      },
    ]

    return this.boxRepository.find({ where })
  }

  async findAll(
    organizationId: string,
    page = 1,
    limit = 10,
    filters?: {
      id?: string
      name?: string
      labels?: { [key: string]: string }
      includeErroredDestroyed?: boolean
      states?: BoxState[]
      regionIds?: string[]
      minCpu?: number
      maxCpu?: number
      minMemoryGiB?: number
      maxMemoryGiB?: number
      minDiskGiB?: number
      maxDiskGiB?: number
      lastEventAfter?: Date
      lastEventBefore?: Date
    },
    sort?: {
      field?: BoxSortField
      direction?: BoxSortDirection
    },
  ): Promise<PaginatedList<Box>> {
    const pageNum = Number(page)
    const limitNum = Number(limit)

    const {
      id,
      name,
      labels,
      includeErroredDestroyed,
      states,
      regionIds,
      minCpu,
      maxCpu,
      minMemoryGiB,
      maxMemoryGiB,
      minDiskGiB,
      maxDiskGiB,
      lastEventAfter,
      lastEventBefore,
    } = filters || {}

    const { field: sortField = DEFAULT_BOX_SORT_FIELD, direction: sortDirection = DEFAULT_BOX_SORT_DIRECTION } =
      sort || {}

    const baseFindOptions: FindOptionsWhere<Box> = {
      organizationId,
      ...(labels ? { labels: JsonContains(labels) } : {}),
      ...(regionIds ? { region: In(regionIds) } : {}),
    }

    baseFindOptions.cpu = createRangeFilter(minCpu, maxCpu)
    if (minMemoryGiB !== undefined || maxMemoryGiB !== undefined) {
      baseFindOptions.memoryMib = Raw(
        (alias) => {
          const legacy = `${alias.slice(0, alias.lastIndexOf('.') + 1)}mem`
          const gib = `COALESCE(${alias}, ${legacy} * 1024) / 1024.0`
          return [
            minMemoryGiB !== undefined && `${gib} >= :minMemoryGiB`,
            maxMemoryGiB !== undefined && `${gib} <= :maxMemoryGiB`,
          ]
            .filter(Boolean)
            .join(' AND ')
        },
        { minMemoryGiB, maxMemoryGiB },
      )
    }
    baseFindOptions.disk = createRangeFilter(minDiskGiB, maxDiskGiB)
    baseFindOptions.updatedAt = createRangeFilter(lastEventAfter, lastEventBefore)

    const statesToInclude = (states || Object.values(BoxState)).filter((state) => state !== BoxState.DESTROYED)
    const errorStates = [BoxState.ERROR]

    const nonErrorStatesToInclude = statesToInclude.filter((state) => !errorStates.includes(state))
    const errorStatesToInclude = statesToInclude.filter((state) => errorStates.includes(state))

    const where: FindOptionsWhere<Box>[] = []
    const searchFindOptions = this.getBoxSearchFindOptions(baseFindOptions, id, name)

    if (nonErrorStatesToInclude.length > 0) {
      where.push(
        ...searchFindOptions.map((findOptions) => ({
          ...findOptions,
          state: In(nonErrorStatesToInclude),
        })),
      )
    }

    if (errorStatesToInclude.length > 0) {
      where.push(
        ...searchFindOptions.map((findOptions) => ({
          ...findOptions,
          state: In(errorStatesToInclude),
          ...(includeErroredDestroyed ? {} : { desiredState: Not(BoxDesiredState.DESTROYED) }),
        })),
      )
    }

    const [items, total] = await this.boxRepository.findAndCount({
      where,
      order: {
        [sortField]: {
          direction: sortDirection,
          nulls: 'LAST',
        },
        ...(sortField !== BoxSortField.CREATED_AT && { createdAt: 'DESC' }),
      },
      skip: (pageNum - 1) * limitNum,
      take: limitNum,
    })

    return {
      items,
      total,
      page: pageNum,
      totalPages: Math.ceil(total / limitNum),
    }
  }

  private getBoxSearchFindOptions(
    baseFindOptions: FindOptionsWhere<Box>,
    id?: string,
    name?: string,
  ): FindOptionsWhere<Box>[] {
    const nameFilter = name ? { name: ILike(`${name}%`) } : {}

    if (!id) {
      return [
        {
          ...baseFindOptions,
          ...nameFilter,
        },
      ]
    }

    const idFilter = ILike(`${id}%`)
    return [
      {
        ...baseFindOptions,
        ...nameFilter,
        id: idFilter,
      },
      {
        ...baseFindOptions,
        ...nameFilter,
        name: idFilter,
      },
    ]
  }

  private getExpectedDesiredStateForState(state: BoxState): BoxDesiredState | undefined {
    switch (state) {
      case BoxState.STARTED:
        return BoxDesiredState.STARTED
      case BoxState.STOPPED:
        return BoxDesiredState.STOPPED
      case BoxState.DESTROYED:
        return BoxDesiredState.DESTROYED
      default:
        return undefined
    }
  }

  private hasValidDesiredState(state: BoxState): boolean {
    return this.getExpectedDesiredStateForState(state) !== undefined
  }

  private getStartupJobTypeForState(state: BoxState): JobType | undefined {
    switch (state) {
      case BoxState.CREATING:
        return JobType.CREATE_BOX
      case BoxState.STARTING:
        return JobType.START_BOX
      default:
        return undefined
    }
  }

  /**
   * The box's own startup job, if it was claimed by its runner and has since
   * stopped making progress.
   *
   * "Stalled" is measured from when the runner claimed the job, because that
   * is what a lost completion callback looks like from here: claimed, never
   * closed. A job still within the window is assumed to be running normally,
   * and an unclaimed (PENDING) job has no runner to have lost anything.
   */
  private async findStalledStartupJob(box: Box): Promise<Job | null> {
    const startupJobType = this.getStartupJobTypeForState(box.state)
    if (!startupJobType || !box.runnerId) {
      return null
    }

    const stallSeconds = this.configService.getOrThrow('boxSync.startConfirmationStallSeconds')
    const claimedBefore = new Date(Date.now() - stallSeconds * 1000)

    return this.jobRepository.findOne({
      where: {
        runnerId: box.runnerId,
        resourceType: ResourceType.BOX,
        resourceId: box.id,
        type: startupJobType,
        status: JobStatus.IN_PROGRESS,
        startedAt: LessThan(claimedBefore),
      },
      order: { createdAt: 'DESC' },
    })
  }

  async findByRunnerId(runnerId: string, states?: BoxState[], skipReconcilingBoxes?: boolean): Promise<Box[]> {
    const where: FindOptionsWhere<Box> = { runnerId }
    if (states && states.length > 0) {
      // Only the skip filter needs a state to have a corresponding desired
      // state — it is defined as "state already matches desired state". Asking
      // for a transitional state is a legitimate query on its own (a runner
      // reconciling a startup whose job completion was lost does exactly
      // that), so the requirement belongs to the filter, not to the parameter.
      if (skipReconcilingBoxes) {
        states.forEach((state) => {
          if (!this.hasValidDesiredState(state)) {
            throw new BadRequestError(`State ${state} does not have a corresponding desired state`)
          }
        })
      }
      where.state = In(states)
    }

    let boxes = await this.boxRepository.find({ where })

    if (skipReconcilingBoxes) {
      boxes = boxes.filter((box) => {
        const expectedDesiredState = this.getExpectedDesiredStateForState(box.state)
        return expectedDesiredState !== undefined && expectedDesiredState === box.desiredState
      })
    }

    return boxes
  }

  async findOneByIdOrName(
    boxIdOrName: string,
    organizationId?: string,
    returnDestroyed?: boolean,
    lockTimeoutMs?: number,
  ): Promise<Box> {
    const stateFilter = returnDestroyed ? {} : { state: Not(BoxState.DESTROYED) }
    const organizationFilter = organizationId ? { organizationId } : {}

    // Public Box ID is the primary key. Name remains a user-facing fallback within an organization.
    let box = await this.boxRepository.findOne({
      lockTimeoutMs,
      where: {
        id: boxIdOrName,
        ...organizationFilter,
        ...stateFilter,
      },
      cache: {
        id: boxLookupCacheKeyById({ organizationId, returnDestroyed, id: boxIdOrName }),
        milliseconds: BOX_LOOKUP_CACHE_TTL_MS,
      },
    })

    if (!box) {
      box = await this.boxRepository.findOne({
        lockTimeoutMs,
        where: {
          name: boxIdOrName,
          ...organizationFilter,
          ...stateFilter,
        },
        cache: {
          id: boxLookupCacheKeyByName({ organizationId, returnDestroyed, boxName: boxIdOrName }),
          milliseconds: BOX_LOOKUP_CACHE_TTL_MS,
        },
      })
    }

    if (!box || (!returnDestroyed && box.state === BoxState.ERROR && box.desiredState === BoxDesiredState.DESTROYED)) {
      throw new NotFoundException(`Box with ID or name ${boxIdOrName} not found`)
    }

    return box
  }

  async findOne(boxId: string, returnDestroyed?: boolean): Promise<Box> {
    const box = await this.boxRepository.findOne({
      where: {
        id: boxId,
        ...(returnDestroyed ? {} : { state: Not(BoxState.DESTROYED) }),
      },
    })

    if (!box || (!returnDestroyed && box.state === BoxState.ERROR && box.desiredState === BoxDesiredState.DESTROYED)) {
      throw new NotFoundException(`Box with ID ${boxId} not found`)
    }

    return box
  }

  async getOrganizationId(boxIdOrName: string, organizationId?: string): Promise<string> {
    const organizationFilter = organizationId ? { organizationId: organizationId } : {}

    let box = await this.boxRepository.findOne({
      where: {
        id: boxIdOrName,
        ...organizationFilter,
      },
      select: ['organizationId'],
      cache: {
        id: boxOrgIdCacheKeyById({ organizationId, id: boxIdOrName }),
        milliseconds: BOX_ORG_ID_CACHE_TTL_MS,
      },
    })

    if (!box && organizationId) {
      box = await this.boxRepository.findOne({
        where: {
          name: boxIdOrName,
          organizationId: organizationId,
        },
        select: ['organizationId'],
        cache: {
          id: boxOrgIdCacheKeyByName({ organizationId, boxName: boxIdOrName }),
          milliseconds: BOX_ORG_ID_CACHE_TTL_MS,
        },
      })
    }

    if (!box || !box.organizationId) {
      throw new NotFoundException(`Box with ID or name ${boxIdOrName} not found`)
    }

    return box.organizationId
  }

  async getRunnerId(boxIdOrName: string): Promise<string | null> {
    const box = await this.boxRepository.findOne({
      where: [{ id: boxIdOrName }, { name: boxIdOrName }],
      select: ['runnerId'],
      loadEagerRelations: false,
    })

    if (!box) {
      throw new NotFoundException(`Box with ID or name ${boxIdOrName} not found`)
    }

    return box.runnerId || null
  }

  async getRegionId(boxIdOrName: string): Promise<string> {
    const box = await this.boxRepository.findOne({
      where: [{ id: boxIdOrName }, { name: boxIdOrName }],
      select: ['region'],
      loadEagerRelations: false,
    })

    if (!box) {
      throw new NotFoundException(`Box with ID or name ${boxIdOrName} not found`)
    }

    return box.region
  }

  async getNetworkTunnelUrl(boxIdOrName: string, organizationId: string, port: number): Promise<string> {
    if (port < 1 || port > 65535) {
      throw new BadRequestError('Invalid port')
    }

    const proxyDomain = this.configService.getOrThrow('proxy.domain')
    const proxyProtocol = this.configService.getOrThrow('proxy.protocol')
    const box = await this.findOneByIdOrName(boxIdOrName, organizationId)
    const endpointId = encodeDirectPreviewBoxId(box.id)

    let url = `${proxyProtocol}://${port}-${endpointId}.${proxyDomain}`
    const region = await this.regionService.findOne(box.region, true)
    if (region?.proxyUrl) {
      url = region.proxyUrl.replace(/(https?:\/)(\/)/, `$1/${port}-${endpointId}.`)
    }
    return url
  }

  private async lifecycleBox(
    id: string,
    organizationId: string | undefined,
    lookup: 'id' | 'id-or-name',
    lockTimeoutMs?: number,
  ) {
    if (lookup === 'id-or-name') return this.findOneByIdOrName(id, organizationId, undefined, lockTimeoutMs)
    const box = await this.findOne(id, true)
    if (!organizationId || box.organizationId !== organizationId || box.state === BoxState.DESTROYED)
      throw new NotFoundException(`Box with ID ${id} not found`)
    return box
  }

  async destroy(
    boxIdOrName: string,
    organizationId: string | undefined,
    ctx: Context,
    lookup: 'id' | 'id-or-name' = 'id-or-name',
  ): Promise<Box> {
    const selected = await this.lifecycleBox(boxIdOrName, organizationId, lookup)
    const { box, checkpointState } = await this.boxRepository.findWithCheckpointState(
      selected.id,
      selected.organizationId,
    )

    const waitingFilestoreRestart =
      box.state === BoxState.STOPPED &&
      box.desiredState === BoxDesiredState.STARTED &&
      box.volumes?.some((volume) => volume.filestore)
    if (box.pending && !checkpointState?.activeJobId && !waitingFilestoreRestart) {
      throw new BoxError('Box state change in progress')
    }

    const updatedBox = checkpointState?.activeJobId
      ? await this.boxRepository.deleteCheckpointTarget(box, checkpointState)
      : await this.boxRepository.requestDestroy(box)

    recordBoxRequested('box.delete', updatedBox, ctx)

    const committedCheckpointState = checkpointState?.activeJobId
      ? { ...checkpointState, activeJobId: null, sequence: checkpointState.sequence + 1 }
      : checkpointState
    this.eventEmitter.emit(
      BoxEvents.DESTROYED,
      new BoxDestroyedEvent(updatedBox, { checkpointState: committedCheckpointState }),
    )
    return updatedBox
  }

  async start(
    boxIdOrName: string,
    organization: Organization,
    ctx: Context,
    options?: { idOnly?: boolean },
  ): Promise<Box> {
    const box = options?.idOnly
      ? await this.findOne(boxIdOrName)
      : await this.findOneByIdOrName(boxIdOrName, organization.id)
    if (box.organizationId !== organization.id) throw new NotFoundException('Box not found')

    const region = await this.regionService.findOne(box.region)
    if (!region) {
      throw new NotFoundException(`Region with ID ${box.region} not found`)
    }

    if (box.state === BoxState.STARTED && box.desiredState === BoxDesiredState.STARTED) {
      return box
    }

    this.assertBoxNotErrored(box)

    if (String(box.state) !== String(box.desiredState)) {
      throw new BoxError('State change in progress')
    }

    if (box.state !== BoxState.STOPPED) {
      throw new BoxError('Box is not in valid state')
    }

    if (box.pending) {
      throw new BoxError('Box state change in progress')
    }

    this.organizationService.assertOrganizationIsNotSuspended(organization)

    const updateData: Partial<Box> = {
      pending: true,
      desiredState: BoxDesiredState.STARTED,
      authToken: nanoid(32).toLocaleLowerCase(),
    }

    const updatedBox = await this.boxRepository.updateWhere(box.id, {
      updateData,
      whereCondition: { pending: false, state: box.state },
    })

    recordBoxRequested('box.start', updatedBox, ctx)

    this.eventEmitter.emit(BoxEvents.STARTED, new BoxStartedEvent(updatedBox))

    return updatedBox
  }

  /**
   * Submit or join a proxy-triggered Start intent.
   *
   * Only a stable STOPPED box performs the conditional update. Transitional
   * states are returned unchanged so the caller can wait and retry. Unexpected
   * database errors propagate; AutoResume must never proxy before readiness.
   */
  async ensureStartedForProxy(boxIdOrName: string, organization: Organization, admit?: ProxyAdmission): Promise<Box> {
    this.organizationService.assertOrganizationIsNotSuspended(organization)
    const box = await this.findOneByIdOrName(boxIdOrName, organization.id)

    // Check the freshly read state inside the caller's lifecycle lock.
    admit?.(box, boxIdOrName)

    if (box.state !== BoxState.STOPPED || box.desiredState !== BoxDesiredState.STOPPED || box.pending) {
      return box
    }

    const updated = await this.boxRepository.conditionalStartForProxy(box.id, organization.id)
    if (!updated) {
      return this.findOneByIdOrName(box.id, organization.id)
    }

    recordBoxRequested('box.start', updated, Context.platform(PlatformReason.AUTO_RESUME))

    this.eventEmitter.emit(BoxEvents.STARTED, new BoxStartedEvent(updated))
    this.eventEmitter.emit(
      BoxEvents.DESIRED_STATE_UPDATED,
      new BoxDesiredStateUpdatedEvent(updated, BoxDesiredState.STOPPED, BoxDesiredState.STARTED),
    )
    return updated
  }

  async stop(
    boxIdOrName: string,
    organizationId: string | undefined,
    ctx: Context,
    force?: boolean,
    lookup: 'id' | 'id-or-name' = 'id-or-name',
  ): Promise<Box> {
    const box = await this.lifecycleBox(boxIdOrName, organizationId, lookup, ctx.lockTimeoutMs)

    this.assertBoxNotErrored(box)

    if (String(box.state) !== String(box.desiredState)) {
      throw new BoxError('State change in progress')
    }

    if (box.state !== BoxState.STARTED) {
      throw new BoxError('Box is not started')
    }

    if (box.pending) {
      throw new BoxError('Box state change in progress')
    }

    const updateData: Partial<Box> = {
      pending: true,
      desiredState: BoxDesiredState.STOPPED,
    }

    const updatedBox = await this.boxRepository.updateWhere(box.id, {
      updateData,
      whereCondition: { pending: false, state: box.state, organizationId: box.organizationId },
      lockTimeoutMs: ctx.lockTimeoutMs,
    })

    recordBoxRequested('box.stop', updatedBox, ctx)

    this.eventEmitter.emit(BoxEvents.STOPPED, new BoxStoppedEvent(updatedBox, force))

    return updatedBox
  }

  async recover(boxIdOrName: string, organization: Organization, ctx: Context): Promise<Box> {
    const box = await this.findOneByIdOrName(boxIdOrName, organization.id)

    if (box.state !== BoxState.ERROR) {
      throw new BadRequestError('Box must be in error state to recover')
    }

    if (box.pending) {
      throw new BoxError('Box state change in progress')
    }

    // Validate runner exists
    if (!box.runnerId) {
      throw new NotFoundException(`Box with ID ${box.id} does not have a runner`)
    }
    const runner = await this.runnerService.findOneOrFail(box.runnerId)

    if (runner.apiVersion === '2') {
      // TODO: we need "recovering" state that can be set after calling recover
      // Once in recovering, we abort further processing and let the manager/job handler take care of it
      throw new ForbiddenException('Recovering boxes with runner API version 2 is not supported')
    }

    const runnerAdapter = await this.runnerAdapterFactory.create(runner)

    try {
      await runnerAdapter.recoverBox(box)
    } catch (error) {
      if (error instanceof Error && error.message.includes('storage cannot be further expanded')) {
        const errorMsg = `Box storage cannot be further expanded. Maximum expansion of ${(box.disk * 0.1).toFixed(2)}GB (10% of original ${box.disk.toFixed(2)}GB) has been reached. Please contact support for further assistance.`
        throw new ForbiddenException(errorMsg)
      }
      throw error
    }

    const updateData: Partial<Box> = {
      state: BoxState.STOPPED,
      desiredState: BoxDesiredState.STOPPED,
      errorReason: null,
      recoverable: false,
    }

    await this.boxRepository.updateWhere(box.id, {
      updateData,
      whereCondition: { state: BoxState.ERROR },
    })

    // Now that box is in STOPPED state, use the normal start flow
    // This handles state validation and event emission.
    return await this.start(box.id, organization, ctx)
  }

  async updateInboundEnabled(boxIdOrName: string, inboundEnabled: boolean, organizationId?: string): Promise<Box> {
    const box = await this.findOneByIdOrName(boxIdOrName, organizationId)

    const updateData: Partial<Box> = {
      inboundEnabled,
    }

    return await this.boxRepository.update(box.id, {
      updateData,
      entity: box,
    })
  }

  async updateLastActivityAt(boxId: string, lastActivityAt: Date, previewOpen = false): Promise<void> {
    if (!previewOpen) return this.boxActivityService.updateLastActivityAt(boxId, lastActivityAt)
    const controller = new AbortController()
    const { signal } = controller
    let operation = 'update_activity'
    let timeout: ReturnType<typeof setTimeout>
    const observe = async () => {
      await this.boxActivityService.updateLastActivityAt(boxId, lastActivityAt, signal)
      signal.throwIfAborted()
      operation = 'deduplicate'
      const first = await this.redis.set(`box:preview-open:${boxId}`, '1', 'EX', 60, 'NX')
      signal.throwIfAborted()
      if (first !== 'OK') return
      operation = 'load_box'
      const box = await this.findOne(boxId)
      signal.throwIfAborted()
      operation = 'record_event'
      recordBusinessEvent({
        name: 'box.open',
        outcome: 'success',
        correlationId: box.id,
        organizationId: box.organizationId,
      })
    }
    try {
      await Promise.race([
        observe(),
        new Promise<never>((_, reject) => {
          timeout = setTimeout(() => {
            const error = new Error('Preview activity deadline exceeded')
            controller.abort(error)
            reject(error)
          }, PREVIEW_ACTIVITY_TIMEOUT_MS)
        }),
      ])
    } catch (error) {
      // Preserve activity-buffer failures; only preview observation/timeouts fail closed.
      if (operation === 'update_activity' && !signal.aborted) throw error
      this.logger.warn('Preview activity observation could not be recorded', {
        boxId,
        operation,
        errorType: signal.aborted ? 'timeout' : mutationFailureType(error),
      })
    } finally {
      clearTimeout(timeout)
    }
  }

  /**
   * Last activity is metadata about the box rather than part of it, so the read
   * degrades to absent instead of failing the conversion: create() has already
   * persisted the box by the time it converts, and a rejection there would read
   * to the client as a failed creation and invite a duplicate on retry. The
   * auto-lifecycle paths keep reading it directly, where the distinction
   * between "unknown" and "idle" decides whether a box is stopped.
   */
  async toBoxDto(box: Box): Promise<BoxDto> {
    const reads = await this.resolveDtoMetadata(box)
    return BoxDto.fromBox(box, reads)
  }

  /**
   * The out-of-entity values every single-box conversion needs, read together.
   * The preparation read is here rather than in {@link toBoxDto} alone because
   * a caller polling a creating box reads it through
   * {@link toBoxDtoWithExitCode}, and that is the caller progress is for.
   */
  private async resolveDtoMetadata(box: Box): Promise<BoxDtoReads> {
    const [lastActivityAt, preparing] = await Promise.all([
      this.boxActivityService.getLastActivityAt(box.id).catch((err) => {
        this.logger.warn(`Failed to read last activity for box ${box.id}: ${err}`)
        return null
      }),
      // Degrades to absent for the same reason as the activity read: what the
      // box is waiting on is commentary on the box, and losing it must not turn
      // a successful create into a failed one.
      this.imagePreparationService.preparingImage([box]).catch((err) => {
        this.logger.warn(`Failed to read image preparation for box ${box.id}: ${err}`)
        return new Set<string>()
      }),
    ])
    return { lastActivityAt, preparingImage: preparing.has(box.id) }
  }

  /**
   * A box as a tenant asked to read it, with the main command's exit code.
   *
   * Separate from {@link toBoxDto} because the code comes from the box's
   * runner, and that is a cross-service call. `toBoxDto` is on the event path:
   * every `BoxEvents.STATE_UPDATED` converts through it
   * (`NotificationService`), as does every resolution in
   * `BoxStateWaiterService`. A box reaching STOPPED is exactly what fires
   * those, so reading there would put a runner round trip in front of every
   * stop notification — and make each one wait out the timeout precisely when
   * the runner is the thing that went wrong.
   *
   * Only the two endpoints that answer a tenant's read use this.
   */
  async toBoxDtoWithExitCode(box: Box): Promise<BoxDto> {
    const [reads, exitCode] = await Promise.all([
      this.resolveDtoMetadata(box),
      this.boxExitCodeService.getExitCode(box),
    ])
    return BoxDto.fromBox(box, { ...reads, exitCode })
  }

  /**
   * Degrades a failed activity read to absent, as {@link toBoxDto} does.
   *
   * Exit codes are deliberately left out here. Reading one means asking the
   * runner that owns the box, so a list would fan out to one call per box; the
   * field is optional in the spec, so omitting it on a list is conformant. A
   * client that needs it reads the box itself.
   */
  async toBoxDtos(boxes: Box[]): Promise<BoxDto[]> {
    const [activityMap, preparing] = await Promise.all([
      this.boxActivityService.getLastActivityAtMany(boxes.map((s) => s.id)).catch((err) => {
        this.logger.warn(`Failed to read last activity for ${boxes.length} boxes: ${err}`)
        return new Map<string, Date>()
      }),
      this.imagePreparationService.preparingImage(boxes).catch((err) => {
        this.logger.warn(`Failed to read image preparation for ${boxes.length} boxes: ${err}`)
        return new Set<string>()
      }),
    ])
    return boxes.map((s) => {
      return BoxDto.fromBox(s, { lastActivityAt: activityMap.get(s.id), preparingImage: preparing.has(s.id) })
    })
  }

  private async getValidatedOrDefaultRegion(organization: Organization, regionIdOrName?: string): Promise<Region> {
    regionIdOrName = regionIdOrName?.trim()

    if (!regionIdOrName) {
      const defaultRegionId = organization.defaultRegionId || this.configService.getOrThrow('defaultRegion.id')
      const region = await this.regionService.findOne(defaultRegionId)
      if (!region) {
        throw new NotFoundException('Default region not found')
      }
      return region
    }

    const region =
      (await this.regionService.findOneByName(regionIdOrName, organization.id)) ??
      (await this.regionService.findOneByName(regionIdOrName, null)) ??
      (await this.regionService.findOne(regionIdOrName))

    if (!region) {
      throw new NotFoundException('Region not found')
    }

    return region
  }

  private getValidatedOrDefaultClass(boxClass: BoxClass): BoxClass {
    if (!boxClass) {
      return BoxClass.SMALL
    }

    if (Object.values(BoxClass).includes(boxClass)) {
      return boxClass
    } else {
      throw new BadRequestError('Invalid class')
    }
  }

  @Cron(CronExpression.EVERY_SECOND, { name: 'cleanup-destroyed-boxes' })
  @LogExecution('cleanup-destroyed-boxes')
  @WithInstrumentation()
  async cleanupDestroyedBoxes() {
    const twentyFourHoursAgo = new Date()
    twentyFourHoursAgo.setHours(twentyFourHoursAgo.getHours() - 24)

    const retained = chargedNativeTombstone(this.configService.get('ci.githubClientId'))
    const destroyedBoxs = await this.boxRepository
      .createQueryBuilder()
      .delete()
      .where({ state: BoxState.DESTROYED, updatedAt: LessThan(twentyFourHoursAgo) })
      .andWhere(`NOT ${retained.sql}`, retained.parameters)
      .execute()

    if (destroyedBoxs.affected > 0) {
      this.logger.debug(`Cleaned up ${destroyedBoxs.affected} destroyed boxes`)
    }
  }

  @Cron(CronExpression.EVERY_SECOND, { name: 'cleanup-stale-error-boxes' })
  @LogExecution('cleanup-stale-error-boxes')
  @WithInstrumentation()
  async cleanupStaleErrorBoxes() {
    const sevenDaysAgo = new Date()
    sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7)

    const target = pendingDeletionTarget(this.configService.get('ci.githubClientId'))
    const result = await this.boxRepository
      .createQueryBuilder()
      .delete()
      .where({ state: BoxState.ERROR, desiredState: BoxDesiredState.DESTROYED, updatedAt: LessThan(sevenDaysAgo) })
      .andWhere(`NOT ${target.sql}`, target.parameters)
      .execute()

    if (result.affected > 0) {
      this.logger.debug(`Cleaned up ${result.affected} stale error boxes`)
    }
  }

  async updateNetworkSettings(
    boxIdOrName: string,
    outboundEnabled?: boolean,
    outboundAllowNet?: string[],
    organizationId?: string,
  ): Promise<Box> {
    const box = await this.findOneByIdOrName(boxIdOrName, organizationId)

    const updateData: Partial<Box> = {}

    if (outboundEnabled !== undefined) {
      updateData.outboundEnabled = outboundEnabled
    }

    if (outboundAllowNet !== undefined) {
      updateData.outboundAllowNet = this.resolveOutboundAllowNet(outboundAllowNet)
    }

    const updatedBox = await this.boxRepository.update(box.id, { updateData, entity: box })

    // Update network settings on the runner
    if (box.runnerId) {
      const runner = await this.runnerService.findOne(box.runnerId)
      if (runner) {
        const runnerAdapter = await this.runnerAdapterFactory.create(runner)
        await runnerAdapter.updateNetworkSettings(box.id, updateData.outboundEnabled, updateData.outboundAllowNet)
      }
    }

    return updatedBox
  }

  async setOutboundNetwork(boxIdOrName: string, policy: OutboundPolicy, organizationId: string): Promise<Box> {
    if (hasDisabledOutboundRules(policy.mode, policy.allow_net)) {
      throw new BadRequestError(DISABLED_OUTBOUND_RULES_ERROR)
    }
    const allowNet = this.resolveOutboundAllowNet(policy.allow_net) ?? []
    const box = await this.findOneByIdOrName(boxIdOrName, organizationId)
    const resolved = { ...policy, allow_net: allowNet }
    return this.boxRepository.replaceOutbound(box.id, organizationId, resolved, async (locked, next) => {
      const runner = await this.runnerService.findOne(locked.runnerId)
      if (!runner) throw new ConflictException('Box runner is unavailable')
      await setRunnerOutbound(runner, locked.id, next)
    })
  }

  // used by internal services to update the state of a box to resolve domain and runner state mismatch
  // notably, when a box instance stops or errors on the runner, the domain state needs to be updated to reflect the actual state
  async updateState(
    boxId: string,
    newState: BoxState,
    recoverable = false,
    errorReason?: string,
    reportedImage?: ReportedImage,
  ): Promise<void> {
    const box = await this.boxRepository.findOne({
      where: { id: boxId },
    })

    if (!box) {
      throw new NotFoundException(`Box with ID ${boxId} not found`)
    }

    // Before any state handling, and deliberately not inside it: this is a fact
    // about the box's image, not a transition. The runner may well be telling
    // us a state we already have — the control plane also learns a box is up by
    // polling the runner — and the early returns below would drop the report.
    //
    // Only a report that says the box is up: a failed pull reports ERROR, and
    // an image that never booted must not appear in the catalog as if it had.
    // It is the report that is filtered, not the outcome — the state machine
    // below may still refuse this transition, and a box that pulled an image
    // and started it did so either way.
    if (reportedImage && newState === BoxState.STARTED && box.image) {
      try {
        await this.imageRegistrarService.onBoxStarted(
          box.organizationId,
          { ref: box.image, isOrgOwned: boxImageIsOrgOwned(box), runnerId: box.runnerId },
          reportedImage,
        )
      } catch (error) {
        // A lost registration costs the next create one re-resolution, which
        // is the documented trade; one refused for the image limit leaves the
        // name unrecorded, so admission refuses the next create of it. Failing
        // the state update instead would leave the control plane believing a
        // running box is still starting.
        this.logger.error(`Failed to register image for box ${boxId}: ${error}`)
      }
    }

    if (box.state === newState) {
      this.logger.debug(`Box ${boxId} is already in state ${newState}`)
      return
    }

    // A stale runner snapshot can say a box that is already up is still
    // creating: a configured-but-never-booted local record folds into
    // Creating. Believing it walks STARTED back to CREATING, leaves
    // desiredState at STARTED, and the pending invariant then blocks destroy
    // with "state change in progress". The report is stale, not the box —
    // acknowledge it without writing, so an older runner gains nothing from
    // retrying. Real runtime exits (STOPPED, ERROR) are unaffected below.
    if (box.state === BoxState.STARTED && newState === BoxState.CREATING) {
      this.logger.debug(`Ignoring stale creating report for started box ${boxId}`)
      return
    }

    //  only allow updating the state of started | stopped boxes
    if (![BoxState.STARTED, BoxState.STOPPED].includes(box.state)) {
      // One exception: a runner reporting STARTED for a box we still show as
      // coming up. That means its startup job finished on the runner but the
      // completion never reached us. Believe it only once the job has stopped
      // making progress on its own — until then the normal callback is still
      // the better answer, and we say nothing rather than reject a runner that
      // is telling the truth.
      if (newState !== BoxState.STARTED || box.desiredState !== BoxDesiredState.STARTED) {
        throw new BadRequestError('Box is not in a valid state to be updated')
      }

      const stalledStartupJob = await this.findStalledStartupJob(box)
      if (!stalledStartupJob) {
        this.logger.debug(`Box ${boxId} start not yet confirmable; startup job still progressing`)
        return
      }

      // Completing the job is what moves the box: the normal completion
      // handler owns the STARTED transition, the pending flag, the activity
      // stamp, the state-change event, and releasing the box's Redis lock.
      // Doing any of that here instead would fork that logic.
      this.logger.warn(
        `Completing stalled startup job ${stalledStartupJob.id} for box ${boxId} from runner-reported state`,
      )
      await this.jobService.updateJobStatus(stalledStartupJob.id, JobStatus.COMPLETED)
      return
    }

    if (box.desiredState == BoxDesiredState.DESTROYED) {
      this.logger.debug(`Box ${boxId} is already DESTROYED, skipping state update`)
      return
    }

    const oldState = box.state
    const oldDesiredState = box.desiredState

    const updateData: Partial<Box> = {
      state: newState,
      recoverable: false,
    }

    if (errorReason !== undefined) {
      // The runner's words, which can name the registry proxy ref it pulled.
      updateData.errorReason = withoutRegistryProxy(errorReason)
      if (newState === BoxState.ERROR) {
        updateData.errorReason = await this.imagePullFailureService.reasonFor(box, updateData.errorReason)
        updateData.recoverable = recoverable
      }
    }

    //  we need to update the desired state to match the new state
    const desiredState = this.getExpectedDesiredStateForState(newState)
    if (desiredState) {
      updateData.desiredState = desiredState
    }

    await this.boxRepository.updateWhere(box.id, {
      updateData,
      whereCondition: { pending: false, state: oldState, desiredState: oldDesiredState },
    })
  }

  @OnEvent(WarmPoolEvents.TOPUP_REQUESTED)
  private async createWarmPoolBox(event: WarmPoolTopUpRequested) {
    await this.createForWarmPool(event.warmPool)
  }

  @Cron(CronExpression.EVERY_MINUTE, { name: 'handle-unschedulable-runners' })
  @LogExecution('handle-unschedulable-runners')
  @WithInstrumentation()
  private async handleUnschedulableRunners() {
    const runners = await this.runnerRepository.find({ where: { unschedulable: true } })

    if (runners.length === 0) {
      return
    }

    //  find all boxes that are using the unschedulable runners and have organizationId = '00000000-0000-0000-0000-000000000000'
    const boxes = await this.boxRepository.find({
      where: {
        runnerId: In(runners.map((runner) => runner.id)),
        organizationId: '00000000-0000-0000-0000-000000000000',
        state: BoxState.STARTED,
        desiredState: Not(BoxDesiredState.DESTROYED),
      },
    })

    if (boxes.length === 0) {
      return
    }

    const destroyPromises = boxes.map((box) =>
      this.destroy(box.id, undefined, Context.platform(PlatformReason.WARM_POOL)),
    )
    const results = await Promise.allSettled(destroyPromises)

    // Log any failed box destructions
    results.forEach((result, index) => {
      if (result.status === 'rejected') {
        this.logger.error(`Failed to destroy box ${boxes[index].id}: ${result.reason}`)
      }
    })
  }

  async getInboundMode(boxId: string): Promise<NetworkMode> {
    const box = await this.boxRepository.findOne({
      where: { id: boxId },
    })

    if (!box) {
      throw new NotFoundException(`Box with ID ${boxId} not found`)
    }

    return networkMode(box.inboundEnabled)
  }

  @OnEvent(OrganizationEvents.SUSPENDED_BOX_STOPPED)
  async handleSuspendedBoxStopped(event: OrganizationSuspendedBoxStoppedEvent) {
    await this.stop(event.boxId, undefined, Context.platform(PlatformReason.ORG_SUSPENSION)).catch((error) => {
      //  log the error for now, but don't throw it as it will be retried
      this.logger.error(`Error stopping box from suspended organization. BoxId: ${event.boxId}: `, error)
    })
  }

  private resolveLifecyclePolicy(input: { autoStop?: number; autoDelete?: number; autoResume?: boolean }): {
    autoStop: number
    autoDelete: number
    autoResume: boolean
  } {
    const autoStop = input.autoStop ?? DEFAULT_AUTO_STOP_SECONDS
    const autoDelete = input.autoDelete ?? AUTO_DELETE_DISABLED
    const autoResume = input.autoResume ?? DEFAULT_AUTO_RESUME

    if (!Number.isInteger(autoStop) || autoStop < AUTO_STOP_DISABLED) {
      throw new BadRequestError('Auto-stop interval must be a non-negative integer number of seconds')
    }
    if (autoStop !== AUTO_STOP_DISABLED && autoStop < MIN_AUTO_STOP_SECONDS) {
      throw new BadRequestError(
        `Auto-stop interval must be 0 (disabled) or at least ${MIN_AUTO_STOP_SECONDS} seconds; shorter windows cannot be kept alive by proxy traffic`,
      )
    }
    if (!Number.isInteger(autoDelete) || autoDelete < AUTO_DELETE_DISABLED) {
      throw new BadRequestError('Auto-delete interval must be a non-negative integer number of seconds')
    }

    return { autoStop, autoDelete, autoResume }
  }

  private resolveOutboundAllowNet(allowNet: string[]): string[] | undefined {
    try {
      validateNetworkAllowList(allowNet)
    } catch (error) {
      throw new BadRequestError(error instanceof Error ? error.message : 'Invalid network allow list')
    }

    const entries = allowNet.map((entry) => entry.trim()).filter(Boolean)
    return entries.length > 0 ? entries : undefined
  }

  private resolveVolumes(volumes: BoxVolume[]): BoxVolume[] {
    try {
      validateMountPaths(volumes)
    } catch (error) {
      throw new BadRequestError(error instanceof Error ? error.message : 'Invalid volume mount configuration')
    }

    try {
      validateSubpaths(volumes)
    } catch (error) {
      throw new BadRequestError(error instanceof Error ? error.message : 'Invalid volume subpath configuration')
    }

    return volumes
  }
}

function encodeDirectPreviewBoxId(boxId: string): string {
  return `d-${Buffer.from(boxId, 'utf8').toString('hex')}`
}