# The remote crew deployment image: two processes, one task.
#
# What runs here is Kiro Crew's own backend, headless, plus a thin front process.
# Headless means no interface is served to anyone, the
# owner included: the owner's control plane stays on the owner's own machine and
# no part of it is in this image.
#
# AWS CLI v2 is NOT in Debian apt, so it is fetched and unpacked in a throwaway
# builder stage and only the installed tree is carried into the final image with
# a COPY --from below. The builder's installer (the unzip step, the ./aws/install
# scaffolding, the downloaded zip) never reaches the final image this way.
#
# Same pinning discipline as kiro-cli, for the same reason: the version is pinned
# and the per-arch sha256 is recorded HERE so the build fails if the published
# artifact ever differs from what was reviewed. AWS publishes a detached GPG
# signature but no .sha256, so these were hand-computed from the downloaded zips
# and cross-checked across two fetches while adding this. Bumping AWSCLI_VERSION
# means updating BOTH checksums in the same change. Architecture is resolved from
# the builder (TARGETARCH) and NEVER pinned, exactly as for kiro-cli. ARG
# defaults are overridable, so never pass these as --build-arg: an override
# silently defeats the pin.
FROM python:3.12-slim-bookworm@sha256:782412e85d0f0984994c290652577d4018aff08145c85b262bb63dc0c7522254 AS awscli-builder

ARG TARGETARCH
ARG AWSCLI_VERSION=2.34.0
ARG AWSCLI_SHA256_X86_64=f7137e1c4d6d5cae31fbdcfd1fe03784b71e46aead36ba046674a694e1623aa6
ARG AWSCLI_SHA256_AARCH64=d1abb2e8fcbc9e7ac3b6acf92bf886af67dfb4d30d77b766cc8a56bd00009aeb

RUN set -eux; \
    apt-get update; \
    apt-get install -y --no-install-recommends ca-certificates curl unzip; \
    case "${TARGETARCH:-amd64}" in \
      amd64) AWS_ARCH=x86_64;  AWS_SHA256="${AWSCLI_SHA256_X86_64}" ;; \
      arm64) AWS_ARCH=aarch64; AWS_SHA256="${AWSCLI_SHA256_AARCH64}" ;; \
      *) echo "unsupported TARGETARCH: ${TARGETARCH}" >&2; exit 1 ;; \
    esac; \
    curl -fsSL -o /tmp/awscliv2.zip \
      "https://awscli.amazonaws.com/awscli-exe-linux-${AWS_ARCH}-${AWSCLI_VERSION}.zip"; \
    echo "${AWS_SHA256}  /tmp/awscliv2.zip" | sha256sum -c -; \
    unzip -q /tmp/awscliv2.zip -d /tmp; \
    /tmp/aws/install --bin-dir /usr/local/bin --install-dir /usr/local/aws-cli; \
    /usr/local/bin/aws --version

# Base image: bookworm ships glibc 2.36. The floor for the kiro-cli gnu builds is
# 2.30, not the 2.39 the installer claims, so slim is new enough.
#
# Pinned by manifest-list digest, not only by tag: a tag can move, and nothing
# would detect that the built image differs from the reviewed one. Not
# hypothetical -- while adding this pin, bare `3.12-slim` had already moved to
# trixie (Debian 13), a different release from the bookworm this file's glibc
# reasoning was reviewed against. The tag names the bookworm variant explicitly
# so the digest and the human-readable name cannot disagree. The digest names
# the multi-arch INDEX, so the builder's platform still selects the right
# per-arch manifest (and sets TARGETARCH). To bump:
# `docker buildx imagetools inspect python:3.12-slim-bookworm` and update the
# digest, keeping tag and digest in step.
FROM python:3.12-slim-bookworm@sha256:782412e85d0f0984994c290652577d4018aff08145c85b262bb63dc0c7522254

# Architecture comes from the builder, it is NEVER pinned here. An earlier build
# hardcoded arm64 in two places and cost two separate deploy failures: the image
# refused to exec on an x86 task, and then a task definition kept an arm64
# RuntimePlatform while accepting an x86 parameter that nothing referenced. The
# deploy must cross-check image arch against task arch; this file's job is only
# to not lie about it.
ARG TARGETARCH

