Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(pre-gate): shadow-build changed images over release tags
Jose Ramirezb590c4ade58f
diff --git a/.github/workflows/ci-public.yml b/.github/workflows/ci-public.ymlindex 2d550b255..f20453b01 100644--- a/.github/workflows/ci-public.yml+++ b/.github/workflows/ci-public.yml@@ -372,6 +372,17 @@ jobs:- name: Test minikube Makefile targetsrun: bash scripts/tests/test-minikube-makefile.sh+ # Runs the real pre-gate scripts against PATH stubs for+ # docker/minikube/kubectl/make in a throwaway repo copy. No cluster, no+ # network. It proves a ghcr pre-gate retags its local build onto the ref+ # the Deployment runs, which is the only thing standing between a green+ # gate and a green gate about undeployed code.+ - name: Test pre-gate shadow builds and image-mode resolution+ run: bash scripts/tests/test-minikube-pre-gate-shadow.sh++ - name: Test pre-gate sync state contract+ run: bash scripts/tests/test-minikube-pre-gate-sync-state.sh+# ADMIN_PASSWORD is a required precondition of full-setup.sh Step 1 on the# default (minimal) seed profile. Two cases in this harness execute the# script against stubbed docker/minikube/kubectl, so without it they abortdiff --git a/Makefile b/Makefileindex eeda23c0f..c47a43581 100644--- a/Makefile+++ b/Makefile@@ -235,7 +235,17 @@ minikube-deploy-all: ## Deploy ALL services via Kustomize minikube overlayelse \echo "[minikube-deploy-all] fresh bootstrap: reader staging deferred until post-migration full-setup (GFSC fail-closed)"; \fi- kubectl --context=$(MINIKUBE_PROFILE) kustomize deploy/overlays/minikube | kubectl --context=$(MINIKUBE_PROFILE) apply -f -+ @# THE OVERLAY FOLLOWS THE CLUSTER, NOT THIS SHELL. Hardcoding+ @# deploy/overlays/minikube applied clerum/*:test image refs to a cluster+ @# that pulled ghcr release images: nothing ever built those tags there, so+ @# a deploy/*-only change produced cluster-wide ImagePullBackOff, and a+ @# pre-gate full-deployment silently flipped a ghcr cluster to local refs+ @# with no record. image-mode.sh resolves it from what the last image+ @# acquisition recorded. It runs HERE, after minikube-detect-k8s-api-ip+ @# above, because an overridden tag renders from a copy of deploy/ that must+ @# already contain the generated k8s-api-ip.yaml.+ render_dir="$$(bash scripts/minikube/image-mode.sh --render-dir)" && \+ kubectl --context=$(MINIKUBE_PROFILE) kustomize "$$render_dir" | kubectl --context=$(MINIKUBE_PROFILE) apply -f -CONTEXT=$(MINIKUBE_PROFILE) bash deploy/scripts/apply-inter-service-tokens.sh$(KC) apply -f deploy/overlays/minikube/instances/@# Kustomize reapplies the persisted mcp-host ConfigMap, which can overwritediff --git a/docs/deploy/minikube.md b/docs/deploy/minikube.mdindex 487be20c1..dabb2a0ad 100644--- a/docs/deploy/minikube.md+++ b/docs/deploy/minikube.md@@ -73,6 +73,19 @@ generated config, secrets, and rollouts match the current worktree:make minikube-pre-gate-sync GATE=<gate-name>```+On a cluster running published images (the default), every pod runs a release+image, so the pre-gate **shadow-builds**: it builds only the services your tree+changed and tags each build with the exact `ghcr.io/evenfire-ai/...` ref the+Deployment already references, which `imagePullPolicy: IfNotPresent` then picks+up. Everything else stays on the release digest, and the run ends with an+explicit `SHADOWED:` list of what is local and what is not. The next+`make minikube-setup` re-pulls and discards the shadow set.++Two changes it cannot cover in that mode, both of which stop the gate instead of+passing it: a changed path that maps to no image at all, and a cluster whose+release images name no commit this clone has (so the changed set is unknowable).+Both print the remedy; `make minikube-setup-local` always works.+For target-aware promptBridge or provider-free `clientNotifications` upgrades,follow the fail-closed migration and rollout order in[Plugin Workload SDK upgrade and policy migration](plugin-workload-sdk-upgrade.md)@@ -792,15 +805,28 @@ make minikube-setup ARGS="--skip-build" # Re-applies kustomize overlay with co### ImagePullBackOff on pods-Images are tagged `:test` locally but the cluster can't find them. Run:+The cluster cannot find an image it was told to run. The fix depends on how the+cluster acquired its images, which is recorded in+`deploy/minikube/.image-manifest.json` (`imageSource`), not by whatever+`IMAGE_SOURCE` your shell defaults to:```bash-make minikube-pre-gate-sync GATE=image-refresh ARGS="--force-cluster-sync"-# or:-make minikube-build-images # Rebuilds all images in minikube's Docker daemon-make minikube-restart-all # Restart deployments to pick up images+make minikube-verify-images # Reports the mode and every ref the cluster is missing```+```bash+# imageSource=ghcr: re-pull the release set at the recorded tag.+make minikube-pull-images+make minikube-restart-all++# imageSource=local: rebuild in minikube's Docker daemon.+make minikube-build-images+make minikube-restart-all+```++`make minikube-pre-gate-sync GATE=image-refresh ARGS="--force-cluster-sync"`+does the right one for you, then re-applies the manifests.+### Postgres CrashLoopBackOff (WAL corruption)Common after cold starts. The setup script detects and auto-fixes this, but you can also run manually:diff --git a/scripts/minikube/build-images.sh b/scripts/minikube/build-images.shindex 927cd25df..e75b78869 100755--- a/scripts/minikube/build-images.sh+++ b/scripts/minikube/build-images.sh@@ -121,20 +121,20 @@ MANIFEST_FILE="${PROJECT_DIR}/deploy/minikube/.image-manifest.json"# The mode the cluster's images were actually acquired in. Prints nothing when# the manifest is absent, unparseable, or records anything other than# ghcr|local -- callers then fall back to the IMAGE_SOURCE env var.+#+# ONE reader, shared with scripts/minikube/pre-gate-sync.sh through+# scripts/minikube/image-mode.sh. A second copy here would let the verify path+# and the pre-gate disagree about what the cluster is running, which is the+# exact failure this key exists to prevent.+# shellcheck source=scripts/minikube/image-mode.sh+source "${SCRIPT_DIR}/image-mode.sh"+recorded_image_source() {- [ -f "$MANIFEST_FILE" ] || return 0- node -e '- const fs = require("node:fs")- let parsed- try {- parsed = JSON.parse(fs.readFileSync(process.argv[1], "utf8"))- } catch {- process.exit(0)- }- if (parsed.imageSource === "ghcr" || parsed.imageSource === "local") {- process.stdout.write(parsed.imageSource)- }- ' "$MANIFEST_FILE"+ image_mode_recorded_source "$PROJECT_DIR"+}++recorded_image_tag() {+ image_mode_manifest_field "$PROJECT_DIR" 2}# The two E2E-only fixtures are built by `make minikube-setup-e2e` alone, which@@ -814,18 +814,36 @@ echo -e "\n${BOLD}=== Generating Image Manifest ===${NC}"# fixtures with --only AFTER the ghcr pull, and `make minikube-setup` builds# doc-generator-mcp with --only BEFORE it. Carry the recorded value forward# instead, and fall back to the env var only when nothing is recorded yet.+#+# imageTag rides along for exactly the same reason. A pre-gate shadow build is+# an --only run, so dropping the tag here would make the next pre-gate fall back+# to the committed pin and declare a `MINIKUBE_IMAGE_TAG=latest` cluster out of+# sync on every run. A full build has no ghcr coordinate at all, so it clears+# the key rather than leaving a stale one behind.MANIFEST_IMAGE_SOURCE="local"+MANIFEST_IMAGE_TAG=""if [ -n "$ONLY_SVC" ]; thenMANIFEST_IMAGE_SOURCE="$(recorded_image_source)"if [ -z "$MANIFEST_IMAGE_SOURCE" ]; thenMANIFEST_IMAGE_SOURCE="$IMAGE_SOURCE"fi+ MANIFEST_IMAGE_TAG="$(recorded_image_tag)"+ if [ -z "$MANIFEST_IMAGE_TAG" ] && [ "$MANIFEST_IMAGE_SOURCE" = ghcr ]; then+ # Charset-checked before it is interpolated into JSON: an unusable value+ # would make the whole manifest unparseable, which every reader here+ # correctly treats as "nothing recorded" -- silently losing the mode too.+ case "${MINIKUBE_IMAGE_TAG:-}" in+ "" | *[!A-Za-z0-9._-]*) MANIFEST_IMAGE_TAG="" ;;+ *) MANIFEST_IMAGE_TAG="${MINIKUBE_IMAGE_TAG}" ;;+ esac+ fifi{echo "{"echo " \"generated\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\","echo " \"profile\": \"${PROFILE}\","echo " \"imageSource\": \"${MANIFEST_IMAGE_SOURCE}\","+ echo " \"imageTag\": \"${MANIFEST_IMAGE_TAG}\","echo " \"images\": {"count=0total=${#ALL_IMAGES[@]}diff --git a/scripts/minikube/image-mode.sh b/scripts/minikube/image-mode.shnew file mode 100755index 000000000..28bd1aadd--- /dev/null+++ b/scripts/minikube/image-mode.sh@@ -0,0 +1,269 @@+#!/usr/bin/env bash+# ======================================================================+# Which images this cluster runs, and therefore which overlay renders it+# ======================================================================+#+# ONE resolver, sourced as a library and callable as a CLI. Every consumer that+# has to answer "is this cluster running ghcr release images or locally built+# clerum/* ones, and at which tag" asks here.+#+# THE ANSWER IS NOT THE IMAGE_SOURCE ENVIRONMENT VARIABLE. That describes what+# the caller's shell would have done; what a cluster actually runs is decided by+# whichever writer last acquired images, and both writers record it in+# deploy/minikube/.image-manifest.json (scripts/minikube/pull-images.sh writes+# "ghcr", scripts/minikube/build-images.sh writes "local"). Trusting the env+# default instead is what made `make minikube-verify-images` report "25 of 28+# images missing" on a healthy locally built cluster; the same mistake in+# scripts/minikube/pre-gate-sync.sh makes a gate pass against code that was+# never deployed, which is strictly worse because nothing reports it.+#+# The env var remains the fallback for a cluster nothing has built or pulled+# into yet, and a value that is neither ghcr nor local is always an error --+# guessing a mode silently picks a cluster shape.+#+# Usage (library):+# source scripts/minikube/image-mode.sh+# mode="$(image_mode_source "$PROJECT_DIR")" || exit 1+# tag="$(image_mode_tag "$PROJECT_DIR")" || exit 1 # empty in local mode+# dir="$(image_mode_render_dir "$PROJECT_DIR")" || exit 1+#+# Usage (CLI, for Makefile recipes):+# scripts/minikube/image-mode.sh --render-dir | --image-source | --image-tag+# | --images-generated-at+#+# This file deliberately sets no shell options: it is sourced into scripts that+# run under `set -euo pipefail` and must not change their contract.+# ======================================================================++IMAGE_MODE_SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+IMAGE_MODE_PROJECT_DIR="$(cd "${IMAGE_MODE_SCRIPT_DIR}/../.." && pwd)"++# Prints `imageSource<TAB>imageTag<TAB>generated`, with any field the manifest+# does not carry (or carries in an unusable shape) left empty.+#+# A missing manifest is a legitimate "nothing recorded yet" and prints nothing.+# A node that cannot run is NOT: that is a broken toolchain, and reporting it as+# "nothing recorded" would silently hand the caller the env-var default.+image_mode_read_manifest() {+ local project_dir="${1:-$IMAGE_MODE_PROJECT_DIR}"+ local manifest out rc+ manifest="${project_dir}/deploy/minikube/.image-manifest.json"+ if [ ! -f "$manifest" ]; then+ return 0+ fi+ out="$(node -e '+ const fs = require("node:fs")+ let parsed+ try {+ parsed = JSON.parse(fs.readFileSync(process.argv[1], "utf8"))+ } catch {+ // A truncated or pre-dating manifest records nothing; the caller falls+ // back to the environment rather than aborting a healthy cluster.+ process.stdout.write("\t\t")+ process.exit(0)+ }+ const mode = parsed.imageSource === "ghcr" || parsed.imageSource === "local" ? parsed.imageSource : ""+ const tag =+ typeof parsed.imageTag === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(parsed.imageTag)+ ? parsed.imageTag+ : ""+ const generated =+ typeof parsed.generated === "string" && /^[A-Za-z0-9:._-]*$/.test(parsed.generated)+ ? parsed.generated+ : ""+ process.stdout.write(`${mode}\t${tag}\t${generated}`)+ ' "$manifest" 2>&1)"+ rc=$?+ if [ "$rc" -ne 0 ]; then+ printf 'image-mode: could not read %s: %s\n' "$manifest" "$out" >&2+ return 1+ fi+ printf '%s' "$out"+}++image_mode_manifest_field() {+ local project_dir="$1" field="$2" fields+ if ! fields="$(image_mode_read_manifest "$project_dir")"; then+ return 1+ fi+ printf '%s' "$fields" | cut -f"$field"+}++# ghcr|local from the manifest, else the environment. Prints nothing and fails+# when IMAGE_SOURCE names a mode that does not exist -- validated even when the+# manifest wins, because a typo in the environment is always a mistake worth+# surfacing rather than a value to ignore.+image_mode_source() {+ local project_dir="${1:-$IMAGE_MODE_PROJECT_DIR}" recorded env_mode+ env_mode="${IMAGE_SOURCE:-ghcr}"+ case "$env_mode" in+ ghcr | local) ;;+ *)+ printf "image-mode: unknown IMAGE_SOURCE '%s' (expected: ghcr | local)\n" "$env_mode" >&2+ return 1+ ;;+ esac+ if ! recorded="$(image_mode_manifest_field "$project_dir" 1)"; then+ return 1+ fi+ if [ -n "$recorded" ]; then+ printf '%s' "$recorded"+ return 0+ fi+ printf '%s' "$env_mode"+}++# The committed release pointer. The component is the single source of truth;+# MINIKUBE_IMAGE_TAG is a render-time lever applied to one run, never a second+# writer of the coordinate.+image_mode_pinned_tag() {+ local project_dir="${1:-$IMAGE_MODE_PROJECT_DIR}" component tags+ component="${project_dir}/deploy/components/ghcr-images/kustomization.yaml"+ if [ ! -f "$component" ]; then+ printf 'image-mode: ghcr component not found at %s\n' "$component" >&2+ return 1+ fi+ tags="$(sed -n 's/^[[:space:]]*newTag:[[:space:]]*\([^[:space:]]*\)[[:space:]]*$/\1/p' "$component" | sort -u)"+ if [ -z "$tags" ]; then+ printf 'image-mode: no newTag: line in %s\n' "$component" >&2+ return 1+ fi+ if [ "$(printf '%s\n' "$tags" | wc -l | tr -d ' ')" != "1" ]; then+ printf 'image-mode: mixed newTag values in %s: %s\n' "$component" "$(printf '%s ' $tags)" >&2+ return 1+ fi+ printf '%s' "$tags"+}++# The ghcr tag this cluster runs: the explicit override, else what the last+# acquisition recorded, else the committed pin. Empty in local mode, where there+# is no ghcr coordinate at all.+image_mode_tag() {+ local project_dir="${1:-$IMAGE_MODE_PROJECT_DIR}" mode recorded tag+ if ! mode="$(image_mode_source "$project_dir")"; then+ return 1+ fi+ if [ "$mode" != ghcr ]; then+ return 0+ fi+ if [ -n "${MINIKUBE_IMAGE_TAG:-}" ]; then+ tag="$MINIKUBE_IMAGE_TAG"+ else+ if ! recorded="$(image_mode_manifest_field "$project_dir" 2)"; then+ return 1+ fi+ if [ -n "$recorded" ]; then+ tag="$recorded"+ elif ! tag="$(image_mode_pinned_tag "$project_dir")"; then+ return 1+ fi+ fi+ # The tag is interpolated into image refs and into a sed replacement, so its+ # charset is checked once, here, rather than at each of those sites.+ case "$tag" in+ *[!A-Za-z0-9._-]* | "")+ printf "image-mode: '%s' is not a usable image tag\n" "$tag" >&2+ return 1+ ;;+ esac+ printf '%s' "$tag"+}++# When the last image acquisition happened. A `make minikube-setup` between two+# pre-gates replaces every image and discards any shadow build, so a marker+# stamped before it describes a cluster that no longer exists.+image_mode_images_generated_at() {+ image_mode_manifest_field "${1:-$IMAGE_MODE_PROJECT_DIR}" 3+}++# A copy of deploy/ whose component carries an overridden tag.+#+# A stdout filter cannot do this: the overlay is rendered from a DIRECTORY by+# `kubectl kustomize` and by deploy/scripts/run-control-api-db-migration.sh,+# which takes --overlay and extracts the control-api image from the render.+# Rewriting the committed component in place would make an operator lever a+# second writer of the release coordinate. So the tree moves, exactly as+# scripts/minikube/full-setup.sh does it, and the path is derived from the+# project dir and the tag so repeated runs reuse one location instead of+# leaking a new mktemp -d every time.+image_mode_override_render_dir() {+ local project_dir="$1" tag="$2" key root component rewritten+ key="$(printf '%s' "$project_dir" | shasum | awk '{print $1}')"+ root="${TMPDIR:-/tmp}/clerum-image-tag-override/${key}-${tag}"+ rm -rf "$root"+ mkdir -p "$root"+ if ! cp -R "${project_dir}/deploy" "${root}/deploy"; then+ printf 'image-mode: could not copy %s/deploy for the tag override\n' "$project_dir" >&2+ return 1+ fi+ component="${root}/deploy/components/ghcr-images/kustomization.yaml"+ if [ ! -f "$component" ]; then+ printf 'image-mode: ghcr component missing from the deploy copy at %s\n' "$component" >&2+ return 1+ fi+ # -i.bak plus rm keeps this portable across BSD and GNU sed; `sed -i ''` is a+ # BSD-only spelling GNU sed rejects.+ sed -i.bak "s|^\([[:space:]]*newTag:[[:space:]]*\).*$|\1${tag}|" "$component"+ rm -f "${component}.bak"+ rewritten="$(sed -n 's/^[[:space:]]*newTag:[[:space:]]*\([^[:space:]]*\)[[:space:]]*$/\1/p' "$component" | sort -u)"+ if [ "$rewritten" != "$tag" ]; then+ printf "image-mode: tag override did not apply cleanly: copy carries '%s', expected '%s'\n" \+ "$rewritten" "$tag" >&2+ return 1+ fi+ printf '%s' "${root}/deploy/overlays/minikube-ghcr"+}++# The overlay directory that renders THIS cluster. Callers that render the+# wrong one apply manifests referencing images the cluster has never held:+# the local overlay on a ghcr cluster names clerum/*:test tags nothing built+# there, and the pinned ghcr overlay on an overridden cluster names a release+# nobody pulled.+image_mode_render_dir() {+ local project_dir="${1:-$IMAGE_MODE_PROJECT_DIR}" mode tag pinned+ if ! mode="$(image_mode_source "$project_dir")"; then+ return 1+ fi+ if [ "$mode" = local ]; then+ printf '%s' "${project_dir}/deploy/overlays/minikube"+ return 0+ fi+ if ! tag="$(image_mode_tag "$project_dir")"; then+ return 1+ fi+ if ! pinned="$(image_mode_pinned_tag "$project_dir")"; then+ return 1+ fi+ if [ "$tag" = "$pinned" ]; then+ printf '%s' "${project_dir}/deploy/overlays/minikube-ghcr"+ return 0+ fi+ image_mode_override_render_dir "$project_dir" "$tag"+}++# Back-compat name for build-images.sh, whose --verify-only path has always+# spelled it this way.+image_mode_recorded_source() {+ image_mode_manifest_field "${1:-$IMAGE_MODE_PROJECT_DIR}" 1+}++if [ "${BASH_SOURCE[0]}" = "${0}" ]; then+ image_mode_cli() {+ case "${1:-}" in+ --image-source) image_mode_source ;;+ --image-tag) image_mode_tag ;;+ --render-dir) image_mode_render_dir ;;+ --images-generated-at) image_mode_images_generated_at ;;+ *)+ printf 'usage: image-mode.sh --image-source|--image-tag|--render-dir|--images-generated-at\n' >&2+ return 2+ ;;+ esac+ }+ IMAGE_MODE_CLI_OUT="$(image_mode_cli "$@")"+ IMAGE_MODE_CLI_RC=$?+ if [ "$IMAGE_MODE_CLI_RC" -eq 0 ]; then+ printf '%s\n' "$IMAGE_MODE_CLI_OUT"+ fi+ exit "$IMAGE_MODE_CLI_RC"+fidiff --git a/scripts/minikube/pre-gate-incremental.sh b/scripts/minikube/pre-gate-incremental.shindex 79aaf6c5d..ea0e5d49b 100755--- a/scripts/minikube/pre-gate-incremental.sh+++ b/scripts/minikube/pre-gate-incremental.sh@@ -1,12 +1,30 @@#!/usr/bin/env bash# Incremental image planning for pre-gate-sync.sh. The caller supplies-# PROJECT_DIR, PROFILE, KC, FORCE_CLUSTER_SYNC, log(), and rollout_if_present().+# PROJECT_DIR, PROFILE, KC, FORCE_CLUSTER_SYNC, IMAGE_SOURCE, IMAGE_TAG,+# IMAGES_GENERATED_AT, log(), and rollout_if_present().+#+# IN GHCR MODE EVERY POD RUNS A RELEASE IMAGE. Building clerum/<svc>:test here+# would produce an image nothing references: the pod restarts onto the same+# release digest and the gate passes against code that was never deployed. So a+# ghcr pre-gate SHADOW-BUILDS -- it builds locally and then tags that build with+# the exact ghcr ref the Deployment already carries, which IfNotPresent picks up+# with no manifest edit, leaving every other image on its release digest.INCREMENTAL_TARGETS=()INCREMENTAL_FULL_IMAGE_BUILD=falseINCREMENTAL_FULL_DEPLOYMENT=falseINCREMENTAL_CRDS_CHANGED=false+# Why a full image build was demanded. In ghcr mode "build everything" is not a+# recovery (it reinstates the 20-minute build and leaves the cluster holding+# clerum/* images the ghcr overlay never references), so the reason decides+# between re-pulling the release set and refusing to gate at all.+INCREMENTAL_FULL_IMAGE_BUILD_REASON=""+INCREMENTAL_UNMAPPED=()+# Discard the current image set and re-pull the release tag before shadowing.+INCREMENTAL_REPULL_ALL=false+INCREMENTAL_SHADOWED=()+INCREMENTAL_DOCKER_ENV_APPLIED=falseincremental_add_target() {local selector="$1" namespace="$2" deployment="$3" target@@ -19,9 +37,88 @@ incremental_add_target() {INCREMENTAL_TARGETS+=("${target}")}+# The commit the cluster's images were last synced to, or nothing.+#+# In ghcr mode the marker is only a usable baseline while the image set it was+# stamped against is still in place. `make minikube-setup` re-pulls every+# release image, discarding any shadow build, and does not touch this marker --+# so a marker whose acquisition stamp predates the current one describes a+# cluster that no longer exists, and trusting its gitHead would compute an empty+# delta and gate on release code. Local mode has no such hazard: a full local+# build puts every image at the tree state the marker names.incremental_marker_git_head() {- ${KC} get configmap "${CLUSTER_SYNC_STATE_CONFIGMAP}" -n control-plane \- -o jsonpath='{.data.gitHead}' 2>/dev/null || true+ local git_head marker_generated+ git_head="$(${KC} get configmap "${CLUSTER_SYNC_STATE_CONFIGMAP}" -n control-plane \+ -o jsonpath='{.data.gitHead}' 2>/dev/null || true)"+ if [[ -z "${git_head}" ]]; then+ return 0+ fi+ if [[ "${IMAGE_SOURCE}" == "ghcr" ]]; then+ marker_generated="$(${KC} get configmap "${CLUSTER_SYNC_STATE_CONFIGMAP}" -n control-plane \+ -o jsonpath='{.data.imagesGeneratedAt}' 2>/dev/null || true)"+ if [[ "${marker_generated}" != "${IMAGES_GENERATED_AT:-}" ]]; then+ return 0+ fi+ fi+ printf '%s' "${git_head}"+}++# Point the Docker CLI at minikube's daemon, once, so a retag lands where the+# kubelet looks. build-images.sh does this in its own process, which does not+# propagate back to this one.+incremental_use_minikube_docker() {+ local env_script+ if [[ "${INCREMENTAL_DOCKER_ENV_APPLIED}" == "true" ]]; then+ return 0+ fi+ if [[ "${MINIKUBE_MULTI_NODE:-false}" == "true" ]]; then+ # Multi-node cannot use docker-env: images are built/pulled in the host+ # daemon and placed on every node with `minikube image load`.+ INCREMENTAL_DOCKER_ENV_APPLIED=true+ return 0+ fi+ if ! env_script="$(minikube -p "${PROFILE}" docker-env)"; then+ # >&2 because this runs inside a command substitution on the baseline+ # path, where anything on stdout would be captured AS the baseline.+ log "ERROR: could not point Docker at minikube's daemon; a shadow build would land in the wrong daemon" >&2+ exit 1+ fi+ eval "${env_script}"+ unset DOCKER_API_VERSION 2>/dev/null || true+ INCREMENTAL_DOCKER_ENV_APPLIED=true+}++# The commit the RUNNING release images were built from.+#+# build-publish.yml stamps every published image with+# org.opencontainers.image.revision, which is the only baseline that works on+# the `latest` bootstrap tag -- `latest` resolves to no git ref at all. The tag+# is tried as a git ref second, for a clone whose daemon no longer holds the+# image. Nothing else is guessed: without a baseline the changed image set is+# unknowable, and the caller must refuse to gate rather than shadow nothing.+incremental_release_baseline_commit() {+ local probe ref revision rc+ incremental_use_minikube_docker+ for probe in control-api workflow-recipes external-rest-api; do+ ref="ghcr.io/evenfire-ai/${probe}:${IMAGE_TAG}"+ revision="$(docker inspect --format='{{index .Config.Labels "org.opencontainers.image.revision"}}' "${ref}" 2>&1)"+ rc=$?+ if [[ "${rc}" -ne 0 ]]; then+ continue+ fi+ revision="$(printf '%s' "${revision}" | tr -d '[:space:]')"+ if [[ "${revision}" =~ ^[0-9a-f]{40}$ ]] &&+ git -C "${PROJECT_DIR}" cat-file -e "${revision}^{commit}" 2>/dev/null; then+ printf '%s' "${revision}"+ return 0+ fi+ done+ revision="$(git -C "${PROJECT_DIR}" rev-parse -q --verify "${IMAGE_TAG}^{commit}" 2>/dev/null || true)"+ if [[ "${revision}" =~ ^[0-9a-f]{40}$ ]]; then+ printf '%s' "${revision}"+ return 0+ fi+ return 0}incremental_is_nonruntime_path() {@@ -74,27 +171,61 @@ incremental_classify_path() {;;*)# An unmapped runtime path must fail closed into the established full- # build rather than risking a stale image in a successful gate.+ # build rather than risking a stale image in a successful gate. In ghcr+ # mode there is no image to shadow-build for it at all, so the path is+ # recorded and named in the refusal instead of silently skipped.INCREMENTAL_FULL_IMAGE_BUILD=true+ INCREMENTAL_FULL_IMAGE_BUILD_REASON="unmapped"+ INCREMENTAL_UNMAPPED+=("${path}");;esac}incremental_plan() {- local marker_git_head path+ local marker_git_head path baselineif [[ "${FORCE_CLUSTER_SYNC}" == "true" ]]; then- INCREMENTAL_FULL_IMAGE_BUILD=true- log "Forced cluster sync requires the established full image build"- return 0+ if [[ "${IMAGE_SOURCE}" == "ghcr" ]]; then+ # A forced sync in ghcr mode means "discard what the cluster holds and+ # start from the release set again", not "build 28 images". The delta is+ # still derived below, so the changed images are shadowed back on top of+ # the freshly pulled release images.+ INCREMENTAL_REPULL_ALL=true+ INCREMENTAL_FULL_DEPLOYMENT=true+ log "Forced cluster sync in ghcr mode: re-pulling the release set, then shadowing the changed images"+ else+ INCREMENTAL_FULL_IMAGE_BUILD=true+ INCREMENTAL_FULL_IMAGE_BUILD_REASON="forced"+ log "Forced cluster sync requires the established full image build"+ return 0+ fifimarker_git_head="$(incremental_marker_git_head)"if [[ ! "${marker_git_head}" =~ ^[0-9a-f]{40}$ ]] || \! git -C "${PROJECT_DIR}" cat-file -e "${marker_git_head}^{commit}" 2>/dev/null; then- INCREMENTAL_FULL_IMAGE_BUILD=true- log "No usable cluster git marker; using the established full image build"- return 0+ if [[ "${IMAGE_SOURCE}" != "ghcr" ]]; then+ INCREMENTAL_FULL_IMAGE_BUILD=true+ INCREMENTAL_FULL_IMAGE_BUILD_REASON="no-marker"+ log "No usable cluster git marker; using the established full image build"+ return 0+ fi+ # A ghcr cluster has a second baseline the local path does not: the commit+ # its release images were built from. Without it the changed set cannot be+ # derived and no amount of building would make the cluster match the tree.+ baseline="$(incremental_release_baseline_commit)"+ # Not `-z`: anything that is not a commit id (including a diagnostic that+ # leaked onto stdout) must take the fail-closed branch, never become a+ # git revision this plan then diffs against.+ if [[ ! "${baseline}" =~ ^[0-9a-f]{40}$ ]]; then+ INCREMENTAL_FULL_IMAGE_BUILD=true+ INCREMENTAL_FULL_IMAGE_BUILD_REASON="no-baseline"+ log "No usable cluster marker, and the release images at ${IMAGE_TAG} name no commit this clone has"+ return 0+ fi+ marker_git_head="${baseline}"+ INCREMENTAL_REPULL_ALL=true+ log "No usable cluster marker; deriving the shadow set from the release images' commit ${baseline:0:12}"fiwhile IFS= read -r path; do@@ -116,9 +247,140 @@ incremental_has_target() {return 1}+# Every image a changed selector maps to, as `name<TAB>localRef<TAB>ghcrRef`,+# with `-` for an image ghcr cannot supply.+#+# A SELECTOR IS NOT AN IMAGE NAME. incremental_classify_path emits selectors+# like `workflow`, and build-images.sh's --only does SUBSTRING matching, so+# --only=workflow builds workflow-recipes, workflow-coordinator,+# workflow-snippet-runner and workflow-approval-request-reader. Resolving a+# selector to one name would shadow one of them and leave the rest on their+# release digests while the report claimed the whole selector was covered, so+# this matches exactly the way --only does.+incremental_shadow_refs() {+ local selector="$1" out rc+ out="$(node -e '+ import("'"${PROJECT_DIR}"'/scripts/release/images-manifest.mjs").then(m => {+ const selector = process.argv[1]+ const tag = process.argv[2]+ const publishable = new Set(m.pullInGhcrMode().map(i => i.name))+ for (const image of m.IMAGES) {+ const localRef = m.localRef(image)+ // The same substring test build-images.sh applies to --only, over both+ // the local ref and the logical name, so the two can never disagree.+ if (!localRef.includes(selector) && !image.name.includes(selector)) continue+ const ghcrRef = publishable.has(image.name)+ ? `ghcr.io/evenfire-ai/${image.name}:${tag}`+ : "-"+ process.stdout.write(`${image.name}\t${localRef}\t${ghcrRef}\n`)+ }+ }).catch(err => {+ process.stderr.write(`images-manifest read failed: ${err.message}\n`)+ process.exit(1)+ })' "${selector}" "${IMAGE_TAG}" 2>&1)"+ rc=$?+ if [[ "${rc}" -ne 0 ]]; then+ printf '%s\n' "${out}" >&2+ return 1+ fi+ printf '%s' "${out}"+}++# Tag the freshly built local image with the exact ghcr ref the Deployment+# already references. That, and only that, is what makes IfNotPresent run the+# local build with no manifest edit.+incremental_shadow_selector() {+ local selector="$1" pairs name local_ref shadow_ref shadowed=0+ if ! pairs="$(incremental_shadow_refs "${selector}")"; then+ log "ERROR: could not resolve the shadow set for selector ${selector}; the gate would test undeployed code"+ exit 1+ fi+ if [[ -z "${pairs}" ]]; then+ # Not "nothing to do": a selector that matches no image at all means+ # incremental_classify_path emitted something build-images.sh cannot build.+ log "ERROR: image selector ${selector} matches no image in deploy/images.json"+ exit 1+ fi+ while IFS="$(printf '\t')" read -r name local_ref shadow_ref; do+ [[ -n "${name}" ]] || continue+ if [[ "${shadow_ref}" == "-" ]]; then+ # published:false images (the two E2E fixtures, doc-generator-mcp) run+ # under their clerum/* ref in BOTH modes, so the local build is already+ # the running image and there is nothing to shadow.+ log " ${local_ref} has no published counterpart; the local build is what runs"+ continue+ fi+ if ! docker tag "${local_ref}" "${shadow_ref}"; then+ log "ERROR: could not shadow ${shadow_ref} with ${local_ref}; the gate would test undeployed code"+ exit 1+ fi+ if [[ "${MINIKUBE_MULTI_NODE:-false}" == "true" ]]; then+ minikube -p "${PROFILE}" image load "${shadow_ref}" >/dev/null+ fi+ INCREMENTAL_SHADOWED+=("${shadow_ref} <- ${local_ref}")+ shadowed=$((shadowed + 1))+ done <<< "${pairs}"+ log " shadowed ${shadowed} image(s) for selector ${selector}"+}++# Nobody can act on a shadow they cannot see. This is the difference between+# "the gate is green" and "the gate is green about these two images".+incremental_shadow_summary() {+ if [[ "${IMAGE_SOURCE}" != "ghcr" ]]; then+ return 0+ fi+ echo ""+ if (( ${#INCREMENTAL_SHADOWED[@]} == 0 )); then+ echo "SHADOWED: none - every image is the release build (${IMAGE_TAG})"+ else+ echo "SHADOWED (local build over release tag ${IMAGE_TAG}):"+ printf ' %s\n' "${INCREMENTAL_SHADOWED[@]}"+ echo " Everything else is still release ${IMAGE_TAG}."+ echo " The shadow set is discarded by the next 'make minikube-setup'."+ fi+ echo ""+}++# The one state a ghcr pre-gate cannot repair. Passing here would gate against+# code that is not deployed, and nothing downstream would report it.+incremental_abort_unshadowable() {+ local path+ log "ERROR: this pre-gate cannot make the cluster match your working tree."+ log " mode: ghcr - every pod runs a RELEASE image (${IMAGE_TAG})"+ case "${INCREMENTAL_FULL_IMAGE_BUILD_REASON}" in+ unmapped)+ log " reason: these changed path(s) map to no image, so there is nothing to shadow-build:"+ if (( ${#INCREMENTAL_UNMAPPED[@]} > 0 )); then+ for path in "${INCREMENTAL_UNMAPPED[@]}"; do+ log " ${path}"+ done+ fi+ log " fix: map the path in scripts/minikube/pre-gate-incremental.sh, or"+ ;;+ no-baseline)+ log " reason: no shadow baseline. The cluster marker is unusable and the release"+ log " images at '${IMAGE_TAG}' name no org.opencontainers.image.revision"+ log " commit this clone has, so the changed image set is unknowable."+ log " fix: fetch the release commit (git fetch --tags origin), or"+ ;;+ *)+ log " reason: ${INCREMENTAL_FULL_IMAGE_BUILD_REASON:-unknown}"+ log " fix:"+ ;;+ esac+ log " make minikube-setup-local # rebuild the cluster from source, then re-run this gate"+ log "Refusing to continue: the gate would pass against code that is not deployed."+ exit 1+}+incremental_build_images() {local target selector+ if [[ "${IMAGE_SOURCE}" == "ghcr" ]]; then+ incremental_build_images_ghcr+ return 0+ fi+if [[ "${INCREMENTAL_FULL_IMAGE_BUILD}" == "true" ]]; thenlog "Building all images because the change cannot be safely targeted"(@@ -142,6 +404,44 @@ incremental_build_images() {done}+incremental_build_images_ghcr() {+ local target selector++ if [[ "${INCREMENTAL_FULL_IMAGE_BUILD}" == "true" ]]; then+ incremental_abort_unshadowable+ fi++ if [[ "${INCREMENTAL_REPULL_ALL}" == "true" ]]; then+ # Discard whatever the daemon holds (including shadows from an older tree)+ # and restore the release set, then shadow the changed images on top.+ log "Re-pulling the release image set (${IMAGE_TAG}) before shadowing the changed images"+ (+ cd "${PROJECT_DIR}"+ make minikube-pull-images+ make minikube-verify-images+ )+ fi++ if (( ${#INCREMENTAL_TARGETS[@]} == 0 )); then+ log "No runtime image changes detected"+ incremental_shadow_summary+ return 0+ fi++ incremental_use_minikube_docker+ log "cluster imageSource=ghcr (${IMAGE_TAG}); changed: $(incremental_target_summary)"++ for target in "${INCREMENTAL_TARGETS[@]}"; do+ selector="${target%%|*}"+ log "Building only image selector ${selector}"+ MINIKUBE_PROFILE="${PROFILE}" \+ bash "${PROJECT_DIR}/scripts/minikube/build-images.sh" "--only=${selector}"+ incremental_shadow_selector "${selector}"+ done++ incremental_shadow_summary+}+incremental_restart_targets() {local target selector remainder namespace deployment deployment_keylocal restarted="|"diff --git a/scripts/minikube/pre-gate-sync.sh b/scripts/minikube/pre-gate-sync.shindex ea114de5e..f95ba0601 100755--- a/scripts/minikube/pre-gate-sync.sh+++ b/scripts/minikube/pre-gate-sync.sh@@ -47,6 +47,37 @@ log() {printf '[pre-gate-sync] %s\n' "$*"}+# ---- Which images this cluster runs ---------------------------------------+# THIS HAS TO COME FROM THE CLUSTER, NOT FROM THIS SHELL. A cluster set up with+# ghcr release images and pre-gated with IMAGE_SOURCE=local (or the reverse)+# would otherwise look in sync while every running pod referenced images this+# sync never touched, and the gate would pass against code that is not+# deployed. scripts/minikube/image-mode.sh is the one resolver; it reads the+# mode whichever writer last acquired images recorded, and falls back to the+# environment only for a cluster nothing has built or pulled into yet.+# shellcheck source=scripts/minikube/image-mode.sh+source "${SCRIPT_DIR}/image-mode.sh"++if ! IMAGE_SOURCE="$(image_mode_source "${PROJECT_DIR}")"; then+ exit 1+fi+if ! IMAGE_TAG="$(image_mode_tag "${PROJECT_DIR}")"; then+ exit 1+fi+if ! PRE_GATE_RENDER_DIR="$(image_mode_render_dir "${PROJECT_DIR}")"; then+ exit 1+fi+if ! IMAGES_GENERATED_AT="$(image_mode_images_generated_at "${PROJECT_DIR}")"; then+ exit 1+fi+export IMAGE_SOURCE+if [[ "${IMAGE_SOURCE}" == "ghcr" ]]; then+ # Every `make` sub-invocation below (pull-images, verify-images, deploy-all)+ # must resolve the SAME coordinate this run resolved, including an override+ # the committed pin does not carry.+ export MINIKUBE_IMAGE_TAG="${IMAGE_TAG}"+fi+# shellcheck source=scripts/minikube/pre-gate-runtime.shsource "${SCRIPT_DIR}/pre-gate-runtime.sh"# shellcheck source=scripts/minikube/pre-gate-incremental.sh@@ -184,31 +215,53 @@ cluster_marker_matches() {local expected_cluster_fingerprint="$1"local expected_worktree_id="$2"local expected_git_head actual_cluster_fingerprint actual_worktree_id actual_git_head+ local actual_image_source actual_image_tag actual_images_generated_atexpected_git_head="$(git -C "${PROJECT_DIR}" rev-parse --verify HEAD 2>/dev/null || true)"actual_cluster_fingerprint="$(${KC} get configmap "${CLUSTER_SYNC_STATE_CONFIGMAP}" -n control-plane -o jsonpath='{.data.clusterFingerprint}' 2>/dev/null || true)"actual_worktree_id="$(${KC} get configmap "${CLUSTER_SYNC_STATE_CONFIGMAP}" -n control-plane -o jsonpath='{.data.worktreeId}' 2>/dev/null || true)"actual_git_head="$(${KC} get configmap "${CLUSTER_SYNC_STATE_CONFIGMAP}" -n control-plane -o jsonpath='{.data.gitHead}' 2>/dev/null || true)"+ # The image coordinate is part of "in sync". gitHead cannot tell a ghcr+ # cluster from a local one, nor v0.6.0 from latest, and the acquisition stamp+ # is what catches a `make minikube-setup` between two pre-gates: that re-pulls+ # every release image and discards any shadow build while leaving this marker+ # untouched, so without it no sync would run and the gate would silently test+ # release code.+ actual_image_source="$(${KC} get configmap "${CLUSTER_SYNC_STATE_CONFIGMAP}" -n control-plane -o jsonpath='{.data.imageSource}' 2>/dev/null || true)"+ actual_image_tag="$(${KC} get configmap "${CLUSTER_SYNC_STATE_CONFIGMAP}" -n control-plane -o jsonpath='{.data.imageTag}' 2>/dev/null || true)"+ actual_images_generated_at="$(${KC} get configmap "${CLUSTER_SYNC_STATE_CONFIGMAP}" -n control-plane -o jsonpath='{.data.imagesGeneratedAt}' 2>/dev/null || true)"[[ "${actual_cluster_fingerprint}" == "${expected_cluster_fingerprint}" ]] &&[[ "${actual_worktree_id}" == "${expected_worktree_id}" ]] &&- [[ -n "${expected_git_head}" && "${actual_git_head}" == "${expected_git_head}" ]]+ [[ -n "${expected_git_head}" && "${actual_git_head}" == "${expected_git_head}" ]] &&+ [[ "${actual_image_source}" == "${IMAGE_SOURCE}" ]] &&+ [[ "${actual_image_tag}" == "${IMAGE_TAG}" ]] &&+ [[ "${actual_images_generated_at}" == "${IMAGES_GENERATED_AT}" ]]}persist_cluster_marker() {local cluster_fingerprint="$1"local infra_fingerprint="$2"- local git_head updated_at+ local git_head updated_at images_generated_atgit_head="$(git -C "${PROJECT_DIR}" rev-parse --verify HEAD 2>/dev/null || printf 'unknown')"updated_at="$(date -u +%Y-%m-%dT%H:%M:%SZ)"+ # Re-read rather than reusing the value from startup: this run may have+ # re-pulled or rebuilt images, which rewrites the manifest.+ if ! images_generated_at="$(image_mode_images_generated_at "${PROJECT_DIR}")"; then+ log "ERROR: cannot read the image manifest to stamp the cluster sync marker"+ return 1+ fi${KC} create configmap "${CLUSTER_SYNC_STATE_CONFIGMAP}" -n control-plane \--from-literal=clusterFingerprint="${cluster_fingerprint}" \--from-literal=infraFingerprint="${infra_fingerprint}" \--from-literal=worktreeId="${WORKTREE_ID}" \--from-literal=gitHead="${git_head}" \+ --from-literal=imageSource="${IMAGE_SOURCE}" \+ --from-literal=imageTag="${IMAGE_TAG}" \+ --from-literal=imagesGeneratedAt="${images_generated_at}" \--from-literal=gate="${GATE_NAME}" \--from-literal=updatedAt="${updated_at}" \--dry-run=client \@@ -315,7 +368,23 @@ assert_no_legacy_prompt_bridge_grants() {log "Legacy promptBridge grant inventory is empty"}+# Test seam: everything above resolves configuration and defines functions+# only, with no cluster or network call. `PRE_GATE_SYNC_CONFIG_ONLY=true` stops+# here so scripts/tests/test-minikube-pre-gate-shadow.sh can read the resolved+# image coordinate, and (when it sources this file) exercise the marker+# functions, without a cluster. It must stay immediately before the first+# cluster call.+if [[ "${PRE_GATE_SYNC_CONFIG_ONLY:-false}" == "true" ]]; then+ printf 'imageSource=%s\n' "${IMAGE_SOURCE}"+ printf 'imageTag=%s\n' "${IMAGE_TAG}"+ printf 'renderDir=%s\n' "${PRE_GATE_RENDER_DIR}"+ printf 'imagesGeneratedAt=%s\n' "${IMAGES_GENERATED_AT}"+ # `return` when sourced, `exit` when executed.+ return 0 2>/dev/null || exit 0+fi+log "Evaluating sync requirements for ${GATE_NAME}"+log "Cluster images: ${IMAGE_SOURCE}${IMAGE_TAG:+ (${IMAGE_TAG})}; overlay $(basename "${PRE_GATE_RENDER_DIR}")"preflight_host_lifecycle_probecluster_fingerprint="$(@@ -406,9 +475,16 @@ if [[ "${cluster_changed}" == "true" ]]; thenif incremental_requires_database_reconcile; thenrollout_if_present control-plane control-postgres+ # The migration script EXTRACTS THE CONTROL-API IMAGE from the overlay it+ # renders. Hardcoding the local overlay here yielded clerum/control-api:test+ # on a ghcr cluster -- an image that does not exist there, so the migration+ # Job ImagePullBackOffs; and rendering the pinned ghcr overlay on a cluster+ # running an overridden tag would run a release nobody pulled. Follow the+ # coordinate the cluster actually runs, which is also the ref the shadow+ # build above just retagged.CONTEXT="${PROFILE}" ALLOWED_CONTEXTS="${PROFILE}" \bash "${PROJECT_DIR}/deploy/scripts/run-control-api-db-migration.sh" \- --overlay "${PROJECT_DIR}/deploy/overlays/minikube"+ --overlay "${PRE_GATE_RENDER_DIR}"CONTEXT="${PROFILE}" ALLOWED_CONTEXTS="${PROFILE}" \bash "${PROJECT_DIR}/deploy/scripts/provision-control-api-runtime-roles.sh"# The GFS DSN authentication probe deliberately runs inside control-api sodiff --git a/scripts/tests/test-gfs-deploy-contract.sh b/scripts/tests/test-gfs-deploy-contract.shindex 7660f3041..3b4fa5a58 100755--- a/scripts/tests/test-gfs-deploy-contract.sh+++ b/scripts/tests/test-gfs-deploy-contract.sh@@ -92,7 +92,11 @@ assert_minikube_upgrade_classifier() {"$abort" -lt "$reconcile" && "$reconcile" -lt "$fallback" && "$fallback" -lt "$fresh" ]] \|| fail "$path does not reconcile ready upgrades, abort unready upgrades, and defer only empty bootstraps"}-assert_minikube_upgrade_classifier Makefile '# Upgrade path: adopt/validate writer' 'kustomize deploy/overlays/minikube'+# The block ends where the overlay apply begins. That apply no longer names a+# fixed overlay: it resolves one from the mode the cluster's images were+# acquired in (scripts/minikube/image-mode.sh), so the resolver call is the+# anchor.+assert_minikube_upgrade_classifier Makefile '# Upgrade path: adopt/validate writer' 'image-mode.sh --render-dir'assert_minikube_upgrade_classifier scripts/minikube/full-setup.sh '# Upgrade path: stage the additive reader' 'Applying kustomize overlay'assert_minikube_upgrade_classifier scripts/minikube/pre-gate-sync.sh 'apply-gfs-writer-secret.sh' 'incremental_build_images'full_setup_classifier="$(sed -n '/# Upgrade path: stage the additive reader/,/Applying kustomize overlay/p' scripts/minikube/full-setup.sh)"diff --git a/scripts/tests/test-minikube-pre-gate-shadow.sh b/scripts/tests/test-minikube-pre-gate-shadow.shnew file mode 100755index 000000000..34be12752--- /dev/null+++ b/scripts/tests/test-minikube-pre-gate-shadow.sh@@ -0,0 +1,922 @@+#!/usr/bin/env bash+set -u+FAIL=0++# A ghcr cluster runs RELEASE images. Before this harness existed, the pre-gate+# had no idea: it built clerum/<svc>:test, restarted the Deployment, and the pod+# came back on the SAME release digest, because nothing referenced the image it+# had just built. The gate then passed against code that was never deployed --+# the worst outcome this whole change can produce.+#+# Every case here runs the REAL scripts against PATH stubs for+# docker/minikube/kubectl/make, in a throwaway copy of deploy/ + scripts/ with a+# real git history. Nothing needs a cluster or a network.+#+# The assertions are written to die on INVERTED LOGIC, not on a renamed+# identifier: they observe the docker/make/kubectl calls the scripts actually+# make and the refs those calls carry. Swapping the ghcr and local refs in the+# retag, or wrapping the shadow loop in `if false`, fails them.++REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+GHCR_COMPONENT="$REPO_ROOT/deploy/components/ghcr-images/kustomization.yaml"++pass() { echo "PASS: $1"; }+fail() { echo "FAIL: $1"; FAIL=1; }++PIN_TAG="$(sed -n 's/^[[:space:]]*newTag:[[:space:]]*\([^[:space:]]*\)[[:space:]]*$/\1/p' "$GHCR_COMPONENT" | sort -u)"+if [ -z "$PIN_TAG" ] || [ "$(printf '%s\n' "$PIN_TAG" | wc -l | tr -d ' ')" != "1" ]; then+ echo "FAIL: could not read a single committed pin from $GHCR_COMPONENT (got '$PIN_TAG')"+ exit 1+fi++# Derived from the manifest, deliberately NOT from the code under test.+ghcr_refs_for_selector() {+ local selector="$1" tag="$2"+ node -e '+ import("'"$REPO_ROOT"'/scripts/release/images-manifest.mjs").then(m => {+ for (const i of m.pullInGhcrMode()) {+ if (!i.name.includes(process.argv[1]) && !m.localRef(i).includes(process.argv[1])) continue+ console.log(`ghcr.io/evenfire-ai/${i.name}:${process.argv[2]}`)+ }+ }).catch(e => { console.error(e.message); process.exit(1) })' "$selector" "$tag"+}++local_ref_for_image() {+ node -e '+ import("'"$REPO_ROOT"'/scripts/release/images-manifest.mjs").then(m => {+ const i = m.IMAGES.find(x => x.name === process.argv[1])+ if (!i) { console.error("no such image"); process.exit(1) }+ console.log(m.localRef(i))+ }).catch(e => { console.error(e.message); process.exit(1) })' "$1"+}++make_stubs() {+ local d=$1+ mkdir -p "$d/bin"+ cat > "$d/bin/docker" <<'STUB'+#!/usr/bin/env bash+printf 'docker %s\n' "$*" >>"${TEST_LOG_FILE:?}"+case "${1:-}" in+ inspect)+ # The only inspect the pre-gate makes is the OCI revision-label read that+ # gives it the commit a release image was built from.+ printf '%s\n' "${TEST_IMAGE_REVISION:-}"+ exit 0+ ;;+ tag)+ if [ "${TEST_DOCKER_TAG_FAILS:-0}" = "1" ]; then+ echo "Error response from daemon: simulated retag failure" >&2+ exit 1+ fi+ exit 0+ ;;+esac+exit 0+STUB+ cat > "$d/bin/minikube" <<'STUB'+#!/usr/bin/env bash+printf 'minikube %s\n' "$*" >>"${TEST_LOG_FILE:?}"+case "$*" in+ *docker-env*) echo 'export DOCKER_HOST="tcp://127.0.0.1:2376"'; exit 0 ;;+esac+exit 0+STUB+ cat > "$d/bin/kubectl" <<'STUB'+#!/usr/bin/env bash+printf 'kubectl %s\n' "$*" >>"${TEST_LOG_FILE:?}"+case "$*" in+ *"get nodes"*) echo "minikube Ready control-plane 1d v1.30.0"; exit 0 ;;+ *"get configmap"*jsonpath*)+ key="$(printf '%s' "$*" | sed -n 's/.*{\.data\.\([A-Za-z]*\)}.*/\1/p')"+ file="${TEST_MARKER_DIR:-/nonexistent}/${key}"+ [ -n "$key" ] || exit 1+ [ -f "$file" ] || exit 1+ cat "$file"+ exit 0+ ;;+esac+exit 0+STUB+ cat > "$d/bin/make" <<'STUB'+#!/usr/bin/env bash+printf 'make %s\n' "$*" >>"${TEST_LOG_FILE:?}"+exit 0+STUB+ chmod +x "$d/bin/docker" "$d/bin/minikube" "$d/bin/kubectl" "$d/bin/make"+}++# A throwaway repo carrying the REAL deploy/ and scripts/, with a real git+# history so incremental_plan's diffs work, and a stubbed build-images.sh so a+# "build" is observable without Docker.+prepare_repo() {+ local d=$1+ make_stubs "$d"+ mkdir -p "$d/repo"+ cp -R "$REPO_ROOT/deploy" "$d/repo/deploy"+ cp -R "$REPO_ROOT/scripts" "$d/repo/scripts"+ rm -rf "$d/repo/deploy/minikube"+ cat > "$d/repo/scripts/minikube/build-images.sh" <<'STUB'+#!/usr/bin/env bash+printf 'build-images %s\n' "$*" >>"${TEST_LOG_FILE:?}"+exit 0+STUB+ mkdir -p "$d/repo/control-api/src"+ echo "export const x = 1" > "$d/repo/control-api/src/index.ts"+ (+ cd "$d/repo"+ git init -q .+ git add -A+ git -c user.email=t@t -c user.name=t commit -qm base+ )+}++write_manifest() {+ local d=$1 body=$2+ mkdir -p "$d/repo/deploy/minikube"+ printf '%s' "$body" > "$d/repo/deploy/minikube/.image-manifest.json"+}++repo_head() { git -C "$1/repo" rev-parse HEAD; }++# Loads pre-gate-incremental.sh the way pre-gate-sync.sh does, in a subshell the+# caller controls, and runs $2 with the callers' contract satisfied.+run_incremental() {+ local d=$1 fn=$2+ (+ set +u+ PROJECT_DIR="$d/repo"+ PROFILE="clerum-test"+ KC="kubectl --context=${PROFILE}"+ CLUSTER_SYNC_STATE_CONFIGMAP="clerum-pre-gate-sync-state"+ FORCE_CLUSTER_SYNC="${FORCE_CLUSTER_SYNC:-false}"+ log() { printf '[pre-gate-sync] %s\n' "$*"; }+ rollout_if_present() { :; }+ # shellcheck source=/dev/null+ . "$PROJECT_DIR/scripts/minikube/pre-gate-incremental.sh"+ eval "$fn"+ ) 2>&1+}++# ---------------------------------------------------------------------------+# The shadow build itself+# ---------------------------------------------------------------------------++# The whole trick: build LOCALLY, then tag that build with the exact ghcr ref+# the Deployment already references, so IfNotPresent picks it up with no+# manifest edit. Building clerum/control-api:test alone leaves the pod on the+# release digest.+assert_a_targeted_ghcr_build_is_retagged_onto_the_running_ghcr_ref() {+ local d out rc want_local want_ghcr+ d="$(mktemp -d)"+ prepare_repo "$d"+ want_local="$(local_ref_for_image control-api)"+ want_ghcr="ghcr.io/evenfire-ai/control-api:${PIN_TAG}"+ out="$(+ PATH="$d/bin:$PATH" TEST_LOG_FILE="$d/ops.log" \+ IMAGE_SOURCE=ghcr IMAGE_TAG="$PIN_TAG" \+ INCREMENTAL_TARGETS_INIT="control-api|control-plane|control-api" \+ run_incremental "$d" 'INCREMENTAL_TARGETS=("control-api|control-plane|control-api"); incremental_build_images'+ )"+ rc=$?+ if [ "$rc" -eq 0 ] \+ && grep -Fq "build-images --only=control-api" "$d/ops.log" \+ && grep -Fq "docker tag ${want_local} ${want_ghcr}" "$d/ops.log"; then+ pass "a targeted ghcr build is retagged onto the ref the Deployment runs"+ else+ fail "expected 'docker tag ${want_local} ${want_ghcr}'; rc=$rc log=$(cat "$d/ops.log") out=$out"+ fi+ rm -rf "$d"+}++# A SELECTOR IS NOT AN IMAGE NAME. build-images.sh's --only does SUBSTRING+# matching, so --only=workflow builds four images. Resolving the selector to one+# name would shadow one and leave three on their release digests while the+# report claimed the whole selector was covered.+assert_a_multi_image_selector_shadows_every_image_it_builds() {+ local d out rc ref missing="" count+ d="$(mktemp -d)"+ prepare_repo "$d"+ out="$(+ PATH="$d/bin:$PATH" TEST_LOG_FILE="$d/ops.log" \+ IMAGE_SOURCE=ghcr IMAGE_TAG="$PIN_TAG" \+ run_incremental "$d" 'INCREMENTAL_TARGETS=("workflow|control-plane|workflow-recipes"); incremental_build_images'+ )"+ rc=$?+ count=0+ while IFS= read -r ref; do+ [ -n "$ref" ] || continue+ count=$((count + 1))+ grep -Fq "docker tag " "$d/ops.log" && grep -Fq " ${ref}" "$d/ops.log" || missing+="${ref} "+ done < <(ghcr_refs_for_selector workflow "$PIN_TAG")+ # An image with no published counterpart carries `-` as its ghcr ref; tagging+ # onto that would put a literal `-` image in the daemon.+ if grep -q 'docker tag .* -$' "$d/ops.log"; then+ missing+="(retagged an unpublished image onto '-') "+ fi+ if [ "$rc" -eq 0 ] && [ "$count" -ge 4 ] && [ -z "$missing" ]; then+ pass "a multi-image selector shadows every image build-images.sh --only builds (${count})"+ else+ fail "selector 'workflow' resolved to ${count} image(s), not shadowed: ${missing:-none}; rc=$rc out=$out"+ fi+ rm -rf "$d"+}++# The other direction, so the fix cannot be "always retag": a locally built+# cluster runs clerum/* refs, and inventing a ghcr tag there would put an image+# in the daemon that no pod references and no verify expects.+assert_local_mode_never_retags_onto_a_ghcr_ref() {+ local d out rc+ d="$(mktemp -d)"+ prepare_repo "$d"+ out="$(+ PATH="$d/bin:$PATH" TEST_LOG_FILE="$d/ops.log" \+ IMAGE_SOURCE=local IMAGE_TAG="" \+ run_incremental "$d" 'INCREMENTAL_TARGETS=("control-api|control-plane|control-api"); incremental_build_images'+ )"+ rc=$?+ if [ "$rc" -eq 0 ] \+ && grep -Fq "build-images --only=control-api" "$d/ops.log" \+ && ! grep -q 'docker tag' "$d/ops.log" \+ && ! grep -q 'SHADOWED' <<< "$out"; then+ pass "local mode builds the image and never retags it onto a ghcr ref"+ else+ fail "local mode retagged or reported a shadow; rc=$rc log=$(cat "$d/ops.log") out=$out"+ fi+ rm -rf "$d"+}++# Nobody can act on a shadow they cannot see. The report is the difference+# between "the gate is green" and "the gate is green about these two images".+assert_the_shadow_set_is_reported_with_every_ref() {+ local d out rc want+ d="$(mktemp -d)"+ prepare_repo "$d"+ want="ghcr.io/evenfire-ai/control-api:${PIN_TAG}"+ out="$(+ PATH="$d/bin:$PATH" TEST_LOG_FILE="$d/ops.log" \+ IMAGE_SOURCE=ghcr IMAGE_TAG="$PIN_TAG" \+ run_incremental "$d" 'INCREMENTAL_TARGETS=("control-api|control-plane|control-api"); incremental_build_images'+ )"+ rc=$?+ if [ "$rc" -eq 0 ] && grep -q 'SHADOWED' <<< "$out" && grep -Fq "$want" <<< "$out"; then+ pass "the shadow set is reported explicitly, naming every shadowed ref"+ else+ fail "expected a SHADOWED report naming ${want}; rc=$rc out=$out"+ fi+ rm -rf "$d"+}++# With nothing to shadow the report must still run and must say so, or an+# operator reads silence as "my code is deployed".+assert_an_empty_shadow_set_is_reported_as_release_only() {+ local d out rc+ d="$(mktemp -d)"+ prepare_repo "$d"+ out="$(+ PATH="$d/bin:$PATH" TEST_LOG_FILE="$d/ops.log" \+ IMAGE_SOURCE=ghcr IMAGE_TAG="$PIN_TAG" \+ run_incremental "$d" 'INCREMENTAL_TARGETS=(); incremental_build_images'+ )"+ rc=$?+ if [ "$rc" -eq 0 ] && grep -q 'SHADOWED: none' <<< "$out" && grep -Fq "$PIN_TAG" <<< "$out"; then+ pass "an empty shadow set is reported as 'every image is the release build'"+ else+ fail "expected an explicit empty-shadow report naming ${PIN_TAG}; rc=$rc out=$out"+ fi+ rm -rf "$d"+}++# A retag that fails leaves the pod on the release digest with a freshly built+# local image nothing references -- exactly the silent-wrong-code state. It has+# to stop the gate.+assert_a_failed_retag_fails_the_pre_gate() {+ local d out rc+ d="$(mktemp -d)"+ prepare_repo "$d"+ out="$(+ PATH="$d/bin:$PATH" TEST_LOG_FILE="$d/ops.log" TEST_DOCKER_TAG_FAILS=1 \+ IMAGE_SOURCE=ghcr IMAGE_TAG="$PIN_TAG" \+ run_incremental "$d" 'INCREMENTAL_TARGETS=("control-api|control-plane|control-api"); incremental_build_images'+ )"+ rc=$?+ if [ "$rc" -ne 0 ] && grep -qi 'undeployed\|could not shadow' <<< "$out"; then+ pass "a failed retag stops the pre-gate instead of reporting a build success"+ else+ fail "expected a non-zero exit naming the failed shadow; rc=$rc out=$out"+ fi+ rm -rf "$d"+}++# ---------------------------------------------------------------------------+# What INCREMENTAL_FULL_IMAGE_BUILD means in each mode+# ---------------------------------------------------------------------------++# "Build everything" is the wrong recovery in ghcr mode: it reinstates the+# 20-minute build this change exists to remove and leaves the cluster holding+# clerum/* images the ghcr overlay never references.+assert_a_full_sync_in_ghcr_mode_repulls_instead_of_building_everything() {+ local d out rc+ d="$(mktemp -d)"+ prepare_repo "$d"+ out="$(+ PATH="$d/bin:$PATH" TEST_LOG_FILE="$d/ops.log" \+ IMAGE_SOURCE=ghcr IMAGE_TAG="$PIN_TAG" \+ run_incremental "$d" 'INCREMENTAL_REPULL_ALL=true; INCREMENTAL_TARGETS=("control-api|control-plane|control-api"); incremental_build_images'+ )"+ rc=$?+ if [ "$rc" -eq 0 ] \+ && grep -Fq "make minikube-pull-images" "$d/ops.log" \+ && ! grep -Fq "make minikube-build-images" "$d/ops.log" \+ && grep -Fq "docker tag $(local_ref_for_image control-api) ghcr.io/evenfire-ai/control-api:${PIN_TAG}" "$d/ops.log"; then+ pass "a ghcr full sync re-pulls the release set, then shadows the changed set on top"+ else+ fail "expected a re-pull followed by the shadow build; rc=$rc log=$(cat "$d/ops.log") out=$out"+ fi+ rm -rf "$d"+}++# Local mode is untouched: a full image build still means build everything.+assert_local_mode_still_builds_everything_on_a_full_image_build() {+ local d out rc+ d="$(mktemp -d)"+ prepare_repo "$d"+ out="$(+ PATH="$d/bin:$PATH" TEST_LOG_FILE="$d/ops.log" \+ IMAGE_SOURCE=local IMAGE_TAG="" \+ run_incremental "$d" 'INCREMENTAL_FULL_IMAGE_BUILD=true; incremental_build_images'+ )"+ rc=$?+ if [ "$rc" -eq 0 ] \+ && grep -Fq "make minikube-build-images" "$d/ops.log" \+ && ! grep -Fq "make minikube-pull-images" "$d/ops.log"; then+ pass "local mode still builds every image when the change cannot be targeted"+ else+ fail "expected a full local build and no pull; rc=$rc log=$(cat "$d/ops.log") out=$out"+ fi+ rm -rf "$d"+}++# An unmapped runtime path in ghcr mode is the one case the shadow cannot cover:+# there is no image to build. Passing here would gate against undeployed code,+# so it must stop, name the path, and name a remedy that works.+assert_an_unmapped_change_hard_fails_in_ghcr_mode_with_a_remedy() {+ local d out rc+ d="$(mktemp -d)"+ prepare_repo "$d"+ out="$(+ PATH="$d/bin:$PATH" TEST_LOG_FILE="$d/ops.log" \+ IMAGE_SOURCE=ghcr IMAGE_TAG="$PIN_TAG" \+ run_incremental "$d" 'INCREMENTAL_FULL_IMAGE_BUILD=true; INCREMENTAL_FULL_IMAGE_BUILD_REASON=unmapped; INCREMENTAL_UNMAPPED=("some/unmapped/file.ts"); incremental_build_images'+ )"+ rc=$?+ if [ "$rc" -ne 0 ] \+ && grep -Fq 'some/unmapped/file.ts' <<< "$out" \+ && grep -Fq 'minikube-setup-local' <<< "$out"; then+ pass "an unmapped change in ghcr mode hard-fails, naming the path and a working remedy"+ else+ fail "expected a hard fail naming the unmapped path and minikube-setup-local; rc=$rc out=$out"+ fi+ rm -rf "$d"+}++# The same rule for the other unrecoverable case: no baseline means the shadow+# set is unknowable, and "shadow nothing" would read as "everything is fine".+assert_an_unresolvable_baseline_hard_fails_in_ghcr_mode() {+ local d out rc+ d="$(mktemp -d)"+ prepare_repo "$d"+ out="$(+ PATH="$d/bin:$PATH" TEST_LOG_FILE="$d/ops.log" \+ IMAGE_SOURCE=ghcr IMAGE_TAG=latest \+ run_incremental "$d" 'INCREMENTAL_FULL_IMAGE_BUILD=true; INCREMENTAL_FULL_IMAGE_BUILD_REASON=no-baseline; incremental_build_images'+ )"+ rc=$?+ if [ "$rc" -ne 0 ] \+ && grep -Fq 'minikube-setup-local' <<< "$out" \+ && grep -q 'baseline' <<< "$out"; then+ pass "an unresolvable release baseline hard-fails instead of gating on release code"+ else+ fail "expected a hard fail naming the missing baseline and a remedy; rc=$rc out=$out"+ fi+ rm -rf "$d"+}++# ---------------------------------------------------------------------------+# Where the shadow baseline comes from+# ---------------------------------------------------------------------------++# Published images carry org.opencontainers.image.revision (build-publish.yml),+# so a ghcr cluster with no usable marker still knows exactly which commit its+# release images were built from -- including on the `latest` bootstrap tag,+# which resolves to no git ref at all.+assert_the_release_image_revision_label_supplies_the_missing_baseline() {+ local d out rc base+ d="$(mktemp -d)"+ prepare_repo "$d"+ base="$(repo_head "$d")"+ echo "// changed" >> "$d/repo/control-api/src/index.ts"+ out="$(+ PATH="$d/bin:$PATH" TEST_LOG_FILE="$d/ops.log" TEST_IMAGE_REVISION="$base" \+ TEST_MARKER_DIR="$d/nomarker" \+ IMAGE_SOURCE=ghcr IMAGE_TAG=latest \+ run_incremental "$d" 'incremental_plan; echo "targets=$(incremental_target_summary) full=${INCREMENTAL_FULL_IMAGE_BUILD} repull=${INCREMENTAL_REPULL_ALL}"'+ )"+ rc=$?+ if [ "$rc" -eq 0 ] \+ && grep -Fq 'targets=control-api' <<< "$out" \+ && grep -Fq 'full=false' <<< "$out" \+ && grep -Fq 'repull=true' <<< "$out"; then+ pass "the release image's revision label supplies the baseline when no marker exists"+ else+ fail "expected a control-api-only plan from the revision label; rc=$rc out=$out"+ fi+ rm -rf "$d"+}++# Without a marker AND without a resolvable release revision there is no+# baseline at all, and the plan must say so rather than compute an empty delta.+assert_no_marker_and_no_revision_label_fails_closed() {+ local d out rc+ d="$(mktemp -d)"+ prepare_repo "$d"+ echo "// changed" >> "$d/repo/control-api/src/index.ts"+ out="$(+ PATH="$d/bin:$PATH" TEST_LOG_FILE="$d/ops.log" TEST_IMAGE_REVISION="" \+ TEST_MARKER_DIR="$d/nomarker" \+ IMAGE_SOURCE=ghcr IMAGE_TAG=latest \+ run_incremental "$d" 'incremental_plan; echo "full=${INCREMENTAL_FULL_IMAGE_BUILD} reason=${INCREMENTAL_FULL_IMAGE_BUILD_REASON}"'+ )"+ rc=$?+ if [ "$rc" -eq 0 ] \+ && grep -Fq 'full=true' <<< "$out" \+ && grep -Fq 'reason=no-baseline' <<< "$out"; then+ pass "no marker and no revision label fails closed with an explicit reason"+ else+ fail "expected full=true reason=no-baseline; rc=$rc out=$out"+ fi+ rm -rf "$d"+}++# The baseline read runs inside a command substitution, so a diagnostic printed+# on stdout there would be captured AS the baseline and then diffed against.+# A daemon this pre-gate cannot reach must produce no baseline at all.+assert_an_unreachable_docker_daemon_cannot_become_a_baseline() {+ local d out rc+ d="$(mktemp -d)"+ prepare_repo "$d"+ cat > "$d/bin/minikube" <<'STUB'+#!/usr/bin/env bash+printf 'minikube %s\n' "$*" >>"${TEST_LOG_FILE:?}"+echo "minikube: profile not found" >&2+exit 1+STUB+ chmod +x "$d/bin/minikube"+ echo "// changed" >> "$d/repo/control-api/src/index.ts"+ out="$(+ PATH="$d/bin:$PATH" TEST_LOG_FILE="$d/ops.log" TEST_MARKER_DIR="$d/nomarker" \+ IMAGE_SOURCE=ghcr IMAGE_TAG=latest \+ run_incremental "$d" 'incremental_plan; echo "full=${INCREMENTAL_FULL_IMAGE_BUILD} reason=${INCREMENTAL_FULL_IMAGE_BUILD_REASON}"'+ )"+ rc=$?+ if grep -Fq 'full=true' <<< "$out" && grep -Fq 'reason=no-baseline' <<< "$out"; then+ pass "an unreachable Docker daemon produces no baseline instead of a diagnostic-shaped one"+ else+ fail "expected full=true reason=no-baseline from an unreachable daemon; rc=$rc out=$out"+ fi+ rm -rf "$d"+}++# A `make minikube-setup` between two pre-gates re-pulls every release image and+# DISCARDS the shadows, while leaving the marker untouched. Trusting the+# marker's gitHead there computes an empty delta and gates on release code.+assert_a_re_acquisition_invalidates_the_marker_baseline_in_ghcr_mode() {+ local d out rc head+ d="$(mktemp -d)"+ prepare_repo "$d"+ head="$(repo_head "$d")"+ mkdir -p "$d/marker"+ printf '%s' "$head" > "$d/marker/gitHead"+ printf '%s' "2026-08-06T00:00:00Z" > "$d/marker/imagesGeneratedAt"+ write_manifest "$d" '{"generated":"2026-08-06T09:99:99Z","imageSource":"ghcr","imageTag":"'"$PIN_TAG"'","images":{}}'+ out="$(+ PATH="$d/bin:$PATH" TEST_LOG_FILE="$d/ops.log" TEST_MARKER_DIR="$d/marker" \+ IMAGE_SOURCE=ghcr IMAGE_TAG="$PIN_TAG" IMAGES_GENERATED_AT="2026-08-06T09:99:99Z" \+ run_incremental "$d" 'echo "baseline=[$(incremental_marker_git_head)]"'+ )"+ rc=$?+ if [ "$rc" -eq 0 ] && grep -Fq 'baseline=[]' <<< "$out"; then+ pass "a re-acquisition since the marker invalidates its gitHead baseline in ghcr mode"+ else+ fail "expected an empty baseline after a re-acquisition; rc=$rc out=$out"+ fi+ rm -rf "$d"+}++# The complement, so the fix cannot be "never trust the marker": an untouched+# image set keeps its baseline, which is what makes the incremental path fast.+assert_an_untouched_image_set_keeps_the_marker_baseline() {+ local d out rc head+ d="$(mktemp -d)"+ prepare_repo "$d"+ head="$(repo_head "$d")"+ mkdir -p "$d/marker"+ printf '%s' "$head" > "$d/marker/gitHead"+ printf '%s' "2026-08-06T00:00:00Z" > "$d/marker/imagesGeneratedAt"+ out="$(+ PATH="$d/bin:$PATH" TEST_LOG_FILE="$d/ops.log" TEST_MARKER_DIR="$d/marker" \+ IMAGE_SOURCE=ghcr IMAGE_TAG="$PIN_TAG" IMAGES_GENERATED_AT="2026-08-06T00:00:00Z" \+ run_incremental "$d" 'echo "baseline=[$(incremental_marker_git_head)]"'+ )"+ rc=$?+ if [ "$rc" -eq 0 ] && grep -Fq "baseline=[${head}]" <<< "$out"; then+ pass "an untouched image set keeps the marker's gitHead as the shadow baseline"+ else+ fail "expected baseline=[${head}]; rc=$rc out=$out"+ fi+ rm -rf "$d"+}++# ---------------------------------------------------------------------------+# The mode the pre-gate assumes, and the marker that records it+# ---------------------------------------------------------------------------++# Runs pre-gate-sync.sh up to its configuration seam. No cluster call happens+# before that point.+run_pre_gate_config() {+ local d=$1; shift+ (+ cd "$d/repo" || exit 1+ PATH="$d/bin:$PATH" \+ TEST_LOG_FILE="$d/ops.log" \+ TMPDIR="$d/state" \+ PRE_GATE_SYNC_CONFIG_ONLY=true \+ env "$@" bash "$d/repo/scripts/minikube/pre-gate-sync.sh" --gate manual+ ) 2>&1+}++# A cluster set up in one mode and pre-gated in the other must not silently+# agree. What the cluster RUNS decides, and that is recorded by whichever writer+# last acquired images -- not by whatever IMAGE_SOURCE this shell defaults to.+assert_the_pre_gate_adopts_the_recorded_cluster_mode_over_the_environment() {+ local d out rc+ d="$(mktemp -d)"+ prepare_repo "$d"+ write_manifest "$d" '{"generated":"g1","imageSource":"ghcr","imageTag":"'"$PIN_TAG"'","images":{}}'+ out="$(run_pre_gate_config "$d" IMAGE_SOURCE=local)"+ rc=$?+ if [ "$rc" -eq 0 ] \+ && grep -Fq "imageSource=ghcr" <<< "$out" \+ && grep -Fq "imageTag=${PIN_TAG}" <<< "$out" \+ && grep -Fq "renderDir=${d}/repo/deploy/overlays/minikube-ghcr" <<< "$out"; then+ pass "the pre-gate adopts the mode the cluster's images were acquired in"+ else+ fail "expected the recorded ghcr mode to win over IMAGE_SOURCE=local; rc=$rc out=$out"+ fi+ rm -rf "$d"+}++# The other direction, so the fix cannot be "always ghcr": a locally built+# cluster must render the local overlay even though ghcr is the default.+assert_a_recorded_local_build_renders_the_local_overlay() {+ local d out rc+ d="$(mktemp -d)"+ prepare_repo "$d"+ write_manifest "$d" '{"generated":"g1","imageSource":"local","images":{}}'+ out="$(run_pre_gate_config "$d")"+ rc=$?+ if [ "$rc" -eq 0 ] \+ && grep -Fq "imageSource=local" <<< "$out" \+ && grep -Fq "renderDir=${d}/repo/deploy/overlays/minikube" <<< "$out" \+ && ! grep -q "minikube-ghcr" <<< "$out"; then+ pass "a recorded local build renders the local overlay despite the ghcr default"+ else+ fail "expected the local overlay for a recorded local build; rc=$rc out=$out"+ fi+ rm -rf "$d"+}++# The migration Job EXTRACTS THE CONTROL-API IMAGE from the overlay it renders.+# Rendering the local overlay on a ghcr cluster yields clerum/control-api:test,+# which does not exist there, so the Job ImagePullBackOffs on every ghcr+# pre-gate; rendering the pinned ghcr overlay when the cluster runs an+# overridden tag pulls an image the cluster never had.+assert_the_migration_job_renders_the_overlay_the_cluster_runs() {+ local d out rc hardcoded+ d="$(mktemp -d)"+ prepare_repo "$d"+ hardcoded='--overlay "${PROJECT_DIR}/deploy/overlays/minikube"'+ write_manifest "$d" '{"generated":"g1","imageSource":"ghcr","imageTag":"latest","images":{}}'+ out="$(run_pre_gate_config "$d")"+ rc=$?+ if [ "$rc" -eq 0 ] \+ && grep -q "renderDir=.*/deploy/overlays/minikube-ghcr" <<< "$out" \+ && grep -Fq 'newTag: latest' "$(grep -o 'renderDir=.*' <<< "$out" | head -1 | cut -d= -f2-)/../../components/ghcr-images/kustomization.yaml" \+ && ! grep -Fq "$hardcoded" "$REPO_ROOT/scripts/minikube/pre-gate-sync.sh" \+ && grep -Fq -- '--overlay "${PRE_GATE_RENDER_DIR}"' "$REPO_ROOT/scripts/minikube/pre-gate-sync.sh"; then+ pass "the migration Job renders the overlay (and tag) the cluster actually runs"+ else+ fail "the migration overlay does not follow the cluster's mode/tag; rc=$rc out=$out"+ fi+ rm -rf "$d"+}++# Sourcing the script stops at the same seam, which leaves its marker functions+# defined and callable against the stubbed kubectl.+source_pre_gate_marker_fns() {+ local d=$1+ cd "$d/repo" || return 1+ PRE_GATE_SYNC_CONFIG_ONLY=true+ export PRE_GATE_SYNC_CONFIG_ONLY+ # A sourced script sees the SOURCING function's positional parameters, and+ # pre-gate-sync.sh rejects unknown arguments. Clear them first.+ set --+ # shellcheck source=/dev/null+ . "$d/repo/scripts/minikube/pre-gate-sync.sh"+}++# gitHead alone cannot tell a ghcr cluster from a local one, nor v0.6.0 from+# latest. Both belong in the marker or a mode change reads as "in sync".+assert_the_marker_records_the_image_source_and_tag() {+ local d out rc+ d="$(mktemp -d)"+ prepare_repo "$d"+ write_manifest "$d" '{"generated":"g7","imageSource":"ghcr","imageTag":"'"$PIN_TAG"'","images":{}}'+ out="$(+ (+ set +u+ PATH="$d/bin:$PATH"+ TEST_LOG_FILE="$d/ops.log"+ TMPDIR="$d/state"+ export PATH TEST_LOG_FILE TMPDIR+ source_pre_gate_marker_fns "$d" >/dev/null+ persist_cluster_marker fingerprint-a fingerprint-b+ ) 2>&1+ )"+ rc=$?+ if [ "$rc" -eq 0 ] \+ && grep -Fq -- "--from-literal=imageSource=ghcr" "$d/ops.log" \+ && grep -Fq -- "--from-literal=imageTag=${PIN_TAG}" "$d/ops.log" \+ && grep -Fq -- "--from-literal=imagesGeneratedAt=g7" "$d/ops.log" \+ && grep -Fq -- "--from-literal=gitHead=" "$d/ops.log"; then+ pass "the marker records imageSource, imageTag and the image-acquisition stamp beside gitHead"+ else+ fail "the marker does not record the image mode; rc=$rc log=$(cat "$d/ops.log") out=$out"+ fi+ rm -rf "$d"+}++# A marker written by a ghcr pre-gate must not match a local one.+marker_matches_for() {+ local d=$1+ (+ set +u+ PATH="$d/bin:$PATH"+ TEST_LOG_FILE="$d/ops.log"+ TEST_MARKER_DIR="$d/marker"+ TMPDIR="$d/state"+ export PATH TEST_LOG_FILE TEST_MARKER_DIR TMPDIR+ source_pre_gate_marker_fns "$d" >/dev/null+ printf '%s' "$WORKTREE_ID" > "$d/marker/worktreeId"+ cluster_marker_matches fingerprint-a "$WORKTREE_ID"+ ) >/dev/null 2>&1+}++assert_a_mode_change_forces_a_full_resync() {+ local d rc_same rc_diff head+ d="$(mktemp -d)"+ prepare_repo "$d"+ head="$(repo_head "$d")"+ write_manifest "$d" '{"generated":"g7","imageSource":"ghcr","imageTag":"'"$PIN_TAG"'","images":{}}'+ mkdir -p "$d/marker"+ printf '%s' "fingerprint-a" > "$d/marker/clusterFingerprint"+ printf '%s' "$head" > "$d/marker/gitHead"+ printf '%s' "g7" > "$d/marker/imagesGeneratedAt"+ printf '%s' "$PIN_TAG" > "$d/marker/imageTag"+ printf '%s' "ghcr" > "$d/marker/imageSource"+ marker_matches_for "$d"; rc_same=$?+ printf '%s' "local" > "$d/marker/imageSource"+ marker_matches_for "$d"; rc_diff=$?+ if [ "$rc_same" -eq 0 ] && [ "$rc_diff" -ne 0 ]; then+ pass "an identical marker matches and a changed imageSource forces a resync"+ else+ fail "expected match=0 and mode-change!=0; got same=$rc_same changed=$rc_diff"+ fi+ rm -rf "$d"+}++# The tag is half the coordinate: v0.6.0 and latest are different clusters.+assert_a_tag_change_forces_a_full_resync() {+ local d rc_same rc_diff head+ d="$(mktemp -d)"+ prepare_repo "$d"+ head="$(repo_head "$d")"+ write_manifest "$d" '{"generated":"g7","imageSource":"ghcr","imageTag":"'"$PIN_TAG"'","images":{}}'+ mkdir -p "$d/marker"+ printf '%s' "fingerprint-a" > "$d/marker/clusterFingerprint"+ printf '%s' "$head" > "$d/marker/gitHead"+ printf '%s' "g7" > "$d/marker/imagesGeneratedAt"+ printf '%s' "ghcr" > "$d/marker/imageSource"+ printf '%s' "$PIN_TAG" > "$d/marker/imageTag"+ marker_matches_for "$d"; rc_same=$?+ printf '%s' "some-other-tag" > "$d/marker/imageTag"+ marker_matches_for "$d"; rc_diff=$?+ if [ "$rc_same" -eq 0 ] && [ "$rc_diff" -ne 0 ]; then+ pass "an identical marker matches and a changed image tag forces a resync"+ else+ fail "expected match=0 and tag-change!=0; got same=$rc_same changed=$rc_diff"+ fi+ rm -rf "$d"+}++# A setup between two pre-gates replaces every image and discards the shadows.+# Without this the marker still matches and no sync runs at all.+assert_a_re_acquisition_forces_a_full_resync() {+ local d rc_same rc_diff head+ d="$(mktemp -d)"+ prepare_repo "$d"+ head="$(repo_head "$d")"+ write_manifest "$d" '{"generated":"g8","imageSource":"ghcr","imageTag":"'"$PIN_TAG"'","images":{}}'+ mkdir -p "$d/marker"+ printf '%s' "fingerprint-a" > "$d/marker/clusterFingerprint"+ printf '%s' "$head" > "$d/marker/gitHead"+ printf '%s' "ghcr" > "$d/marker/imageSource"+ printf '%s' "$PIN_TAG" > "$d/marker/imageTag"+ printf '%s' "g8" > "$d/marker/imagesGeneratedAt"+ marker_matches_for "$d"; rc_same=$?+ printf '%s' "g7" > "$d/marker/imagesGeneratedAt"+ marker_matches_for "$d"; rc_diff=$?+ if [ "$rc_same" -eq 0 ] && [ "$rc_diff" -ne 0 ]; then+ pass "a marker stamped before the last image acquisition forces a full resync"+ else+ fail "expected match=0 and stale-acquisition!=0; got same=$rc_same stale=$rc_diff"+ fi+ rm -rf "$d"+}++# ---------------------------------------------------------------------------+# The other mode-crossing path: the full overlay apply+# ---------------------------------------------------------------------------++# `make minikube-deploy-all` hardcoded deploy/overlays/minikube, so a deploy/*+# change on a ghcr cluster applied manifests referencing clerum/*:test tags that+# were never built there -- cluster-wide ImagePullBackOff.+assert_make_deploy_all_renders_the_mode_aware_overlay() {+ local out+ out="$(cd "$REPO_ROOT" && make -n minikube-deploy-all 2>&1)"+ if grep -q 'image-mode.sh --render-dir' <<< "$out" \+ && ! grep -q 'kustomize deploy/overlays/minikube |' <<< "$out"; then+ pass "make minikube-deploy-all resolves the overlay from the cluster's image mode"+ else+ fail "make minikube-deploy-all still hardcodes the local overlay: $out"+ fi+}++# The resolver is the single mechanism both call sites use, so its own+# behaviour is checked directly: a recorded mode wins over the environment.+assert_the_render_dir_resolver_follows_the_recorded_mode() {+ local d ghcr_out local_out+ d="$(mktemp -d)"+ prepare_repo "$d"+ write_manifest "$d" '{"generated":"g1","imageSource":"ghcr","imageTag":"'"$PIN_TAG"'","images":{}}'+ ghcr_out="$(IMAGE_SOURCE=local bash "$d/repo/scripts/minikube/image-mode.sh" --render-dir 2>&1)"+ write_manifest "$d" '{"generated":"g1","imageSource":"local","images":{}}'+ local_out="$(bash "$d/repo/scripts/minikube/image-mode.sh" --render-dir 2>&1)"+ if [ "$ghcr_out" = "$d/repo/deploy/overlays/minikube-ghcr" ] \+ && [ "$local_out" = "$d/repo/deploy/overlays/minikube" ]; then+ pass "the render-dir resolver follows the recorded mode, not the environment"+ else+ fail "resolver returned ghcr='$ghcr_out' local='$local_out'"+ fi+ rm -rf "$d"+}++# An overridden tag is not committed anywhere, so rendering the committed+# overlay would apply the PINNED tag to a cluster running the override.+assert_an_overridden_tag_renders_from_a_copy_carrying_that_tag() {+ local d out rendered+ d="$(mktemp -d)"+ prepare_repo "$d"+ write_manifest "$d" '{"generated":"g1","imageSource":"ghcr","imageTag":"latest","images":{}}'+ out="$(bash "$d/repo/scripts/minikube/image-mode.sh" --render-dir 2>&1)"+ rendered="${out}/../../components/ghcr-images/kustomization.yaml"+ if [ -d "$out" ] \+ && [ "${out#"$d/repo/deploy"}" = "$out" ] \+ && [ -f "$rendered" ] \+ && grep -q 'newTag: latest' "$rendered" \+ && ! grep -q "newTag: ${PIN_TAG}" "$rendered" \+ && grep -q "newTag: ${PIN_TAG}" "$d/repo/deploy/components/ghcr-images/kustomization.yaml"; then+ pass "an overridden tag renders from a copy carrying it, leaving the committed pin alone"+ else+ fail "expected an out-of-tree render dir pinned to 'latest'; got '$out'"+ fi+ rm -rf "$d"+}++# A mode that is neither ghcr nor local is a typo, and guessing one silently+# picks a cluster shape.+assert_an_unknown_image_source_is_rejected() {+ local d out rc+ d="$(mktemp -d)"+ prepare_repo "$d"+ out="$(IMAGE_SOURCE=gcr bash "$d/repo/scripts/minikube/image-mode.sh" --render-dir 2>&1)"+ rc=$?+ if [ "$rc" -ne 0 ] && grep -q 'gcr' <<< "$out"; then+ pass "an unknown IMAGE_SOURCE is rejected instead of guessed"+ else+ fail "expected a non-zero exit naming the bad mode; rc=$rc out=$out"+ fi+ rm -rf "$d"+}++# A shadow build rewrites the image manifest through build-images.sh --only. If+# that run dropped the recorded tag, the next pre-gate would fall back to the+# committed pin and declare the cluster out of sync on every run.+# A shadow build is an --only run of build-images.sh, and that run REWRITES the+# image manifest. Dropping the recorded coordinate there would make the next+# pre-gate fall back to the committed pin, decide the cluster changed tag, and+# force a full resync on every single run.+assert_a_targeted_build_carries_the_recorded_coordinate_forward() {+ local d rc manifest mode tag+ d="$(mktemp -d)"+ prepare_repo "$d"+ # The REAL build-images.sh, not the stub prepare_repo installs.+ cp "$REPO_ROOT/scripts/minikube/build-images.sh" "$d/repo/scripts/minikube/build-images.sh"+ write_manifest "$d" '{"generated":"g1","imageSource":"ghcr","imageTag":"latest","images":{}}'+ (+ cd "$d/repo" || exit 1+ PATH="$d/bin:$PATH" TEST_LOG_FILE="$d/ops.log" \+ bash "$d/repo/scripts/minikube/build-images.sh" --only=control-api+ ) >"$d/build.log" 2>&1+ rc=$?+ manifest="$d/repo/deploy/minikube/.image-manifest.json"+ mode="$(IMAGE_SOURCE=local bash "$d/repo/scripts/minikube/image-mode.sh" --image-source 2>&1)"+ tag="$(IMAGE_SOURCE=local bash "$d/repo/scripts/minikube/image-mode.sh" --image-tag 2>&1)"+ if [ "$rc" -eq 0 ] \+ && [ -f "$manifest" ] \+ && [ "$mode" = "ghcr" ] \+ && [ "$tag" = "latest" ]; then+ pass "a targeted build carries the recorded imageSource and imageTag forward"+ else+ fail "after --only the manifest records mode='$mode' tag='$tag' (rc=$rc): $(tail -3 "$d/build.log")"+ fi+ rm -rf "$d"+}++assert_the_touched_scripts_parse() {+ local f bad=""+ for f in scripts/minikube/image-mode.sh scripts/minikube/pre-gate-sync.sh \+ scripts/minikube/pre-gate-incremental.sh scripts/minikube/build-images.sh \+ scripts/tests/test-minikube-pre-gate-shadow.sh; do+ bash -n "$REPO_ROOT/$f" || bad+="$f "+ done+ if [ -z "$bad" ]; then+ pass "every script this harness touches parses"+ else+ fail "bash -n failed for: $bad"+ fi+}++assert_every_defined_case_is_invoked() {+ local self defined invoked missing+ self="$REPO_ROOT/scripts/tests/test-minikube-pre-gate-shadow.sh"+ defined="$(grep -oE '^assert_[a-z_]+\(\) \{' "$self" | sed -E 's/\(\) \{$//' | sort -u)"+ invoked="$(grep -oE '^assert_[a-z_]+$' "$self" | sort -u)"+ missing="$(comm -23 <(printf '%s\n' "$defined") <(printf '%s\n' "$invoked"))"+ if [ -z "$missing" ]; then+ pass "every defined assert_ case is invoked in the call block"+ else+ fail "defined but never invoked: $(printf '%s ' $missing)"+ fi+}++assert_a_targeted_ghcr_build_is_retagged_onto_the_running_ghcr_ref+assert_a_multi_image_selector_shadows_every_image_it_builds+assert_local_mode_never_retags_onto_a_ghcr_ref+assert_the_shadow_set_is_reported_with_every_ref+assert_an_empty_shadow_set_is_reported_as_release_only+assert_a_failed_retag_fails_the_pre_gate+assert_a_full_sync_in_ghcr_mode_repulls_instead_of_building_everything+assert_local_mode_still_builds_everything_on_a_full_image_build+assert_an_unmapped_change_hard_fails_in_ghcr_mode_with_a_remedy+assert_an_unresolvable_baseline_hard_fails_in_ghcr_mode+assert_the_release_image_revision_label_supplies_the_missing_baseline+assert_no_marker_and_no_revision_label_fails_closed+assert_an_unreachable_docker_daemon_cannot_become_a_baseline+assert_a_re_acquisition_invalidates_the_marker_baseline_in_ghcr_mode+assert_an_untouched_image_set_keeps_the_marker_baseline+assert_the_pre_gate_adopts_the_recorded_cluster_mode_over_the_environment+assert_a_recorded_local_build_renders_the_local_overlay+assert_the_migration_job_renders_the_overlay_the_cluster_runs+assert_the_marker_records_the_image_source_and_tag+assert_a_mode_change_forces_a_full_resync+assert_a_tag_change_forces_a_full_resync+assert_a_re_acquisition_forces_a_full_resync+assert_make_deploy_all_renders_the_mode_aware_overlay+assert_the_render_dir_resolver_follows_the_recorded_mode+assert_an_overridden_tag_renders_from_a_copy_carrying_that_tag+assert_an_unknown_image_source_is_rejected+assert_a_targeted_build_carries_the_recorded_coordinate_forward+assert_the_touched_scripts_parse+assert_every_defined_case_is_invoked++exit $FAIL