Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(branch-profile): address PR #855 review round 2 harness findings

Alfredo Lopeza8982841d814
diff --git a/scripts/minikube-profiles/branch-profile.sh b/scripts/minikube-profiles/branch-profile.sh
index 44d2ec872..2748ad7da 100755
--- a/scripts/minikube-profiles/branch-profile.sh
+++ b/scripts/minikube-profiles/branch-profile.sh
@@ -78,14 +78,12 @@ file_value() {
}
validate_host() {
- case "${HOST}" in
- 127.0.0.1|localhost) URL_HOST="${HOST}" ;;
- ::1|\[::1\])
- HOST=::1
- URL_HOST='[::1]'
- ;;
- *) die "HOST must be a loopback address, got: ${HOST}" ;;
- esac
+ # ports.env URLs and every port-forward ownership record are bound to
+ # 127.0.0.1 (kubectl port-forward --address=127.0.0.1). Accepting another
+ # loopback spelling here would publish URLs no forward listens on.
+ [[ "${HOST}" == 127.0.0.1 ]] ||
+ die "HOST must be 127.0.0.1 (the only address branch-profile forwards bind), got: ${HOST}"
+ URL_HOST=127.0.0.1
}
normalize_cache_root() {
@@ -107,10 +105,13 @@ normalize_cache_root() {
validate_profile_name() {
[[ ${#PROFILE} -le 63 && "${PROFILE}" =~ ^[a-zA-Z0-9][a-zA-Z0-9._-]*$ ]] ||
die "resolver returned an unsafe profile name: ${PROFILE}"
- # Positive check: a branch profile is always a local clerum-* profile. The
- # denylist below only names shared profiles known today; this rejects the rest.
- [[ "${PROFILE}" =~ ^clerum-[a-z0-9][a-z0-9._-]*$ ]] ||
- die "resolver returned a profile outside the local clerum-* namespace: ${PROFILE}"
+ # Positive check: a branch profile is always clerum-<branch slug>-<owner id
+ # prefix>. The hex suffix is what separates it from shared profiles such as
+ # clerum-dev, which also match clerum-*; the denylist below only names the
+ # shared profiles known today. {7,8} matches the branch-scoped check in
+ # scripts/e2e/e2e-plugin-workload-sdk.sh.
+ [[ "${PROFILE}" =~ ^clerum-[a-z0-9][a-z0-9._-]*-[0-9a-f]{7,8}$ ]] ||
+ die "resolver returned a profile outside the branch-scoped clerum-<branch>-<owner-id> namespace: ${PROFILE}"
case "${PROFILE}" in
*gke*|*prod*|*staging*|clerum-test|default|minikube)
die "resolver returned a shared or protected profile: ${PROFILE}" ;;
@@ -635,29 +636,43 @@ select_mcp_service() {
return 3
}
+# Sets STOP_PF_OUTCOME to absent, stopped (the library verified and stopped or
+# cleared the record) or retired (PID reuse proven; nothing signalled).
stop_own_pf() {
local name="$1" namespace="$2" service="$3" local_port="$4" remote_port="$5"
- local pidfile="${PIDS_DIR}/${name}.pid" comm
- [[ -e "${pidfile}" || -L "${pidfile}" ]] || return 0
+ local pidfile="${PIDS_DIR}/${name}.pid" state actual_start
+ STOP_PF_OUTCOME=""
+ if [[ ! -e "${pidfile}" && ! -L "${pidfile}" ]]; then
+ STOP_PF_OUTCOME=absent
+ return 0
+ fi
if pf_owner_cleanup_record "${pidfile}" "${PROFILE}" "${PROFILE}" "${REPO_DIR}" \
"${namespace}" "${service}" "${local_port}" "${remote_port}"; then
+ STOP_PF_OUTCOME=stopped
return 0
fi
- # PID reuse: the live process is not this lane's kubectl. Do not signal it.
- # Drop only the stale record so the next forward records a separate PID.
- if pf_owner_read_record "${pidfile}"; then
- comm="$(ps -p "${PF_OWNER_RECORD_PID}" -o comm= 2>/dev/null || true)"
- case "${comm}" in
- kubectl | */kubectl) ;;
- *)
- printf 'retiring reused port-forward record without signalling pid=%s\n' \
- "${PF_OWNER_RECORD_PID}"
- pf_owner_remove_dead_record "${pidfile}" || return 1
- return 0
- ;;
- esac
+ # PID reuse is the only case retired here: the record is this worktree's own
+ # binding, and its PID now names a live process that started at a different
+ # time, so the recorded kubectl no longer exists. That process is never
+ # signalled; only the stale record is dropped. A foreign binding, an
+ # unreadable record, or a live process whose start still matches the record
+ # is kept, because nothing proves it stale.
+ if pf_owner_read_record "${pidfile}" 2>/dev/null &&
+ pf_owner_record_matches "${PROFILE}" "${PROFILE}" "${REPO_DIR}" \
+ "${namespace}" "${service}" "${local_port}" "${remote_port}"; then
+ state="$(pf_owner_process_state "${PF_OWNER_RECORD_PID}")"
+ if [[ "${state}" == live ]] &&
+ actual_start="$(pf_owner_process_start "${PF_OWNER_RECORD_PID}")" &&
+ [[ "${actual_start}" != "${PF_OWNER_RECORD_START}" ]]; then
+ printf 'retiring %s record: pid=%s now belongs to a process started %s, not the recorded kubectl started %s; that process was not signalled\n' \
+ "${name}" "${PF_OWNER_RECORD_PID}" "${actual_start}" "${PF_OWNER_RECORD_START}"
+ pf_owner_remove_dead_record "${pidfile}" || return 1
+ STOP_PF_OUTCOME=retired
+ return 0
+ fi
fi
- printf 'ERROR: refusing to stop unverified port-forward record: %s\n' "${pidfile}" >&2
+ printf 'ERROR: kept port-forward record %s: it could not be verified as this worktree'"'"'s kubectl forward (reason above) and no process was signalled. Confirm its PID is not a port-forward you still need, then remove the file by hand.\n' \
+ "${pidfile}" >&2
return 1
}
@@ -812,10 +827,17 @@ rewrite_shim() {
cmd_prepare_shims() {
require_command git shasum perl
persist_state
- mkdir -p "${CACHE_DIR}/scripts"
- if [[ -L "${SHIMS_DIR}" || -L "${DEPLOY_SHIM_DIR}" ]]; then
- die "BRANCH_PROFILE_SHIM_SYMLINK: refusing to replace symlink shim dirs"
+ # rm -rf and cp -R below resolve every parent component, so a symlinked
+ # scripts/ directory would redirect the delete and the copy outside the
+ # profile. CACHE_DIR itself was verified as a real directory by persist_state.
+ local shims_parent="${CACHE_DIR}/scripts"
+ if [[ -L "${shims_parent}" || -L "${SHIMS_DIR}" || -L "${DEPLOY_SHIM_DIR}" || -L "${SHIM_ENV}" ]]; then
+ die "BRANCH_PROFILE_SHIM_SYMLINK: refusing symlinked shim paths under ${CACHE_DIR}"
fi
+ mkdir -p "${shims_parent}"
+ [[ -d "${shims_parent}" && ! -L "${shims_parent}" &&
+ "$(cd -- "${shims_parent}" && pwd -P)" == "${CACHE_DIR}/scripts" ]] ||
+ die "BRANCH_PROFILE_SHIM_SYMLINK: ${shims_parent} does not resolve inside ${CACHE_DIR}"
umask 077
rm -rf "${SHIMS_DIR}" "${DEPLOY_SHIM_DIR}"
cp -R "${REPO_DIR}/scripts/minikube" "${SHIMS_DIR}"
@@ -833,7 +855,16 @@ cmd_prepare_shims() {
# fails on its own instead of hiding behind the other. The earlier combined
# expression carried two alternatives that matched nothing in the current upstream.
rewrite_shim "${SHIMS_DIR}/seed-test-data.sh" 's#: "\$\{CONTEXT:=clerum-test\}"#: "\${CONTEXT:=\${MINIKUBE_PROFILE:-clerum-test}}"#g' "seed-test-data.sh CONTEXT default"
- rewrite_shim "${SHIMS_DIR}/seed-test-data.sh" 's#export ADMIN_PASSWORD E2E_DEV_LOGIN_EMAIL CONTEXT#: "\${ALLOWED_CONTEXTS:=\${CONTEXT}}"\nexport ADMIN_PASSWORD E2E_DEV_LOGIN_EMAIL CONTEXT ALLOWED_CONTEXTS#g' "seed-test-data.sh ALLOWED_CONTEXTS"
+ # The seed authorizes only the context it runs against. Default the allowlist
+ # to CONTEXT only when CONTEXT is this validated branch profile, baked in as a
+ # literal; any other CONTEXT (clerum, clerum-dev, ...) must not authorize
+ # itself. PROFILE passed validate_profile_name, so it holds no perl or shell
+ # metacharacters.
+ local allowlist_line allowlist_expr
+ allowlist_line='if [ "\$CONTEXT" = "'"${PROFILE}"'" ]; then : "\${ALLOWED_CONTEXTS:=\$CONTEXT}"; fi'
+ printf -v allowlist_expr 's#\nexport ADMIN_PASSWORD E2E_DEV_LOGIN_EMAIL CONTEXT ALLOWED_CONTEXTS #\n%s\nexport ADMIN_PASSWORD E2E_DEV_LOGIN_EMAIL CONTEXT ALLOWED_CONTEXTS #g' \
+ "${allowlist_line}"
+ rewrite_shim "${SHIMS_DIR}/seed-test-data.sh" "${allowlist_expr}" "seed-test-data.sh ALLOWED_CONTEXTS"
rewrite_shim "${SHIMS_DIR}/build-images.sh" 's#MANIFEST_FILE="\$\{PROJECT_DIR\}/deploy/minikube/\.image-manifest.json"#MANIFEST_FILE="\${BRANCH_PROFILE_DEPLOY_DIR:-\${PROJECT_DIR}/deploy}/minikube/.image-manifest.json"#g' "build-images.sh"
# full-setup.sh resolves BRANCH_PROFILE_DEPLOY_DIR natively (ACTIVE_MINIKUBE_*),
# so it needs no path rewrite; rewrite_shim would fail on it as a no-op.
@@ -887,6 +918,19 @@ cmd_start() {
if [[ "${after_context}" == "${PROFILE}" && "${before_context}" != "${PROFILE}" ]]; then
printf 'ERROR: minikube switched the kubectl current-context from %s to %s despite --keep-context\n' \
"${before_context:-<unset>}" "${after_context}" >&2
+ # The switch belongs to this command, so undo it before failing: another
+ # session may be relying on the context it had selected.
+ if [[ -n "${before_context}" ]]; then
+ if kubectl config use-context "${before_context}" >/dev/null; then
+ printf 'restored the kubectl current-context to %s\n' "${before_context}" >&2
+ else
+ printf 'ERROR: could not restore the kubectl current-context to %s; it is still %s\n' \
+ "${before_context}" "${after_context}" >&2
+ fi
+ else
+ printf 'ERROR: no current-context was set before the start, so none was restored; it is still %s\n' \
+ "${after_context}" >&2
+ fi
exit 1
fi
run_bounded minikube-status "${MINIKUBE_STATUS_TIMEOUT_SECONDS}" \
@@ -1099,24 +1143,69 @@ cmd_stop_pf() {
name="$(basename "${pidfile}" .pid)"
resolve_stop_pf_binding "${name}" "${pidfile}" || return 1
done
+ # Attempt every record, so one record that cannot be verified does not leave
+ # the verified ones running; the kept records are listed and fail the call.
+ local -a kept=()
for pidfile in "${pidfiles[@]}"; do
name="$(basename "${pidfile}" .pid)"
- resolve_stop_pf_binding "${name}" "${pidfile}" || return 1
- stop_own_pf "${name}" "${STOP_PF_NAMESPACE}" "${STOP_PF_SERVICE}" \
- "${STOP_PF_LOCAL_PORT}" "${STOP_PF_REMOTE_PORT}" || return 1
- printf 'stopped or cleared verified %s record\n' "${name}"
+ if ! resolve_stop_pf_binding "${name}" "${pidfile}"; then
+ kept+=("${pidfile}")
+ continue
+ fi
+ if ! stop_own_pf "${name}" "${STOP_PF_NAMESPACE}" "${STOP_PF_SERVICE}" \
+ "${STOP_PF_LOCAL_PORT}" "${STOP_PF_REMOTE_PORT}"; then
+ kept+=("${pidfile}")
+ continue
+ fi
+ case "${STOP_PF_OUTCOME}" in
+ stopped | absent) printf 'stopped or cleared verified %s record\n' "${name}" ;;
+ retired) printf 'retired stale %s record after PID reuse\n' "${name}" ;;
+ *)
+ printf 'ERROR: unexpected stop outcome for %s: %s\n' "${pidfile}" "${STOP_PF_OUTCOME:-<empty>}" >&2
+ kept+=("${pidfile}")
+ ;;
+ esac
done
+ if (( ${#kept[@]} > 0 )); then
+ printf 'ERROR: %s port-forward record(s) kept:\n' "${#kept[@]}" >&2
+ printf ' %s\n' "${kept[@]}" >&2
+ return 1
+ fi
+}
+
+# Runs cmd_stop_pf in a subshell so that a refusal inside it (including a die)
+# is reported without preventing the minikube operation that follows.
+stop_pf_before_minikube() {
+ local status=0
+ ( cmd_stop_pf ) || status=$?
+ return "${status}"
+}
+
+report_kept_pf_records() {
+ local operation="$1"
+ printf 'ERROR: minikube %s ran for profile %s, but port-forward records listed above were kept; the next T2 preflight will refuse them with PORT_FORWARD_CONFLICT until they are removed\n' \
+ "${operation}" "${PROFILE}" >&2
}
cmd_stop() {
require_existing_profile
# Clear the verified port-forward records first: a stopped cluster leaves
# records naming dead kubectl processes, and the next T2 preflight refuses
- # them with PORT_FORWARD_CONFLICT.
- cmd_stop_pf
+ # them with PORT_FORWARD_CONFLICT. A record that cannot be verified is kept
+ # and reported, and must not strand the profile running: the stop still
+ # happens and the command fails at the end.
+ local pf_status=0 minikube_status=0
+ stop_pf_before_minikube || pf_status=$?
printf 'stopping minikube profile: %s\n' "${PROFILE}"
run_bounded minikube-stop "${MINIKUBE_STOP_TIMEOUT_SECONDS}" \
- minikube -p "${PROFILE}" stop
+ minikube -p "${PROFILE}" stop || minikube_status=$?
+ if (( pf_status != 0 )); then
+ report_kept_pf_records stop
+ fi
+ if (( minikube_status != 0 )); then
+ return "${minikube_status}"
+ fi
+ (( pf_status == 0 )) || return 1
}
cmd_setup() {
@@ -1146,10 +1235,20 @@ cmd_delete() {
fi
# The registry (pids/*.pid) outlives the cluster; clear the port-forward
# records so the deleted profile does not leave PORT_FORWARD_CONFLICT behind.
- cmd_stop_pf
+ # As in cmd_stop, a kept record is reported and fails the command, but does
+ # not block the confirmed delete.
+ local pf_status=0 minikube_status=0
+ stop_pf_before_minikube || pf_status=$?
printf 'deleting minikube profile: %s\n' "${PROFILE}"
run_bounded minikube-delete "${MINIKUBE_DELETE_TIMEOUT_SECONDS}" \
- minikube -p "${PROFILE}" delete
+ minikube -p "${PROFILE}" delete || minikube_status=$?
+ if (( pf_status != 0 )); then
+ report_kept_pf_records delete
+ fi
+ if (( minikube_status != 0 )); then
+ return "${minikube_status}"
+ fi
+ (( pf_status == 0 )) || return 1
}
cmd_e2e_plan() {
diff --git a/scripts/tests/test-branch-profile-lifecycle.sh b/scripts/tests/test-branch-profile-lifecycle.sh
new file mode 100755
index 000000000..832b1baa6
--- /dev/null
+++ b/scripts/tests/test-branch-profile-lifecycle.sh
@@ -0,0 +1,584 @@
+#!/usr/bin/env bash
+# Behaviour scenarios for scripts/minikube-profiles/branch-profile.sh.
+#
+# The real script runs against a fixture Git repository. kubectl, minikube,
+# helm, docker and curl are PATH stubs that append every call to a log, and
+# CACHE_ROOT is a temporary directory, so no cluster, Docker daemon or shared
+# kubeconfig is touched. A port-forward stub process presents the exact kubectl
+# argv to ps(1) (exec -a) so the ownership library can record and stop it.
+#
+# Every scenario asserts the exit code, the stub call log and the pidfile state.
+# Every negative assertion is paired with a positive witness proving the path
+# under test actually ran.
+set -euo pipefail
+
+ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd -P)"
+# BRANCH_PROFILE_LIFECYCLE_SCRIPT lets a mutation run point this suite at a
+# modified copy of the script; by default the checked-in script is tested.
+BRANCH_PROFILE="${BRANCH_PROFILE_LIFECYCLE_SCRIPT:-${ROOT}/scripts/minikube-profiles/branch-profile.sh}"
+[[ -f "${BRANCH_PROFILE}" ]] || { printf 'FAIL: script under test is missing: %s\n' "${BRANCH_PROFILE}" >&2; exit 1; }
+
+# Ambient selectors from the caller's shell must not leak into the fixture.
+unset MINIKUBE_PROFILE BRANCH_PROFILE_PROFILE HOST CONFIRM_DELETE CONFIRM_PROFILE \
+ ARGS KUBECONFIG ALLOWED_CONTEXTS CONTEXT DOCKER_CONTEXT PF_STARTUP_DELAY
+
+tmp="$(mktemp -d "${TMPDIR:-/tmp}/branch-profile-lifecycle.XXXXXX")"
+tmp="$(cd -- "${tmp}" && pwd -P)"
+state="${tmp}/state"
+stub_bin="${tmp}/bin"
+cache_root="${tmp}/cache"
+out_dir="${tmp}/out"
+mkdir -p "${state}" "${stub_bin}" "${cache_root}" "${out_dir}"
+
+kill_recorded_processes() {
+ local file pid
+ for file in "${state}/pf-pids" "${state}/foreign-pids"; do
+ [[ -f "${file}" ]] || continue
+ while IFS= read -r pid; do
+ [[ "${pid}" =~ ^[0-9]+$ ]] || continue
+ kill -KILL "${pid}" 2>/dev/null || true
+ # Reap our own children quietly; kubectl stubs are not children here.
+ wait "${pid}" 2>/dev/null || true
+ done <"${file}"
+ done
+}
+cleanup() {
+ kill_recorded_processes
+ rm -rf "${tmp}"
+}
+trap cleanup EXIT
+
+ASSERTIONS=0
+fail() {
+ printf 'FAIL: %s\n' "$*" >&2
+ if [[ -n "${BP_OUT:-}" && -f "${BP_OUT}" ]]; then
+ printf -- '--- last branch-profile output (%s, rc=%s) ---\n' "${BP_OUT##*/}" "${BP_RC:-?}" >&2
+ sed -n '1,60p' "${BP_OUT}" >&2
+ fi
+ if [[ -f "${state}/calls.log" ]]; then
+ printf -- '--- stub call log ---\n' >&2
+ sed -n '1,60p' "${state}/calls.log" >&2
+ fi
+ exit 1
+}
+ok() { ASSERTIONS=$((ASSERTIONS + 1)); }
+
+assert_rc() {
+ local expected="$1" label="$2"
+ [[ "${BP_RC}" == "${expected}" ]] || fail "${label}: expected exit ${expected}, got ${BP_RC}"
+ ok
+}
+assert_rc_nonzero() {
+ local label="$1"
+ [[ "${BP_RC}" != 0 ]] || fail "${label}: expected a non-zero exit, got 0"
+ ok
+}
+assert_output_has() {
+ local needle="$1" label="$2"
+ grep -Fq -- "${needle}" "${BP_OUT}" || fail "${label}: output lacks '${needle}'"
+ ok
+}
+assert_output_lacks() {
+ local needle="$1" label="$2"
+ if grep -Fq -- "${needle}" "${BP_OUT}"; then fail "${label}: output unexpectedly has '${needle}'"; fi
+ ok
+}
+assert_log_has() {
+ local needle="$1" label="$2"
+ grep -Fq -- "${needle}" "${state}/calls.log" || fail "${label}: stub log lacks '${needle}'"
+ ok
+}
+assert_log_lacks() {
+ local needle="$1" label="$2"
+ if grep -Fq -- "${needle}" "${state}/calls.log"; then fail "${label}: stub log unexpectedly has '${needle}'"; fi
+ ok
+}
+assert_log_count() {
+ local needle="$1" expected="$2" label="$3" actual
+ actual="$(grep -Fc -- "${needle}" "${state}/calls.log" || true)"
+ [[ "${actual}" == "${expected}" ]] || fail "${label}: expected ${expected} '${needle}' calls, got ${actual}"
+ ok
+}
+assert_file() {
+ local path="$1" label="$2"
+ [[ -f "${path}" ]] || fail "${label}: missing ${path}"
+ ok
+}
+assert_no_file() {
+ local path="$1" label="$2"
+ [[ ! -e "${path}" && ! -L "${path}" ]] || fail "${label}: unexpectedly present ${path}"
+ ok
+}
+assert_alive() {
+ local pid="$1" label="$2"
+ kill -0 "${pid}" 2>/dev/null || fail "${label}: pid ${pid} is not alive"
+ ok
+}
+assert_dead() {
+ local pid="$1" label="$2" index
+ for ((index = 0; index < 50; index += 1)); do
+ kill -0 "${pid}" 2>/dev/null || { ok; return 0; }
+ sleep 0.05
+ done
+ fail "${label}: pid ${pid} is still alive"
+}
+
+# --- PATH stubs ---------------------------------------------------------------
+cat >"${stub_bin}/kubectl" <<'EOF_KUBECTL'
+#!/usr/bin/env bash
+set -euo pipefail
+state="${BRANCH_PROFILE_STUB_STATE:?stub state directory is required}"
+printf 'kubectl %s\n' "$*" >>"${state}/calls.log"
+if [[ "${1:-}" == config ]]; then
+ case "${2:-}" in
+ current-context)
+ [[ -s "${state}/current-context" ]] || exit 1
+ cat "${state}/current-context"
+ exit 0
+ ;;
+ use-context)
+ printf '%s\n' "${3:?use-context needs a name}" >"${state}/current-context"
+ exit 0
+ ;;
+ esac
+ printf 'kubectl stub: unsupported config call: %s\n' "$*" >&2
+ exit 64
+fi
+original="$*"
+namespace=""
+verb=""
+kind=""
+name=""
+while (( $# > 0 )); do
+ case "$1" in
+ --context=* | --request-timeout=* | --address=* | --ignore-not-found | -A) shift ;;
+ -n) namespace="$2"; shift 2 ;;
+ -o) shift 2 ;;
+ *)
+ if [[ -z "${verb}" ]]; then verb="$1"
+ elif [[ -z "${kind}" ]]; then kind="$1"
+ elif [[ -z "${name}" ]]; then name="$1"
+ fi
+ shift
+ ;;
+ esac
+done
+case "${verb}" in
+ cluster-info)
+ [[ -e "${state}/reachable" ]] || { printf 'stub: cluster unreachable\n' >&2; exit 1; }
+ printf 'stub control plane\n'
+ ;;
+ get)
+ case "${kind}" in
+ svc)
+ if grep -Fqx "${namespace}/${name}" "${state}/services"; then
+ printf 'service/%s\n' "${name}"
+ fi
+ ;;
+ nodes | deploy | sts)
+ [[ ! -e "${state}/fail-get-${kind}" ]] || { printf 'stub: get %s failed\n' "${kind}" >&2; exit 1; }
+ printf 'stub %s\n' "${kind}"
+ ;;
+ *) printf 'kubectl stub: unsupported get: %s\n' "${original}" >&2; exit 64 ;;
+ esac
+ ;;
+ port-forward)
+ printf '%s\n' "$$" >>"${state}/pf-pids"
+ if [[ -e "${state}/pf-ignores-term" ]]; then trap '' TERM; fi
+ # Present exactly "<path>/kubectl <original argv>" to ps(1) and block
+ # until signalled; the FIFO is opened read-write so cat never sees EOF.
+ exec -a "$0 ${original}" cat 0<>"${state}/pf.fifo"
+ ;;
+ *) printf 'kubectl stub: unsupported call: %s\n' "${original}" >&2; exit 64 ;;
+esac
+EOF_KUBECTL
+
+cat >"${stub_bin}/minikube" <<'EOF_MINIKUBE'
+#!/usr/bin/env bash
+set -euo pipefail
+state="${BRANCH_PROFILE_STUB_STATE:?stub state directory is required}"
+profile=""
+previous=""
+for arg in "$@"; do
+ [[ "${previous}" == -p ]] && profile="${arg}"
+ previous="${arg}"
+done
+pidfiles=0
+if [[ -n "${profile}" && -d "${CACHE_ROOT}/${profile}/pids" ]]; then
+ pidfiles="$(find "${CACHE_ROOT}/${profile}/pids" -name '*.pid' | wc -l | tr -d ' ')"
+fi
+# pidfiles= records how many port-forward records still existed when minikube
+# was called, which pins the clear-records-before-stop ordering.
+printf 'minikube %s pidfiles=%s\n' "$*" "${pidfiles}" >>"${state}/calls.log"
+case " $* " in
+ *" start "*)
+ if [[ -e "${state}/start-switches-context" ]]; then
+ printf '%s\n' "${profile}" >"${state}/current-context"
+ fi
+ ;;
+ *" status "*) exit "$(cat "${state}/minikube-status-rc")" ;;
+esac
+EOF_MINIKUBE
+
+cat >"${stub_bin}/docker" <<'EOF_DOCKER'
+#!/usr/bin/env bash
+set -euo pipefail
+printf 'docker %s\n' "$*" >>"${BRANCH_PROFILE_STUB_STATE:?}/calls.log"
+case "$*" in
+ info) ;;
+ # docker-cli-env.sh verifies the pinned endpoint through the isolated config.
+ 'context inspect --format {{.Endpoints.docker.Host}} default') printf '%s\n' "${DOCKER_HOST:?}" ;;
+ *) printf 'docker stub: unsupported call: %s\n' "$*" >&2; exit 64 ;;
+esac
+EOF_DOCKER
+
+cat >"${stub_bin}/helm" <<'EOF_HELM'
+#!/usr/bin/env bash
+set -euo pipefail
+printf 'helm %s\n' "$*" >>"${BRANCH_PROFILE_STUB_STATE:?}/calls.log"
+EOF_HELM
+
+cat >"${stub_bin}/curl" <<'EOF_CURL'
+#!/usr/bin/env bash
+set -euo pipefail
+state="${BRANCH_PROFILE_STUB_STATE:?stub state directory is required}"
+printf 'curl %s\n' "$*" >>"${state}/calls.log"
+url="${*: -1}"
+if [[ -f "${state}/curl-fail" ]] && grep -Fqx "${url}" "${state}/curl-fail"; then exit 7; fi
+EOF_CURL
+chmod +x "${stub_bin}"/*
+mkfifo "${state}/pf.fifo"
+
+# --- fixture repository -------------------------------------------------------
+# shellcheck source=scripts/tests/lib/minikube-fixture-repo.sh
+. "${ROOT}/scripts/tests/lib/minikube-fixture-repo.sh"
+minikube_test_fixture_repo_init "${ROOT}" "${tmp}/fixture"
+repo="${MINIKUBE_TEST_PROJECT_DIR}"
+mkdir -p "${repo}/scripts" "${repo}/deploy/minikube"
+cp -R "${ROOT}/scripts/minikube" "${repo}/scripts/minikube"
+printf 'fixture deploy file\n' >"${repo}/deploy/minikube/fixture.txt"
+other_worktree="${tmp}/other-worktree"
+mkdir -p "${other_worktree}"
+
+# shellcheck source=scripts/minikube/port-forward-owner.sh
+. "${ROOT}/scripts/minikube/port-forward-owner.sh"
+
+reset_state() {
+ : >"${state}/calls.log"
+ printf '0\n' >"${state}/minikube-status-rc"
+ printf 'other-session-context\n' >"${state}/current-context"
+ printf '%s\n' control-plane/control-ui control-plane/control-api \
+ profiles/external-rest-api rpc-proxy/rpc-proxy >"${state}/services"
+ : >"${state}/reachable"
+ rm -f "${state}/fail-get-deploy" "${state}/curl-fail" "${state}/start-switches-context" \
+ "${state}/pf-ignores-term"
+}
+
+# bp <label> <action> [NAME=value ...]
+bp() {
+ local label="$1" action="$2"
+ shift 2
+ BP_OUT="${out_dir}/${label}.log"
+ BP_RC=0
+ (
+ cd -- "${repo}" &&
+ env PATH="${stub_bin}:${PATH}" \
+ BRANCH_PROFILE_STUB_STATE="${state}" \
+ CACHE_ROOT="${cache_root}" \
+ DOCKER_HOST="unix://${tmp}/docker.sock" \
+ PF_OWNER_TERMINATE_ATTEMPTS=5 PF_OWNER_TERMINATE_DELAY=0.05 \
+ "$@" bash "${BRANCH_PROFILE}" "${action}"
+ ) >"${BP_OUT}" 2>&1 || BP_RC=$?
+}
+
+start_foreign_process() {
+ sleep 600 &
+ FOREIGN_PID=$!
+ printf '%s\n' "${FOREIGN_PID}" >>"${state}/foreign-pids"
+}
+
+dead_pid() {
+ local pid
+ sleep 0 &
+ pid=$!
+ wait "${pid}" 2>/dev/null || true
+ printf '%s\n' "${pid}"
+}
+
+write_control_ui_record() {
+ local pid="$1" start="$2" worktree="$3"
+ pf_owner_write_record_atomic "${pids_dir}/control-ui.pid" "${pid}" "${start}" \
+ "${profile}" "${profile}" "${worktree}" control-plane control-ui \
+ "${control_ui_port}" 3000 || fail "could not write the control-ui fixture record"
+}
+
+# === resolve / preflight ======================================================
+reset_state
+bp resolve resolve
+assert_rc 0 'resolve'
+profile="$(awk -F= '$1 == "PROFILE" { print $2; exit }' "${BP_OUT}")"
+[[ "${profile}" =~ ^clerum-test-minikube-fixture-[0-9a-f]{8}$ ]] ||
+ fail "resolve returned an unexpected profile name: ${profile}"
+ok
+profile_dir="${cache_root}/${profile}"
+pids_dir="${profile_dir}/pids"
+
+bp preflight preflight
+assert_rc 0 'preflight'
+assert_output_has 'preflight: OK' 'preflight'
+assert_file "${profile_dir}/profile.env" 'preflight writes profile.env'
+assert_file "${profile_dir}/ports.env" 'preflight writes ports.env'
+assert_log_has 'docker info' 'preflight probes Docker through the bounded runner'
+control_ui_port="$(awk -F= '$1 == "CONTROL_UI_PORT" { print $2; exit }' "${profile_dir}/ports.env")"
+[[ "${control_ui_port}" =~ ^[0-9]+$ ]] || fail "ports.env has no CONTROL_UI_PORT"
+ok
+
+# === HOST: only 127.0.0.1 is consistent with ports.env and PF records =========
+for bad_host in localhost ::1 '[::1]'; do
+ reset_state
+ bp "host-${bad_host//[^a-z0-9]/_}" stop "HOST=${bad_host}"
+ assert_rc 1 "stop with HOST=${bad_host}"
+ # Witness: the refusal names the only accepted address.
+ assert_output_has 'HOST must be 127.0.0.1' "stop with HOST=${bad_host}"
+ assert_log_lacks 'minikube' "stop with HOST=${bad_host} must refuse before touching minikube"
+done
+
+# === explicit profile outside the branch-scoped namespace =====================
+reset_state
+bp explicit-own resolve "MINIKUBE_PROFILE=${profile}"
+assert_rc 0 'explicit selection of the branch-owned profile'
+assert_output_has "PROFILE=${profile}" 'explicit selection of the branch-owned profile'
+shared_dir="${cache_root}/clerum-dev"
+mkdir -p "${shared_dir}"
+cp "${profile_dir}/ports.env" "${shared_dir}/ports.env"
+awk -v wanted=clerum-dev -F= '$1 == "PROFILE" { print "PROFILE=" wanted; next } { print }' \
+ "${profile_dir}/profile.env" >"${shared_dir}/profile.env"
+bp explicit-shared resolve MINIKUBE_PROFILE=clerum-dev
+assert_rc 1 'explicit selection of clerum-dev'
+assert_output_has 'clerum-dev' 'explicit selection of clerum-dev names the refused profile'
+assert_output_lacks 'PROFILE=clerum-dev' 'explicit selection of clerum-dev must not resolve'
+rm -rf "${shared_dir}"
+
+# === status ===================================================================
+reset_state
+bp status-running status
+assert_rc 0 'status of a running profile'
+assert_log_has "minikube -p ${profile} status" 'status of a running profile'
+assert_log_has "kubectl --context=${profile} --request-timeout=10s get deploy -A" 'status lists deployments'
+
+reset_state
+rm -f "${state}/reachable"
+printf '7\n' >"${state}/minikube-status-rc"
+bp status-stopped status
+assert_rc 7 'status of a stopped profile returns the minikube status code'
+assert_output_has "cluster not reachable for context ${profile}" 'status of a stopped profile'
+assert_log_has "minikube -p ${profile} status" 'status of a stopped profile ran minikube status'
+assert_log_lacks 'get deploy' 'status of a stopped profile must not list deployments'
+
+reset_state
+: >"${state}/fail-get-deploy"
+bp status-kubectl-fails status
+assert_rc_nonzero 'status must fail when listing deployments fails'
+assert_log_has "kubectl --context=${profile} --request-timeout=10s get deploy -A" 'status reached the failing deployment listing'
+
+# === pf / health / stop-pf ====================================================
+reset_state
+bp pf-all pf
+assert_rc 0 'pf with every required service present'
+for name in control-ui control-api external-rest-api rpc-proxy; do
+ assert_file "${pids_dir}/${name}.pid" "pf records ${name}"
+done
+assert_no_file "${pids_dir}/profile-ui.pid" 'pf skips an absent optional service'
+assert_output_has 'SKIP profile-ui' 'pf reports the skipped optional service'
+assert_log_count 'port-forward --address=127.0.0.1' 4 'pf starts one forward per present service'
+pf_owner_read_record "${pids_dir}/control-ui.pid" || fail 'control-ui record is unreadable'
+control_ui_pid="${PF_OWNER_RECORD_PID}"
+assert_alive "${control_ui_pid}" 'the recorded control-ui forward is live'
+
+reset_state
+bp health-ok health
+assert_rc 0 'health with every probe answering'
+assert_log_count 'curl ' 4 'health probes every present service'
+
+reset_state
+printf '%s\n' "http://127.0.0.1:$(awk -F= '$1 == "CONTROL_API_PORT" { print $2; exit }' "${profile_dir}/ports.env")/health" \
+ >"${state}/curl-fail"
+bp health-one-fails health
+assert_rc 1 'health with one failing probe'
+assert_output_has '1 health check(s) failed' 'health counts the failing probe'
+assert_log_count 'curl ' 4 'health still probes every service after one failure'
+
+reset_state
+bp stop-pf-owned stop-pf
+assert_rc 0 'stop-pf of verified records'
+assert_output_has 'stopped or cleared verified control-ui record' 'stop-pf reports each verified record'
+for name in control-ui control-api external-rest-api rpc-proxy; do
+ assert_no_file "${pids_dir}/${name}.pid" "stop-pf removes ${name}"
+done
+assert_dead "${control_ui_pid}" 'stop-pf terminates the verified control-ui forward'
+
+reset_state
+printf '%s\n' control-plane/control-ui control-plane/control-api profiles/external-rest-api >"${state}/services"
+bp pf-required-absent pf
+assert_rc 1 'pf with a required service absent'
+assert_output_has 'FAIL rpc-proxy' 'pf names the absent required service'
+assert_output_has '1 port-forward(s) failed to start' 'pf counts the failure'
+for name in control-ui control-api external-rest-api; do
+ assert_file "${pids_dir}/${name}.pid" "pf still starts ${name} after another forward failed"
+done
+bp stop-pf-after-partial stop-pf
+assert_rc 0 'stop-pf after a partial pf'
+
+# === pf-health clears its own forwards on exit ================================
+reset_state
+bp pf-health pf-health
+assert_rc 0 'pf-health'
+assert_log_count 'port-forward --address=127.0.0.1' 4 'pf-health starts every forward'
+assert_log_count 'curl ' 4 'pf-health probes every forward'
+for name in control-ui control-api external-rest-api rpc-proxy; do
+ assert_no_file "${pids_dir}/${name}.pid" "pf-health clears ${name} on exit"
+done
+
+# === stop / delete ============================================================
+reset_state
+bp stop-pf-before-stop pf
+assert_rc 0 'pf before stop'
+bp stop-clean stop
+assert_rc 0 'stop with verified records'
+assert_log_has "minikube -p ${profile} stop pidfiles=0" 'stop clears every record before minikube stop'
+
+reset_state
+printf '12345\n' >"${pids_dir}/control-ui.pid"
+bp stop-unverified stop
+assert_rc 1 'stop with an unverifiable record'
+assert_log_has "minikube -p ${profile} stop" 'stop still stops minikube when a record cannot be verified'
+assert_output_has "${pids_dir}/control-ui.pid" 'stop names the pidfile to retire by hand'
+assert_file "${pids_dir}/control-ui.pid" 'stop keeps the unverifiable record'
+
+reset_state
+bp delete-unconfirmed delete
+assert_rc 1 'delete without confirmation'
+assert_output_has "Re-run with CONFIRM_DELETE=${profile}" 'delete without confirmation names the confirmation'
+assert_log_lacks 'minikube' 'delete without confirmation must not call minikube'
+assert_file "${pids_dir}/control-ui.pid" 'delete without confirmation leaves records alone'
+
+reset_state
+bp delete-unverified delete "CONFIRM_DELETE=${profile}"
+assert_rc 1 'delete with an unverifiable record'
+assert_log_has "minikube -p ${profile} delete" 'delete still deletes the profile when a record cannot be verified'
+assert_output_has "${pids_dir}/control-ui.pid" 'delete names the pidfile to retire by hand'
+assert_file "${pids_dir}/control-ui.pid" 'delete keeps the unverifiable record'
+rm -f "${pids_dir}/control-ui.pid"
+
+reset_state
+bp delete-pf pf
+assert_rc 0 'pf before delete'
+bp delete-clean delete "CONFIRM_DELETE=${profile}"
+assert_rc 0 'delete with verified records'
+assert_log_has "minikube -p ${profile} delete pidfiles=0" 'delete clears every record before minikube delete'
+
+# === stop-pf keeps records it cannot prove are stale ==========================
+reset_state
+write_control_ui_record "$(dead_pid)" 'Mon Jan 1 00:00:00 2024' "${other_worktree}"
+bp stop-pf-foreign-worktree stop-pf
+assert_rc 1 'stop-pf with another worktree record'
+assert_output_has 'belongs to a different profile, context, worktree, service, or port binding' \
+ 'stop-pf ran the ownership check on the foreign record'
+assert_output_lacks 'retiring' 'stop-pf must not retire another worktree record'
+assert_output_lacks 'stopped or cleared verified control-ui record' 'stop-pf must not report a foreign record as cleared'
+assert_file "${pids_dir}/control-ui.pid" 'stop-pf keeps another worktree record'
+rm -f "${pids_dir}/control-ui.pid"
+
+reset_state
+start_foreign_process
+write_control_ui_record "${FOREIGN_PID}" "$(pf_owner_process_start "${FOREIGN_PID}")" "${repo}"
+bp stop-pf-live-foreign stop-pf
+assert_rc 1 'stop-pf with a live non-kubectl process under an exact-start record'
+assert_output_has 'does not have the exact recorded kubectl argv' 'stop-pf ran the argv check'
+assert_output_lacks 'retiring' 'stop-pf must not retire a record whose process start still matches'
+assert_file "${pids_dir}/control-ui.pid" 'stop-pf keeps the record of a live process it cannot verify'
+assert_alive "${FOREIGN_PID}" 'stop-pf never signals a process it cannot verify'
+rm -f "${pids_dir}/control-ui.pid"
+
+reset_state
+start_foreign_process
+write_control_ui_record "${FOREIGN_PID}" 'Mon Jan 1 00:00:00 2024' "${repo}"
+bp stop-pf-pid-reuse stop-pf
+assert_rc 0 'stop-pf with a reused PID'
+assert_output_has "retiring control-ui record: pid=${FOREIGN_PID}" 'stop-pf reports the PID-reuse retirement'
+assert_output_lacks 'stopped or cleared verified control-ui record' 'a retired record is not reported as verified'
+assert_no_file "${pids_dir}/control-ui.pid" 'stop-pf retires the reused-PID record'
+assert_alive "${FOREIGN_PID}" 'stop-pf does not signal the process that reused the PID'
+
+# === start restores a global context minikube switched ========================
+reset_state
+bp start-keeps-context start
+assert_rc 0 'start that keeps the global context'
+assert_log_has "minikube start -p ${profile} --keep-context" 'start runs minikube start'
+assert_log_has "minikube -p ${profile} status" 'start checks status after a clean start'
+[[ "$(cat "${state}/current-context")" == other-session-context ]] || fail 'start changed the global context'
+ok
+
+reset_state
+: >"${state}/start-switches-context"
+bp start-switches-context start
+assert_rc 1 'start after minikube switched the global context'
+assert_log_has "minikube start -p ${profile} --keep-context" 'start ran minikube start before detecting the switch'
+assert_output_has 'switched the kubectl current-context' 'start reports the switch'
+assert_log_has 'kubectl config use-context other-session-context' 'start restores the previous global context'
+[[ "$(cat "${state}/current-context")" == other-session-context ]] ||
+ fail "start left the global context on $(cat "${state}/current-context")"
+ok
+assert_log_lacks "minikube -p ${profile} status" 'start stops after detecting the switch'
+
+# === prepare-shims: symlinks and the seed allowlist ===========================
+reset_state
+bp prepare-shims prepare-shims
+assert_rc 0 'prepare-shims'
+shims_dir="${profile_dir}/scripts/minikube"
+assert_file "${shims_dir}/seed-test-data.sh" 'prepare-shims copies the seed script'
+assert_file "${profile_dir}/shims.env" 'prepare-shims writes shims.env'
+
+seed_project="${tmp}/seed-project"
+mkdir -p "${seed_project}/scripts/e2e"
+cat >"${seed_project}/scripts/e2e/load-dotenv.sh" <<'EOF_DOTENV'
+dotenv_load_canonical_root() { return 0; }
+EOF_DOTENV
+cat >"${seed_project}/scripts/e2e/admin-credentials.sh" <<'EOF_ADMIN'
+e2e_resolve_admin_password() { printf 'fixture-admin-password\n'; }
+EOF_ADMIN
+cat >"${seed_project}/scripts/e2e/seed-e2e-data.sh" <<'EOF_SEED'
+printf 'CONTEXT=%s ALLOWED_CONTEXTS=%s\n' "${CONTEXT}" "${ALLOWED_CONTEXTS:-<unset>}" >>"${SEED_LOG:?}"
+EOF_SEED
+seed_log="${tmp}/seed.log"
+run_seed_shim() {
+ : >"${seed_log}"
+ env CLERUM_PROJECT_DIR="${seed_project}" SEED_LOG="${seed_log}" SEED_PROFILE=minimal \
+ CONTEXT="$1" bash "${shims_dir}/seed-test-data.sh" >"${out_dir}/seed-$1.log" 2>&1 ||
+ fail "seed shim failed for CONTEXT=$1"
+}
+run_seed_shim "${profile}"
+grep -Fqx "CONTEXT=${profile} ALLOWED_CONTEXTS=${profile}" "${seed_log}" ||
+ fail "seed shim did not authorize the branch profile itself: $(cat "${seed_log}")"
+ok
+for foreign_context in clerum clerum-dev; do
+ run_seed_shim "${foreign_context}"
+ # Witness: the seed ran and recorded this context; the allowlist stayed empty.
+ grep -Fqx "CONTEXT=${foreign_context} ALLOWED_CONTEXTS=<unset>" "${seed_log}" ||
+ fail "seed shim authorized ${foreign_context}: $(cat "${seed_log}")"
+ ok
+done
+
+outside="${tmp}/outside"
+mkdir -p "${outside}/minikube"
+printf 'keep\n' >"${outside}/minikube/keep.txt"
+rm -rf "${profile_dir}/scripts"
+ln -s "${outside}" "${profile_dir}/scripts"
+bp prepare-shims-symlink prepare-shims
+assert_rc 1 'prepare-shims with a symlinked scripts directory'
+assert_output_has 'BRANCH_PROFILE_SHIM_SYMLINK' 'prepare-shims names the symlink refusal'
+assert_file "${outside}/minikube/keep.txt" 'prepare-shims must not delete through a symlinked scripts directory'
+rm -f "${profile_dir}/scripts"
+
+(( ASSERTIONS >= 100 )) || fail "expected at least 100 assertions, ran ${ASSERTIONS}"
+printf 'PASS: branch-profile lifecycle scenarios (%s assertions)\n' "${ASSERTIONS}"
diff --git a/scripts/tests/test-minikube-t2-contract.sh b/scripts/tests/test-minikube-t2-contract.sh
index 24cb4921e..f4cc50844 100755
--- a/scripts/tests/test-minikube-t2-contract.sh
+++ b/scripts/tests/test-minikube-t2-contract.sh
@@ -26,6 +26,7 @@ for file in "$MINIKUBE_DIR/profile-readiness.sh" "$ROOT/scripts/tests/test-minik
"$ROOT/scripts/tests/lib/minikube-fixture-repo.sh" \
"$ROOT/scripts/tests/test-minikube-t2-public-boundary.sh" \
"$ROOT/scripts/tests/test-minikube-t2-scenarios.sh" \
+ "$ROOT/scripts/tests/test-branch-profile-lifecycle.sh" \
"$ROOT/scripts/tests/test-minikube-t2-proxy-runtime.sh" \
"$ROOT/scripts/tests/test-minikube-t2-control-api-runtime.sh" \
"$ROOT/scripts/tests/test-minikube-image-capability-fixture.sh" \
diff --git a/scripts/tests/test-minikube-t2-scenarios.sh b/scripts/tests/test-minikube-t2-scenarios.sh
index d81ecc4b6..10cbc7353 100755
--- a/scripts/tests/test-minikube-t2-scenarios.sh
+++ b/scripts/tests/test-minikube-t2-scenarios.sh
@@ -546,27 +546,17 @@ bash "$ROOT/scripts/tests/test-minikube-t2-process-owner.sh"
grep -Fq 'REUSE_DB=true' "$ROOT/scripts/minikube/t2.sh"
grep -Fq 'CONTROL_DB_RESET_PVC_UID' "$ROOT/scripts/minikube/t2.sh"
-# branch-profile.sh cannot be executed here (it needs a live cluster), so pin the
-# lifecycle contract on the body of each function. Each check reads one function,
-# and first asserts that the body is non-empty so a renamed function fails loudly.
+# branch-profile.sh lifecycle (preflight, start, status, pf, health, pf-health,
+# stop-pf, stop, delete, prepare-shims) is exercised end to end against a
+# fixture repository with PATH stubs for kubectl, minikube, helm, docker and
+# curl; it asserts exit codes, the stub call log and pidfile state.
+bash "$ROOT/scripts/tests/test-branch-profile-lifecycle.sh"
+# The one path the stubs do not reach: a failed stop of an existing record
+# inside start_pf. start_pf runs under `|| failed++`, where errexit is
+# suspended, so it must return explicitly.
BRANCH_PROFILE="$ROOT/scripts/minikube-profiles/branch-profile.sh"
-profile_fn_body() {
- local body
- body="$(awk -v fn="$1" '$0 == fn "() {" { on = 1; next } on && $0 == "}" { exit } on { print }' "$BRANCH_PROFILE")"
- [[ -n "$body" ]] || fail "branch-profile.sh function $1 not found or empty"
- printf '%s\n' "$body"
-}
-[[ "$(profile_fn_body cmd_stop)" == *'cmd_stop_pf'* ]] || fail 'branch-profile-stop must clear port-forward records before minikube stop'
-[[ "$(profile_fn_body cmd_delete)" == *'cmd_stop_pf'* ]] || fail 'branch-profile-delete must clear port-forward records before minikube delete'
-[[ "$(profile_fn_body cmd_pf)" == *'|| failed=$((failed + 1))'* ]] || fail 'branch-profile-pf must attempt every forward before failing'
-[[ "$(profile_fn_body cmd_pf)" == *'(( failed > 0 ))'* ]] || fail 'branch-profile-pf must fail when any forward failed'
-[[ "$(profile_fn_body cmd_health)" == *'|| failed=$((failed + 1))'* ]] || fail 'branch-profile-health must probe every service before failing'
-[[ "$(profile_fn_body cmd_health)" == *'(( failed > 0 ))'* ]] || fail 'branch-profile-health must fail when any probe failed'
-[[ "$(profile_fn_body cmd_status)" == *'|| minikube_status=$?'* ]] || fail 'branch-profile-status must report a stopped cluster instead of aborting under set -e'
-[[ "$(profile_fn_body cmd_status)" != *'|| true'* ]] || fail 'branch-profile-status must not mask kubectl failures'
-[[ "$(profile_fn_body cmd_start)" != *'--context='*'config current-context'* ]] || fail 'branch-profile-start must read the global current-context, not the profile context'
-[[ "$(profile_fn_body cmd_start)" == *'"${after_context}" == "${PROFILE}"'* ]] || fail 'branch-profile-start must fail only when minikube switched the context onto the profile'
-[[ "$(profile_fn_body validate_profile_name)" == *'clerum-[a-z0-9]'* ]] || fail 'branch-profile must positively require the local clerum-* namespace'
-[[ "$(profile_fn_body start_pf)" == *'stop_own_pf'*'|| return 1'* ]] || fail 'start_pf must return explicitly on a failed stop because errexit is suspended under || failed++'
+start_pf_body="$(awk '$0 == "start_pf() {" { on = 1; next } on && $0 == "}" { exit } on { print }' "$BRANCH_PROFILE")"
+[[ -n "$start_pf_body" ]] || fail 'branch-profile.sh function start_pf not found or empty'
+[[ "$start_pf_body" == *'stop_own_pf'*'|| return 1'* ]] || fail 'start_pf must return explicitly on a failed stop because errexit is suspended under || failed++'
printf 'PASS: local Minikube T0/T1/T2 scenario checks\n'
diff --git a/scripts/tests/test-repo-intake-packet.sh b/scripts/tests/test-repo-intake-packet.sh
index aa7d473b1..a17396f33 100755
--- a/scripts/tests/test-repo-intake-packet.sh
+++ b/scripts/tests/test-repo-intake-packet.sh
@@ -84,6 +84,10 @@ run_packet_with_profile() {
)
}
+# A bare "yes"/"no"/"dev" matches any line of the packet, so each value is
+# asserted on its own label row, formatted exactly as the packet's kv() prints it.
+kv_row() { printf '%-30s %s' "$1:" "$2"; }
+
payload_value() {
local payload="$1" key="$2"
awk -F= -v wanted="${key}" '$1 == wanted { sub(/^[^=]*=/, ""); print; exit }' <<<"${payload}"
@@ -141,12 +145,12 @@ fi
assert_contains "${PRIMARY_OUTPUT}" "repo_root:" "primary output includes repo root label"
assert_contains "${PRIMARY_OUTPUT}" "${MAIN_REPO}" "primary output includes primary repo path"
assert_contains "${PRIMARY_OUTPUT}" "branch:" "primary output includes branch label"
-assert_contains "${PRIMARY_OUTPUT}" "dev" "primary output reports branch"
+assert_contains "${PRIMARY_OUTPUT}" "$(kv_row branch dev)" "primary output reports branch"
assert_contains "${PRIMARY_OUTPUT}" "profile_helper_exists:" "primary output includes profile helper label"
-assert_contains "${PRIMARY_OUTPUT}" "yes" "primary output finds profile helper"
+assert_contains "${PRIMARY_OUTPUT}" "$(kv_row profile_helper_exists yes)" "primary output finds profile helper"
assert_contains "${PRIMARY_OUTPUT}" "profile_owner_resolver:" "primary output includes profile owner resolver label"
assert_contains "${PRIMARY_OUTPUT}" "profile_cache_state:" "primary output includes profile cache state"
-assert_contains "${PRIMARY_OUTPUT}" "absent" "primary output reports an uninitialized isolated profile root"
+assert_contains "${PRIMARY_OUTPUT}" "$(kv_row profile_cache_state absent)" "primary output reports an uninitialized isolated profile root"
assert_not_contains "${PRIMARY_OUTPUT}" "SENSITIVE_MARKER_DO_NOT_PRINT" "primary output does not print file contents"
assert_not_contains "${PRIMARY_OUTPUT}" "local-sensitive.txt" "primary output does not print local sensitive filenames"
assert_not_contains "${PRIMARY_OUTPUT}" "unbound variable" "primary output has no shell unbound-variable warnings"
@@ -272,16 +276,39 @@ assert_contains "${DETACHED_OUTPUT}" "repo_root:" "detached output includes repo
assert_contains "${DETACHED_OUTPUT}" "${DETACHED_WT}" "detached output uses current worktree root"
assert_contains "${DETACHED_OUTPUT}" "primary_checkout:" "detached output includes primary checkout label"
assert_contains "${DETACHED_OUTPUT}" "${MAIN_REPO}" "detached output resolves primary checkout"
-# A bare "yes"/"no" matches any line of the packet, so each value is asserted on
-# its own label row, formatted exactly as the packet's kv() prints it.
-kv_row() { printf '%-30s %s' "$1:" "$2"; }
assert_contains "${DETACHED_OUTPUT}" "$(kv_row detached yes)" "detached output reports detached state"
assert_contains "${DETACHED_OUTPUT}" "$(kv_row profile_helper_local no)" "detached output tolerates missing local scripts helper"
assert_contains "${DETACHED_OUTPUT}" "$(kv_row profile_helper_primary yes)" "detached output finds primary scripts helper"
+assert_contains "${DETACHED_OUTPUT}" \
+ "$(kv_row profile_helper_command "make -f ${MAIN_REPO}/scripts/minikube-profiles/branch.mk branch-profile-info")" \
+ "detached output falls back to the primary scripts helper when the worktree has none"
assert_not_contains "${DETACHED_OUTPUT}" "unbound variable" "detached output has no shell unbound-variable warnings"
+# Precedence: when both the worktree and the primary checkout carry the helper,
+# the packet must point at the worktree's own copy, because that is the
+# branch-profile code the branch under test ships.
+LOCAL_HELPER_WT="${TMP_ROOT}/local-helper"
+git -C "${MAIN_REPO}" worktree add -q -b feat/local-helper "${LOCAL_HELPER_WT}" HEAD
+mkdir -p "${LOCAL_HELPER_WT}/scripts/minikube-profiles"
+printf '# worktree-owned helper\n' >"${LOCAL_HELPER_WT}/scripts/minikube-profiles/branch.mk"
+LOCAL_HELPER_ROOT="${TMP_ROOT}/local-helper-profiles"
+mkdir -p "${LOCAL_HELPER_ROOT}"
+LOCAL_HELPER_OUTPUT="$(run_packet "${LOCAL_HELPER_WT}" "${LOCAL_HELPER_ROOT}" 2>&1)"
+LOCAL_HELPER_STATUS=$?
+if [[ "${LOCAL_HELPER_STATUS}" -eq 0 || "${LOCAL_HELPER_STATUS}" -eq 2 ]]; then
+ pass "repo intake packet runs in a worktree that carries its own helper"
+else
+ fail "repo intake packet runs in a worktree that carries its own helper"
+ echo "${LOCAL_HELPER_OUTPUT}"
+fi
+assert_contains "${LOCAL_HELPER_OUTPUT}" "$(kv_row profile_helper_local yes)" "local-helper output finds the worktree helper"
+assert_contains "${LOCAL_HELPER_OUTPUT}" "$(kv_row profile_helper_primary yes)" "local-helper output also finds the primary helper"
+assert_contains "${LOCAL_HELPER_OUTPUT}" \
+ "$(kv_row profile_helper_command "make -f ${LOCAL_HELPER_WT}/scripts/minikube-profiles/branch.mk branch-profile-info")" \
+ "local-helper output prefers the worktree helper over the primary one"
+
# A run that skipped its assertions must not exit 0.
-if (( PASSED < 41 )); then
- fail "expected at least 41 passing assertions, got ${PASSED}"
+if (( PASSED < 46 )); then
+ fail "expected at least 46 passing assertions, got ${PASSED}"
fi
exit "${FAIL}"