# Pinned deliberately: this is the version whose ACP behaviour was verified, down
# to agentCapabilities.loadSession and the shape of its tool events.
ARG KIRO_VERSION=2.20.2

# The expected sha256 of each arch's tarball for KIRO_VERSION. The host does
# publish these (<url>.sha256 and stable/latest/manifest.json), but a checksum
# served by the same host it protects verifies transport, not review: the values
# are recorded HERE so the build fails if the published artifact ever differs
# from what was reviewed. Bumping KIRO_VERSION means updating both in the same
# change (cross-check the hand-computed sha against the published .sha256).
# ARG defaults are overridable, so never pass these as --build-arg: an override
# silently defeats the pin.
ARG KIRO_SHA256_X86_64=232ca9498ba7640ec205b1e2ad02553448c897e63e0a89cb01f60056ae255a59
ARG KIRO_SHA256_AARCH64=49395d0491e6d9e46ce9b900f5e819573bd313751a5b0b6906899a92b438ee3a

# GitHub CLI. A crew can clone a repo with git, but cannot open a pull request
# without gh, so it belongs in a base whose whole point is real crew work. It is
# not in Debian apt, and it ships per-arch tarballs with a PUBLISHED
# checksums.txt, so it follows the identical pinning discipline as kiro-cli:
# version pinned, per-arch sha256 recorded here, arch resolved from TARGETARCH
# and never pinned. The checksums below are the linux_amd64 / linux_arm64
# entries from gh_${GH_VERSION}_checksums.txt on the cli/cli release; bumping
# GH_VERSION means replacing both in the same change. ARG defaults are
# overridable, so never pass these as --build-arg.
ARG GH_VERSION=2.101.0
ARG GH_SHA256_X86_64=9bca2d1c16825f109907a23307628a2f0698fbf99662b73a5cf0b020293072b8
ARG GH_SHA256_AARCH64=b57e8063f18862647c9d22727c32e9da1b963f8bf9db648fe123a6975695640f

# The real CLI toolchain an agent needs to do work: version control (git),
# JSON handling (jq), archive tools (unzip, xz-utils), a pager and process
# listing for interactive-shaped tools (less, procps -> ps), patch/file
# utilities, and an SSH client for git-over-ssh remotes.
#
# curl and xz-utils are KEPT in the final image, which REVERSES the earlier
# design where they were installed only to fetch kiro-cli and then purged (the
# purge is removed below). That reversal is deliberate: an agent doing real work
# routinely needs curl, and there is no separate download-only-then-drop tool to
# protect any more. Everything installed here is meant to stay in the final
# image; nothing in this layer is build-time-only, so there is no purge to keep.
# --no-install-recommends holds the size delta down.
RUN apt-get update \
    && apt-get install -y --no-install-recommends \
        ca-certificates \
        curl \
        file \
        git \
        jq \
        less \
        openssh-client \
        patch \
        procps \
        unzip \
        xz-utils \
    && rm -rf /var/lib/apt/lists/*

# The installed AWS CLI v2 tree, carried over from the throwaway builder stage so
# the installer tooling (the zip, unzip, ./aws/install scaffolding) never enters
# the final image. The install is fully self-contained under /usr/local/aws-cli
# (it bundles its own Python runtime, e.g. dist/libpython3.13.so.1.0), and the
# two entry points are RELATIVE symlinks into that tree:
#   /usr/local/bin/aws -> /usr/local/aws-cli/v2/current/bin/aws -> ../dist/aws
# Copying those symlinks as files would dereference them and sever the relative
# path to dist/, so `aws` would fail to load its bundled libpython. The tree is
# copied whole (COPY preserves its internal symlinks) and the two PATH entries
# are recreated here as symlinks pointing back into it.
COPY --from=awscli-builder /usr/local/aws-cli /usr/local/aws-cli
RUN set -eux; \
    ln -s /usr/local/aws-cli/v2/current/bin/aws           /usr/local/bin/aws; \
    ln -s /usr/local/aws-cli/v2/current/bin/aws_completer /usr/local/bin/aws_completer; \
    aws --version

# `kiro-cli acp` is a thin launcher that dispatches to a SIBLING `kiro-cli-chat`,
# resolved relative to its own path and through PATH. Shipping only the launcher
# builds fine and then fails on the first turn, so both go in and both are
# asserted here. The install is unconditional on purpose: an earlier revision
# made it opt-in via a build arg, the deploy path never passed the arg, and the
# build "succeeded" by skipping the download.
RUN set -eux; \
    case "${TARGETARCH:-amd64}" in \
      amd64) KIRO_ARCH=x86_64;  KIRO_SHA256="${KIRO_SHA256_X86_64}" ;; \
      arm64) KIRO_ARCH=aarch64; KIRO_SHA256="${KIRO_SHA256_AARCH64}" ;; \
      *) echo "unsupported TARGETARCH: ${TARGETARCH}" >&2; exit 1 ;; \
    esac; \
    mkdir -p /tmp/kiro; \
    curl -fsSL -o /tmp/kiro/kirocli.tar.xz \
      "https://prod.download.cli.kiro.dev/stable/${KIRO_VERSION}/kirocli-${KIRO_ARCH}-linux.tar.xz"; \
    echo "${KIRO_SHA256}  /tmp/kiro/kirocli.tar.xz" | sha256sum -c -; \
    tar -xJf /tmp/kiro/kirocli.tar.xz -C /tmp/kiro; \
    install -m 0755 /tmp/kiro/kirocli/bin/kiro-cli      /usr/local/bin/kiro-cli; \
    install -m 0755 /tmp/kiro/kirocli/bin/kiro-cli-chat /usr/local/bin/kiro-cli-chat; \
    rm -rf /tmp/kiro; \
    test -x /usr/local/bin/kiro-cli; \
    test -x /usr/local/bin/kiro-cli-chat; \
    command -v kiro-cli-chat; \
    kiro-cli --version

# GitHub CLI, unpacked from its pinned per-arch tarball. Uses the curl and tar
# already in the image (curl is now kept, tar ships in the base). Only the gh
# binary is installed; the rest of the tarball (man pages, completions) is
# dropped with the temp dir.
RUN set -eux; \
    case "${TARGETARCH:-amd64}" in \
      amd64) GH_ARCH=amd64; GH_SHA256="${GH_SHA256_X86_64}" ;; \
      arm64) GH_ARCH=arm64; GH_SHA256="${GH_SHA256_AARCH64}" ;; \
      *) echo "unsupported TARGETARCH: ${TARGETARCH}" >&2; exit 1 ;; \
    esac; \
    mkdir -p /tmp/gh; \
    curl -fsSL -o /tmp/gh/gh.tar.gz \
      "https://github.com/cli/cli/releases/download/v${GH_VERSION}/gh_${GH_VERSION}_linux_${GH_ARCH}.tar.gz"; \
    echo "${GH_SHA256}  /tmp/gh/gh.tar.gz" | sha256sum -c -; \
    tar -xzf /tmp/gh/gh.tar.gz -C /tmp/gh; \
    install -m 0755 "/tmp/gh/gh_${GH_VERSION}_linux_${GH_ARCH}/bin/gh" /usr/local/bin/gh; \
    rm -rf /tmp/gh; \
    test -x /usr/local/bin/gh; \
    gh --version

# No download tool is purged here on purpose: curl and xz-utils are now part of
# the toolchain the running crew is expected to use (see the apt layer above),
# not build-time-only artifacts. The earlier revision purged them because they
# existed solely to fetch kiro-cli.

WORKDIR /app

# Kiro Crew is installed as a real package because the backend is RUN here, not
# imported as a library. scripts/build_crew_base_image.sh builds the wheel from a
# checkout and stages it in vendor/; the wheel is a build artifact and is not
# committed.
COPY container/requirements.txt ./container/requirements.txt

# The wheel reaches pip through a BuildKit context bind mount and NEVER a COPY.
# Image layers are append-only, so a COPY commits the ~48MB wheel to its own
# layer and a later `rm` can only stack a whiteout on top: every pull then
# fetches the wheel and discards it, beside the already-installed copy of the
# same code. That was measured at 5.7% of the published Kiro Crew image before
# #5778 replaced the COPY with this mount there. The mount makes the bytes
# visible for the duration of this RUN only, which is why no cleanup follows it.
#
# One pip invocation for the container requirements AND the wheel, so both are
# resolved together rather than the wheel silently re-resolving a pinned dep.
# test_docker_wheel_layer_contract.py holds both image recipes to this shape.
RUN --mount=type=bind,source=vendor,target=/tmp/wheels \
    set -eux; \
    WHEEL_COUNT=$(ls /tmp/wheels/*.whl | wc -l); \
    [ "${WHEEL_COUNT}" -eq 1 ] || { echo "expected exactly one wheel, found ${WHEEL_COUNT}" >&2; exit 1; }; \
    pip install --no-cache-dir -r container/requirements.txt /tmp/wheels/*.whl; \
    python -c 'import kiro_crew.cli'

# ONLY the container package. The Kiro Crew app's own backend and UI are in this
# repository too, and they must never be copied in: that code runs inside the
# OWNER's gateway with the owner's AWS credentials, and this image is the
# customer-facing surface. Keeping the COPY narrow is what stops a control-plane
# credential from riding into a customer's container.
COPY container/ ./container/

# Non-root: this container terminates a surface that eventually faces customers,
# and nothing it does needs root.
#
# The state directories are created HERE, in the image, on purpose. A fresh
# volume mounted over a path is initialised from the image's directory at that
# mount point, ownership included, so declaring them owned by `crew` is what
# lets a non-root container write to a mounted transcript store. Without it the
# container starts and dies on a PermissionError that reads like a code fault.
RUN useradd --create-home --home-dir /var/lib/crew --shell /usr/sbin/nologin crew \
    && mkdir -p /var/lib/kirocrew/sessions/archive \
                /var/lib/kirocrew/artifacts \
                /var/lib/kirocrew/run \
                /var/lib/crew/.kiro/agents \
    && chown -R crew:crew /var/lib/kirocrew /var/lib/crew

# The container's own processes (supervisor, front and backup sidecar) read their
# configuration only through container.common, so these names are the whole
# environment contract.
#
# SMC_CONFIG_DIR EQUALS SMC_DATA_HOME, and that is not an oversight. Verified
# against a running gateway: Kiro Crew's config_dir() and data_home() resolve to
# the same directory, so session_map.json and open_slots.json live at the home
# root rather than under a config/ subdirectory. Setting them apart puts those two
# files somewhere the rest of the task does not read, which leaves the transcripts
# findable and the resume and the conversation list not. The supervisor refuses to
# start if they disagree.
ENV HOME=/var/lib/crew \
    KIROCREW_HOME=/var/lib/kirocrew \
    SMC_DATA_HOME=/var/lib/kirocrew \
    SMC_CONFIG_DIR=/var/lib/kirocrew \
    SMC_BACKEND_RUN_DIR=/var/lib/kirocrew/run \
    SMC_BACKEND_PORT=8765 \
    SMC_FRONT_PORT=8080 \
    PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1

# Supplied at run time, never baked in: KIRO_IDENTITY, SMC_CONTROL_SECRET,
# SMC_ROUTE_PREFIX, SMC_CREW_NAME, SMC_BACKUP_BUCKET, SMC_BACKUP_PREFIX and, optionally,
# SMC_BACKUP_INTERVAL_SECS (seconds between backup cycles; default 60, zero or less refused).
USER crew

# 8080 is the front process, the only listener the network reaches. The Kiro Crew
# backend listens on 8765 bound to 127.0.0.1 and is deliberately NOT exposed;
# adding it here would defeat the design's only trust boundary.
EXPOSE 8080

# No HEALTHCHECK on purpose. A docker-level check that proves the port is bound
# would report healthy on a container where every turn fails, which is exactly
# what an invalid model credential produces: a present credential is not a
# working one. Readiness belongs to the front process's own endpoint, which can
# gate on a real turn having succeeded.
CMD ["python", "-m", "container.supervisor"]
