Skip to content

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

TypeScript

test(e2e): prove HCC readiness during fleet convergence

Alfredo Lopezf2e8fa8b5749
diff --git a/Makefile b/Makefile
index ca0e77f5a..6921b4e98 100644
--- a/Makefile
+++ b/Makefile
@@ -852,7 +852,14 @@ test-e2e-hcc-communicationchannel-watch-recovery: ## Run isolated minikube HCC w
.PHONY: test-e2e-hcc-readiness-bootstrap
test-e2e-hcc-readiness-bootstrap: ## Prove HCC readiness while its initial Host fleet pass remains active
@echo "Running HCC initial-fleet readiness gate..."
- E2E_HCC_READINESS_FAULT_INJECTION=1 KUBECONTEXT=$(E2E_KUBECONTEXT) bash scripts/e2e/e2e-hcc-readiness-bootstrap.sh
+ @test -n "$(E2E_EXPECTED_PRE_GATE_GATE)" || { echo "Set E2E_EXPECTED_PRE_GATE_GATE to the gate recorded by the branch-owned pre-gate sync" >&2; exit 1; }
+ E2E_HCC_READINESS_FAULT_INJECTION=1 E2E_EXPECTED_PRE_GATE_GATE="$(E2E_EXPECTED_PRE_GATE_GATE)" MINIKUBE_PROFILE=$(E2E_KUBECONTEXT) KUBECONTEXT=$(E2E_KUBECONTEXT) bash scripts/e2e/e2e-hcc-readiness-bootstrap.sh
+
+.PHONY: test-e2e-hcc-mcp-context-readiness
+test-e2e-hcc-mcp-context-readiness: ## Prove HCC readiness during exact MCP/Context/NetworkPolicy initial convergence
+ @echo "Running HCC MCP/Context/NetworkPolicy readiness gate..."
+ @test -n "$(E2E_EXPECTED_PRE_GATE_GATE)" || { echo "Set E2E_EXPECTED_PRE_GATE_GATE to the gate recorded by the branch-owned pre-gate sync" >&2; exit 1; }
+ E2E_HCC_MCP_READINESS_FAULT_INJECTION=1 E2E_EXPECTED_PRE_GATE_GATE="$(E2E_EXPECTED_PRE_GATE_GATE)" MINIKUBE_PROFILE=$(E2E_KUBECONTEXT) KUBECONTEXT=$(E2E_KUBECONTEXT) bash scripts/e2e/e2e-hcc-mcp-context-readiness.sh
.PHONY: test-e2e-stateless-multinode
test-e2e-stateless-multinode: ## Run stateless multi-node lane (opt-in: STATELESS_MULTINODE_GATE=1; needs >=2 schedulable nodes; exit 3 = cross-node UNVERIFIED)
diff --git a/scripts/e2e/e2e-hcc-mcp-context-readiness.sh b/scripts/e2e/e2e-hcc-mcp-context-readiness.sh
new file mode 100755
index 000000000..3de5c5b64
--- /dev/null
+++ b/scripts/e2e/e2e-hcc-mcp-context-readiness.sh
@@ -0,0 +1,1109 @@
+#!/usr/bin/env bash
+# Proves that HCC readiness is independent from the exact McpServer ->
+# external-egress -> runtime -> Context NetworkPolicy initial convergence path.
+#
+# The gate runs only on an exact-HEAD, branch-owned Minikube profile. It routes
+# HCC DNS through an isolated in-cluster proxy that forwards every query except
+# one fixture hostname. Holding that single A query blocks real initial
+# McpServer external-egress reconciliation without a production test hook.
+# While the query is held, the gate proves readiness and discovery, applies a
+# real Context watch update, and requires that Context's three NetworkPolicies
+# to converge independently of the blocked McpServer entity. It then releases
+# DNS and proves eventual McpServer runtime convergence.
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+# shellcheck source=scripts/e2e/e2e-lib.sh
+# shellcheck disable=SC1091
+source "${SCRIPT_DIR}/e2e-lib.sh"
+# shellcheck source=scripts/e2e/_lib/hcc-watch-recovery-lock.sh
+# shellcheck disable=SC1091
+source "${SCRIPT_DIR}/_lib/hcc-watch-recovery-lock.sh"
+
+[ -n "$E2E_KUBECONTEXT" ] || {
+ echo "KUBECONTEXT or E2E_K8S_CONTEXT must select an explicit branch-scoped minikube context." >&2
+ exit 1
+}
+is_branch_scoped_e2e_context "$E2E_KUBECONTEXT" || {
+ echo "Refusing HCC MCP readiness fault injection on non-branch context '${E2E_KUBECONTEXT}'." >&2
+ exit 1
+}
+require_safe_kube_context
+[ "${E2E_HCC_MCP_READINESS_FAULT_INJECTION:-0}" = 1 ] || {
+ echo "Set E2E_HCC_MCP_READINESS_FAULT_INJECTION=1 to acknowledge temporary HCC DNS fault injection." >&2
+ exit 1
+}
+command -v jq >/dev/null 2>&1 || {
+ echo "jq is required" >&2
+ exit 1
+}
+
+HCC_NS="${HCC_NS:-control-plane}"
+HCC_DEPLOY="${HCC_DEPLOY:-host-context-controller}"
+MCP_NS="${MCP_SERVER_NS:-mcp-server}"
+HOST_NS="${MCP_HOST_NS:-mcp-host}"
+RPC_PROXY_NS="${RPC_PROXY_NS:-rpc-proxy}"
+RUN_ID="$(date +%s)-$$"
+SUITE_NAME="hcc-mcp-readiness"
+RUN_LABEL="$(truncate_rfc1123 "$RUN_ID")"
+MCP_NAME="$(truncate_rfc1123 "e2e-hcc-mcp-${RUN_ID}")"
+CONTEXT_NAME="$(truncate_rfc1123 "e2e-hcc-context-${RUN_ID}")"
+CONTEXT_ID="$CONTEXT_NAME"
+TARGET_DNS="$(truncate_rfc1123 "hcc-readiness-${RUN_ID}").example.com"
+DNS_BLOCKER_NAME="$(truncate_rfc1123 "e2e-hcc-dns-${RUN_ID}")"
+DNS_BLOCKER_POLICY="$(truncate_rfc1123 "${DNS_BLOCKER_NAME}-policy")"
+HCC_DNS_POLICY="$(truncate_rfc1123 "${DNS_BLOCKER_NAME}-from-hcc")"
+CONTEXT_POLICY="ctx-${CONTEXT_ID}-${MCP_NAME}"
+CONTEXT_EGRESS_POLICY="${CONTEXT_POLICY}-egress"
+RPC_EGRESS_POLICY="rpc-egress-${CONTEXT_ID}-${MCP_NAME}"
+MANAGED_BY_LABEL="clerum.io/managed-by"
+MANAGED_BY_VALUE="host-context-controller"
+MCP_SERVER_LABEL="clerum.io/mcpserver"
+POLICY_TYPE_LABEL="clerum.io/policy-type"
+CONTEXT_LABEL="clerum.io/context"
+EXTERNAL_EGRESS_CIDR="93.184.216.34/32"
+EXTERNAL_EGRESS_PORT=443
+ORIGINAL_REPLICAS=""
+ORIGINAL_DNS_POLICY=""
+ORIGINAL_DNS_CONFIG=""
+DNS_BLOCKER_IP=""
+UPSTREAM_DNS_IP=""
+NEW_HCC_POD=""
+HCC_UID=""
+HCC_RESTARTS=""
+HCC_MUTATED=0
+DNS_BLOCKER_CREATED=0
+MCP_CREATED=0
+CONTEXT_CREATED=0
+# Read and mutated by the sourced compare-and-swap lock helper.
+# shellcheck disable=SC2034
+HCC_GATE_LOCK_ACQUIRED=0
+# shellcheck disable=SC2034
+HCC_GATE_LOCK_NAME=""
+# shellcheck disable=SC2034
+HCC_GATE_LOCK_UID=""
+# shellcheck disable=SC2034
+HCC_GATE_FINALIZATION_FAILURE=""
+
+die() {
+ if [ -n "$NEW_HCC_POD" ]; then
+ echo "Recent HCC logs from ${NEW_HCC_POD}:" >&2
+ kctl logs "pod/${NEW_HCC_POD}" -n "$HCC_NS" -c host-context-controller \
+ --tail=300 >&2 || true
+ fi
+ if [ "$DNS_BLOCKER_CREATED" = 1 ]; then
+ echo "Recent DNS blocker logs:" >&2
+ kctl logs "deployment/${DNS_BLOCKER_NAME}" -n "$HCC_NS" --tail=120 >&2 || true
+ fi
+ fail "$*"
+ exit 1
+}
+
+wait_until() {
+ local timeout=$1 description=$2
+ shift 2
+ local elapsed=0
+ while [ "$elapsed" -lt "$timeout" ]; do
+ "$@" && return 0
+ sleep 1
+ elapsed=$((elapsed + 1))
+ done
+ echo "Timed out after ${timeout}s waiting for ${description}" >&2
+ return 1
+}
+
+profile_env_value() {
+ local key=$1 file=$2
+ awk -v key="$key" '
+ index($0, key "=") == 1 {
+ print substr($0, length(key) + 2)
+ exit
+ }
+ ' "$file"
+}
+
+running_hcc_pod() {
+ local rows
+ rows="$(kctl get pods -n "$HCC_NS" -l "app=${HCC_DEPLOY}" \
+ --field-selector=status.phase=Running \
+ -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.metadata.uid}{"\t"}{.status.containerStatuses[?(@.name=="host-context-controller")].restartCount}{"\t"}{.metadata.deletionTimestamp}{"\n"}{end}' \
+ 2>/dev/null)" || return 1
+ awk -F '\t' '$1 != "" && $4 == "" { print $1; exit }' <<<"$rows"
+}
+
+hcc_log_contains() {
+ local marker=$1 logs
+ [ -n "$NEW_HCC_POD" ] || return 1
+ logs="$(kctl logs "pod/${NEW_HCC_POD}" -n "$HCC_NS" \
+ -c host-context-controller 2>/dev/null)" || return 1
+ grep -Fq "$marker" <<<"$logs"
+}
+
+hcc_log_matches() {
+ local pattern=$1 logs
+ [ -n "$NEW_HCC_POD" ] || return 1
+ logs="$(kctl logs "pod/${NEW_HCC_POD}" -n "$HCC_NS" \
+ -c host-context-controller 2>/dev/null)" || return 1
+ grep -Eq "$pattern" <<<"$logs"
+}
+
+dns_log_contains() {
+ local marker=$1 logs
+ logs="$(kctl logs "deployment/${DNS_BLOCKER_NAME}" -n "$HCC_NS" 2>/dev/null)" ||
+ return 1
+ grep -Fq "$marker" <<<"$logs"
+}
+
+startup_convergence_window_is_clean() {
+ ! hcc_log_contains "Initial NetworkPolicy background reconciliation failed:" &&
+ ! hcc_log_contains "Scheduling initial NetworkPolicy background convergence retry" &&
+ ! hcc_log_contains "NetworkPolicy reconciliation failed for context ${CONTEXT_NAME}:" &&
+ ! hcc_log_contains \
+ "Initial external egress reconciliation failed for ${MCP_NS}/${MCP_NAME};" &&
+ ! hcc_log_matches \
+ "Scheduling external egress retry [0-9]+/[0-9]+ for McpServer \"${MCP_NAME}\"" &&
+ ! hcc_log_contains \
+ "External egress retry exhausted for McpServer \"${MCP_NAME}\" in namespace \"${MCP_NS}\""
+}
+
+hcc_identity_is_stable() {
+ local row uid restarts
+ row="$(kctl get pod "$NEW_HCC_POD" -n "$HCC_NS" \
+ -o jsonpath='{.metadata.uid}{" "}{.status.containerStatuses[?(@.name=="host-context-controller")].restartCount}' \
+ 2>/dev/null)" || return 1
+ read -r uid restarts <<<"$row"
+ [ "$uid" = "$HCC_UID" ] && [ "$restarts" = "$HCC_RESTARTS" ]
+}
+
+hcc_kubernetes_readiness_is_exact() {
+ [ -n "$NEW_HCC_POD" ] && [ -n "$HCC_UID" ] || return 1
+ kctl get pod "$NEW_HCC_POD" -n "$HCC_NS" -o json 2>/dev/null |
+ jq -e --arg uid "$HCC_UID" '
+ .metadata.uid == $uid and
+ any(.status.conditions[]?; .type == "Ready" and .status == "True") and
+ any(.status.containerStatuses[]?;
+ .name == "host-context-controller" and .ready == true
+ )
+ ' >/dev/null || return 1
+ kctl get deployment "$HCC_DEPLOY" -n "$HCC_NS" -o json 2>/dev/null |
+ jq -e '
+ .status.observedGeneration == .metadata.generation and
+ (.spec.replicas // 0) == 1 and
+ (.status.updatedReplicas // 0) == 1 and
+ (.status.readyReplicas // 0) == 1 and
+ (.status.availableReplicas // 0) == 1 and
+ (.status.unavailableReplicas // 0) == 0
+ ' >/dev/null
+}
+
+resource_absent() {
+ local kind=$1 name=$2 namespace=$3 found
+ found="$(
+ kctl get "$kind" "$name" -n "$namespace" --ignore-not-found -o name 2>/dev/null
+ )" || return 1
+ [ -z "$found" ]
+}
+
+fixture_mcp_runtime_absent() {
+ local external_egress_policies
+ resource_absent deployment "$MCP_NAME" "$MCP_NS" &&
+ resource_absent service "$MCP_NAME" "$MCP_NS" || return 1
+ external_egress_policies="$(
+ kctl get networkpolicy -n "$MCP_NS" \
+ -l "${MCP_SERVER_LABEL}=${MCP_NAME},${POLICY_TYPE_LABEL}=external-egress" \
+ -o name 2>/dev/null
+ )" || return 1
+ [ -z "$external_egress_policies" ]
+}
+
+fixture_mcp_convergence_absent() {
+ fixture_mcp_runtime_absent &&
+ kctl get mcpserver "$MCP_NAME" -n "$MCP_NS" -o json 2>/dev/null |
+ jq -e '
+ any(.status.conditions[]?; .type == "Ready" and .status == "True") | not
+ ' >/dev/null
+}
+
+context_policies_absent() {
+ resource_absent networkpolicy "$CONTEXT_POLICY" "$MCP_NS" &&
+ resource_absent networkpolicy "$CONTEXT_EGRESS_POLICY" "$HOST_NS" &&
+ resource_absent networkpolicy "$RPC_EGRESS_POLICY" "$RPC_PROXY_NS"
+}
+
+context_policies_converged() {
+ kctl get networkpolicy "$CONTEXT_POLICY" -n "$MCP_NS" -o json |
+ jq -e \
+ --arg contextId "$CONTEXT_ID" \
+ --arg contextName "$CONTEXT_NAME" \
+ --arg server "$MCP_NAME" \
+ --arg hostNs "$HOST_NS" \
+ --arg rpcNs "$RPC_PROXY_NS" \
+ --arg mcpNs "$MCP_NS" \
+ --arg managedByLabel "$MANAGED_BY_LABEL" \
+ --arg managedByValue "$MANAGED_BY_VALUE" \
+ --arg contextLabel "$CONTEXT_LABEL" \
+ --arg serverLabel "$MCP_SERVER_LABEL" \
+ --arg policyTypeLabel "$POLICY_TYPE_LABEL" '
+ .metadata.labels[$managedByLabel] == $managedByValue and
+ .metadata.labels[$policyTypeLabel] == "context-allow" and
+ .metadata.labels[$contextLabel] == $contextId and
+ .metadata.labels[$serverLabel] == $server and
+ .spec.podSelector.matchLabels[$serverLabel] == $server and
+ .spec.policyTypes == ["Ingress"] and
+ (.spec.ingress | length) == 1 and
+ .spec.ingress[0].ports == [{port: 3000, protocol: "TCP"}] and
+ (.spec.ingress[0].from | length) == 3 and
+ any(.spec.ingress[0].from[];
+ .namespaceSelector.matchLabels["kubernetes.io/metadata.name"] == $hostNs and
+ .podSelector.matchLabels[$managedByLabel] == $managedByValue and
+ .podSelector.matchLabels[$contextLabel] == $contextName
+ ) and
+ any(.spec.ingress[0].from[];
+ .namespaceSelector.matchLabels["kubernetes.io/metadata.name"] == $rpcNs and
+ .podSelector.matchLabels.app == "rpc-proxy"
+ ) and
+ any(.spec.ingress[0].from[];
+ .namespaceSelector.matchLabels["kubernetes.io/metadata.name"] == $mcpNs and
+ .podSelector.matchLabels.app == "mcp-proxy"
+ )
+ ' >/dev/null || return 1
+ kctl get networkpolicy "$CONTEXT_EGRESS_POLICY" -n "$HOST_NS" -o json |
+ jq -e \
+ --arg contextId "$CONTEXT_ID" \
+ --arg contextName "$CONTEXT_NAME" \
+ --arg server "$MCP_NAME" \
+ --arg mcpNs "$MCP_NS" \
+ --arg managedByLabel "$MANAGED_BY_LABEL" \
+ --arg managedByValue "$MANAGED_BY_VALUE" \
+ --arg contextLabel "$CONTEXT_LABEL" \
+ --arg serverLabel "$MCP_SERVER_LABEL" \
+ --arg policyTypeLabel "$POLICY_TYPE_LABEL" '
+ .metadata.labels[$managedByLabel] == $managedByValue and
+ .metadata.labels[$policyTypeLabel] == "context-allow" and
+ .metadata.labels[$contextLabel] == $contextId and
+ .metadata.labels[$serverLabel] == $server and
+ .spec.podSelector.matchLabels[$managedByLabel] == $managedByValue and
+ .spec.podSelector.matchLabels[$contextLabel] == $contextName and
+ .spec.policyTypes == ["Egress"] and
+ (.spec.egress | length) == 1 and
+ .spec.egress[0].ports == [{port: 3000, protocol: "TCP"}] and
+ (.spec.egress[0].to | length) == 1 and
+ .spec.egress[0].to[0].namespaceSelector.matchLabels[
+ "kubernetes.io/metadata.name"
+ ] == $mcpNs and
+ .spec.egress[0].to[0].podSelector.matchLabels[$serverLabel] == $server
+ ' >/dev/null || return 1
+ kctl get networkpolicy "$RPC_EGRESS_POLICY" -n "$RPC_PROXY_NS" -o json |
+ jq -e \
+ --arg contextId "$CONTEXT_ID" \
+ --arg server "$MCP_NAME" \
+ --arg mcpNs "$MCP_NS" \
+ --arg managedByLabel "$MANAGED_BY_LABEL" \
+ --arg managedByValue "$MANAGED_BY_VALUE" \
+ --arg contextLabel "$CONTEXT_LABEL" \
+ --arg serverLabel "$MCP_SERVER_LABEL" \
+ --arg policyTypeLabel "$POLICY_TYPE_LABEL" '
+ .metadata.labels[$managedByLabel] == $managedByValue and
+ .metadata.labels[$policyTypeLabel] == "rpc-proxy-egress" and
+ .metadata.labels[$contextLabel] == $contextId and
+ .metadata.labels[$serverLabel] == $server and
+ .spec.podSelector.matchLabels.app == "rpc-proxy" and
+ .spec.policyTypes == ["Egress"] and
+ (.spec.egress | length) == 1 and
+ .spec.egress[0].ports == [{port: 3000, protocol: "TCP"}] and
+ (.spec.egress[0].to | length) == 1 and
+ .spec.egress[0].to[0].namespaceSelector.matchLabels[
+ "kubernetes.io/metadata.name"
+ ] == $mcpNs and
+ .spec.egress[0].to[0].podSelector.matchLabels[$serverLabel] == $server
+ ' >/dev/null
+}
+
+external_egress_policy_converged() {
+ kctl get networkpolicy -n "$MCP_NS" \
+ -l "${MCP_SERVER_LABEL}=${MCP_NAME},${POLICY_TYPE_LABEL}=external-egress" \
+ -o json |
+ jq -e \
+ --arg server "$MCP_NAME" \
+ --arg cidr "$EXTERNAL_EGRESS_CIDR" \
+ --arg managedByLabel "$MANAGED_BY_LABEL" \
+ --arg managedByValue "$MANAGED_BY_VALUE" \
+ --arg serverLabel "$MCP_SERVER_LABEL" \
+ --arg policyTypeLabel "$POLICY_TYPE_LABEL" \
+ --argjson port "$EXTERNAL_EGRESS_PORT" '
+ (.items | length) == 1 and
+ .items[0].metadata.labels[$managedByLabel] == $managedByValue and
+ .items[0].metadata.labels[$policyTypeLabel] == "external-egress" and
+ .items[0].metadata.labels[$serverLabel] == $server and
+ .items[0].spec.podSelector.matchLabels[$serverLabel] == $server and
+ .items[0].spec.policyTypes == ["Egress"] and
+ (.items[0].spec.egress | length) == 1 and
+ .items[0].spec.egress[0].ports == [{port: $port, protocol: "TCP"}] and
+ (.items[0].spec.egress[0].to | length) == 1 and
+ .items[0].spec.egress[0].to[0].ipBlock == {cidr: $cidr}
+ ' >/dev/null
+}
+
+fixture_resources_absent() {
+ fixture_mcp_runtime_absent && context_policies_absent
+}
+
+baseline_policies_exist() {
+ kctl get networkpolicy "deny-all-${MCP_NS}" -n "$MCP_NS" >/dev/null 2>&1 &&
+ kctl get networkpolicy "allow-dns-egress-${MCP_NS}" -n "$MCP_NS" >/dev/null 2>&1 &&
+ kctl get networkpolicy allow-host-context-controller-api -n "$MCP_NS" >/dev/null 2>&1
+}
+
+context_watch_has_latest_spec() {
+ kctl get context "$CONTEXT_NAME" -n "$MCP_NS" -o json |
+ jq -e --arg server "$MCP_NAME" '.spec.mcpServers == [$server]' >/dev/null
+}
+
+fixture_converged() {
+ local desired available
+ desired="$(kctl get deployment "$MCP_NAME" -n "$MCP_NS" \
+ -o jsonpath='{.spec.replicas}' 2>/dev/null)" || return 1
+ available="$(kctl get deployment "$MCP_NAME" -n "$MCP_NS" \
+ -o jsonpath='{.status.availableReplicas}' 2>/dev/null)" || return 1
+ [ "${desired:-0}" -ge 1 ] && [ "${available:-0}" -ge 1 ] || return 1
+ kctl get service "$MCP_NAME" -n "$MCP_NS" >/dev/null 2>&1 || return 1
+ kctl get mcpserver "$MCP_NAME" -n "$MCP_NS" -o json |
+ jq -e 'any(.status.conditions[]?; .type == "Ready" and .status == "True")' >/dev/null ||
+ return 1
+ external_egress_policy_converged || return 1
+ context_policies_converged
+}
+
+probe_hcc_during_block() {
+ local probe_script
+ probe_script="$(cat <<'NODE'
+const http = require('http');
+const expected = process.argv[1];
+function get(path) {
+ return new Promise((resolve, reject) => {
+ const request = http.get({host: '127.0.0.1', port: 8081, path}, response => {
+ let body = '';
+ response.setEncoding('utf8');
+ response.on('data', chunk => { body += chunk; });
+ response.on('end', () => resolve({status: response.statusCode, body}));
+ });
+ request.setTimeout(5000, () => request.destroy(new Error('timeout')));
+ request.once('error', reject);
+ });
+}
+(async () => {
+ const ready = await get('/ready');
+ const readyBody = JSON.parse(ready.body);
+ if (ready.status !== 200 || readyBody.ready !== true) {
+ throw new Error('readiness unavailable: ' + ready.status + ' ' + ready.body);
+ }
+ const discovery = await get('/api/v1/mcpservers');
+ const discoveryBody = JSON.parse(discovery.body);
+ const fixture = discoveryBody.servers?.find(server => server.name === expected);
+ if (discovery.status !== 200 || !fixture) {
+ throw new Error('fixture missing from discovery: ' + discovery.status + ' ' + discovery.body);
+ }
+ console.log(JSON.stringify({
+ readyStatus: ready.status,
+ discoveryStatus: discovery.status,
+ fixture: fixture.name,
+ fixtureReady: fixture.status?.ready ?? null
+ }));
+})().catch(error => { console.error(error.message); process.exit(1); });
+NODE
+)"
+ kctl exec "pod/${NEW_HCC_POD}" -n "$HCC_NS" -c host-context-controller -- \
+ node -e "$probe_script" "$MCP_NAME"
+}
+
+probe_hcc_final_context() {
+ local probe_script
+ probe_script="$(cat <<'NODE'
+const http = require('http');
+const context = process.argv[1];
+const expected = process.argv[2];
+function get(path) {
+ return new Promise((resolve, reject) => {
+ const request = http.get({host: '127.0.0.1', port: 8081, path}, response => {
+ let body = '';
+ response.setEncoding('utf8');
+ response.on('data', chunk => { body += chunk; });
+ response.on('end', () => resolve({status: response.statusCode, body}));
+ });
+ request.setTimeout(5000, () => request.destroy(new Error('timeout')));
+ request.once('error', reject);
+ });
+}
+(async () => {
+ const ready = await get('/ready');
+ const scoped = await get('/api/v1/mcpservers/context/' + encodeURIComponent(context));
+ const body = JSON.parse(scoped.body);
+ const fixture = body.servers?.find(server => server.name === expected);
+ if (ready.status !== 200 || JSON.parse(ready.body).ready !== true) {
+ throw new Error('readiness regressed: ' + ready.status + ' ' + ready.body);
+ }
+ if (scoped.status !== 200 || !fixture || fixture.status?.ready !== true) {
+ throw new Error('latest Context did not converge in discovery: ' + scoped.status + ' ' + scoped.body);
+ }
+ console.log(JSON.stringify({
+ readyStatus: ready.status,
+ scopedDiscoveryStatus: scoped.status,
+ contextRef: body.contextRef,
+ fixture: fixture.name,
+ fixtureReady: fixture.status.ready
+ }));
+})().catch(error => { console.error(error.message); process.exit(1); });
+NODE
+)"
+ kctl exec "pod/${NEW_HCC_POD}" -n "$HCC_NS" -c host-context-controller -- \
+ node -e "$probe_script" "$CONTEXT_NAME" "$MCP_NAME"
+}
+
+probe_hcc_ready_pod() {
+ local pod
+ pod="$(ready_pod_name "$HCC_NS" "app=${HCC_DEPLOY}")" || return 1
+ kctl exec "pod/${pod}" -n "$HCC_NS" -c host-context-controller -- \
+ node -e '
+ const http = require("node:http");
+ const request = http.get(
+ {host: "127.0.0.1", port: 8081, path: "/ready"},
+ response => {
+ let body = "";
+ response.setEncoding("utf8");
+ response.on("data", chunk => { body += chunk; });
+ response.on("end", () => {
+ let parsed;
+ try { parsed = JSON.parse(body); } catch { process.exit(2); }
+ process.exit(response.statusCode === 200 && parsed?.ready === true ? 0 : 3);
+ });
+ }
+ );
+ request.setTimeout(5000, () => request.destroy(new Error("timeout")));
+ request.once("error", () => process.exit(4));
+ ' >/dev/null 2>&1
+}
+
+hcc_restore_is_verified() {
+ local deployment
+ deployment="$(kctl get deployment "$HCC_DEPLOY" -n "$HCC_NS" -o json)" || return 1
+ jq -e \
+ --arg dnsPolicy "$ORIGINAL_DNS_POLICY" \
+ --argjson replicas "${ORIGINAL_REPLICAS:-1}" '
+ .spec.replicas == $replicas and
+ (.status.readyReplicas // 0) == $replicas and
+ (.status.availableReplicas // 0) == $replicas and
+ (.spec.template.spec.dnsPolicy // "ClusterFirst") == $dnsPolicy and
+ (.spec.template.spec.dnsConfig // null) == null
+ ' <<<"$deployment" >/dev/null || return 1
+ probe_hcc_ready_pod
+}
+
+release_dns_blocker() {
+ local release_script
+ release_script="$(cat <<'NODE'
+const http = require('http');
+const request = http.request(
+ {host: '127.0.0.1', port: 8090, path: '/release', method: 'POST'},
+ response => {
+ response.resume();
+ response.on('end', () => process.exit(response.statusCode === 200 ? 0 : 2));
+ }
+);
+request.setTimeout(5000, () => request.destroy(new Error('timeout')));
+request.once('error', error => { console.error(error.message); process.exit(3); });
+request.end();
+NODE
+)"
+ kctl exec "deployment/${DNS_BLOCKER_NAME}" -n "$HCC_NS" -c dns-blocker -- \
+ node -e "$release_script"
+}
+
+delete_dns_blocker_fixture() {
+ local failed=0
+ kctl delete networkpolicy "$HCC_DNS_POLICY" "$DNS_BLOCKER_POLICY" -n "$HCC_NS" \
+ --ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 || failed=1
+ kctl delete service "$DNS_BLOCKER_NAME" -n "$HCC_NS" \
+ --ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 || failed=1
+ kctl delete deployment "$DNS_BLOCKER_NAME" -n "$HCC_NS" \
+ --ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 || failed=1
+ [ "$failed" = 0 ]
+}
+
+delete_residual_fixture_runtime() {
+ local failed=0
+ kctl delete deployment "$MCP_NAME" -n "$MCP_NS" \
+ --ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 || failed=1
+ kctl delete service "$MCP_NAME" -n "$MCP_NS" \
+ --ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 || failed=1
+ kctl delete configmap "${MCP_NAME}-nginx-conf" -n "$MCP_NS" \
+ --ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 || failed=1
+ kctl delete networkpolicy "$CONTEXT_POLICY" -n "$MCP_NS" \
+ --ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 || failed=1
+ kctl delete networkpolicy "$CONTEXT_EGRESS_POLICY" -n "$HOST_NS" \
+ --ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 || failed=1
+ kctl delete networkpolicy "$RPC_EGRESS_POLICY" -n "$RPC_PROXY_NS" \
+ --ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 || failed=1
+ kctl delete networkpolicy -n "$MCP_NS" -l "${MCP_SERVER_LABEL}=${MCP_NAME}" \
+ --ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 || failed=1
+ [ "$failed" = 0 ]
+}
+
+suite_resources_absent() {
+ local namespaced cluster_crds
+ namespaced="$(kctl get deployment,service,networkpolicy -A \
+ -l "e2e.clerum.io/suite=${SUITE_NAME}" -o name 2>/dev/null)" || return 1
+ cluster_crds="$(
+ kctl get mcpserver,context -A -l "e2e.clerum.io/suite=${SUITE_NAME}" \
+ -o name 2>/dev/null
+ )" || return 1
+ [ -z "$namespaced$cluster_crds" ]
+}
+
+print_repair_instructions() {
+ cat >&2 <<EOF
+HCC MCP readiness gate cleanup could not restore a verified clean state.
+Context: ${E2E_KUBECONTEXT}
+HCC: ${HCC_NS}/${HCC_DEPLOY}
+DNS blocker: ${HCC_NS}/${DNS_BLOCKER_NAME}
+Fixtures: ${MCP_NS}/${MCP_NAME}, ${MCP_NS}/${CONTEXT_NAME}
+
+Inspect before changing anything:
+ kubectl --context=${E2E_KUBECONTEXT} -n ${HCC_NS} get deployment ${HCC_DEPLOY} -o yaml
+ kubectl --context=${E2E_KUBECONTEXT} get deployment,service,networkpolicy -A -l e2e.clerum.io/suite=${SUITE_NAME}
+ kubectl --context=${E2E_KUBECONTEXT} get mcpserver,context -A -l e2e.clerum.io/suite=${SUITE_NAME}
+
+Do not remove the HCC gate lock until HCC health and fixture absence are verified.
+EOF
+}
+
+cleanup() {
+ local status=$? cleanup_failed=0 restore_ok=1 restore_patch
+ trap - EXIT
+ set +e
+
+ if [ "$HCC_MUTATED" = 1 ]; then
+ kctl scale deployment "$HCC_DEPLOY" -n "$HCC_NS" --replicas=0 >/dev/null 2>&1 ||
+ restore_ok=0
+ kctl wait pod -n "$HCC_NS" -l "app=${HCC_DEPLOY}" --for=delete \
+ --timeout=120s >/dev/null 2>&1 || restore_ok=0
+ fi
+
+ if [ "$CONTEXT_CREATED" = 1 ]; then
+ kctl delete context "$CONTEXT_NAME" -n "$MCP_NS" \
+ --ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 ||
+ cleanup_failed=1
+ fi
+ if [ "$MCP_CREATED" = 1 ]; then
+ kctl delete mcpserver "$MCP_NAME" -n "$MCP_NS" \
+ --ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 ||
+ cleanup_failed=1
+ fi
+
+ if [ "$HCC_MUTATED" = 1 ]; then
+ restore_patch="$(jq -cn --arg dnsPolicy "$ORIGINAL_DNS_POLICY" \
+ '{spec:{template:{spec:{dnsPolicy:$dnsPolicy,dnsConfig:null}}}}')"
+ kctl patch deployment "$HCC_DEPLOY" -n "$HCC_NS" --type=strategic \
+ -p "$restore_patch" >/dev/null 2>&1 || restore_ok=0
+ kctl scale deployment "$HCC_DEPLOY" -n "$HCC_NS" \
+ --replicas="${ORIGINAL_REPLICAS:-1}" >/dev/null 2>&1 || restore_ok=0
+ kctl rollout status deployment "$HCC_DEPLOY" -n "$HCC_NS" \
+ --timeout=240s >/dev/null 2>&1 || restore_ok=0
+ if [ "$restore_ok" = 1 ]; then
+ wait_until 60 "restored HCC DNS, replicas, Ready pod, and /ready endpoint" \
+ hcc_restore_is_verified >/dev/null 2>&1 || restore_ok=0
+ fi
+ fi
+
+ if [ "$restore_ok" = 1 ]; then
+ if ! wait_until 180 "HCC to remove all MCP/Context fixture runtime resources" \
+ fixture_resources_absent >/dev/null 2>&1; then
+ cleanup_failed=1
+ delete_residual_fixture_runtime || cleanup_failed=1
+ fi
+ if [ "$DNS_BLOCKER_CREATED" = 1 ]; then
+ delete_dns_blocker_fixture || cleanup_failed=1
+ fi
+ wait_until 60 "all HCC MCP readiness suite resources to disappear" \
+ suite_resources_absent >/dev/null 2>&1 || cleanup_failed=1
+ else
+ cleanup_failed=1
+ fi
+
+ if ! finalize_hcc_watch_gate_lock "$cleanup_failed" "$restore_ok"; then
+ cleanup_failed=1
+ fi
+
+ if [ "$cleanup_failed" -ne 0 ]; then
+ echo "HCC MCP readiness gate cleanup failed on context ${E2E_KUBECONTEXT}." >&2
+ [ "$restore_ok" = 1 ] || print_repair_instructions
+ [ "$status" = 0 ] && status=1
+ fi
+ exit "$status"
+}
+trap cleanup EXIT
+
+header "HCC readiness during initial McpServer and Context convergence"
+
+repo_root="$(git -C "${SCRIPT_DIR}/../.." rev-parse --show-toplevel)"
+[ -z "$(git -C "$repo_root" status --porcelain --untracked-files=normal)" ] ||
+ die "worktree has uncommitted changes; commit and pre-gate sync before runtime proof"
+expected_worktree_id="$(printf '%s' "$repo_root" | shasum | awk '{print $1}')"
+expected_head="$(git -C "$repo_root" rev-parse HEAD)"
+expected_short_head="$(git -C "$repo_root" rev-parse --short=8 HEAD)"
+expected_branch="$(git -C "$repo_root" branch --show-current)"
+[ -n "$expected_branch" ] ||
+ die "branch-owned runtime proof requires a named branch, not detached HEAD"
+[ -z "${MINIKUBE_PROFILE:-}" ] || [ "$MINIKUBE_PROFILE" = "$E2E_KUBECONTEXT" ] ||
+ die "MINIKUBE_PROFILE ${MINIKUBE_PROFILE} disagrees with context ${E2E_KUBECONTEXT}"
+
+profile_env="${E2E_BRANCH_PROFILE_ENV:-${HOME}/.cache/clerum/minikube-profiles/${E2E_KUBECONTEXT}/profile.env}"
+[ -r "$profile_env" ] ||
+ die "branch-profile helper evidence is missing at ${profile_env}; run a state-writing branch-profile helper action from this worktree"
+[ "$(profile_env_value PROFILE "$profile_env")" = "$E2E_KUBECONTEXT" ] ||
+ die "branch-profile helper output does not select context ${E2E_KUBECONTEXT}"
+[ "$(profile_env_value REPO_DIR "$profile_env")" = "$repo_root" ] ||
+ die "branch-profile helper output belongs to a different worktree"
+[ "$(profile_env_value BRANCH "$profile_env")" = "$expected_branch" ] ||
+ die "branch-profile helper output belongs to a different branch"
+[ "$(profile_env_value SHA_SHORT "$profile_env")" = "$expected_short_head" ] ||
+ die "branch-profile helper output belongs to a different HEAD"
+[ "$(profile_env_value DIRTY "$profile_env")" = false ] ||
+ die "branch-profile helper recorded a dirty worktree; refresh it after committing"
+
+pre_gate_state_root="${E2E_PRE_GATE_STATE_ROOT:-${TMPDIR:-/tmp}/clerum-pre-gate-sync}"
+cluster_fingerprint_file="${pre_gate_state_root}/${expected_worktree_id}/cluster.sha"
+[ -r "$cluster_fingerprint_file" ] ||
+ die "pre-gate fingerprint evidence is missing at ${cluster_fingerprint_file}"
+expected_cluster_fingerprint="$(sed -n '1p' "$cluster_fingerprint_file")"
+printf '%s\n' "$expected_cluster_fingerprint" | grep -Eq '^[0-9a-f]{40}$' ||
+ die "pre-gate fingerprint evidence is malformed"
+[ -n "${E2E_EXPECTED_PRE_GATE_GATE:-}" ] ||
+ die "E2E_EXPECTED_PRE_GATE_GATE must name the gate recorded by the branch-owned pre-gate sync"
+
+sync_marker="$(kctl get configmap clerum-pre-gate-sync-state -n "$HCC_NS" -o json \
+ 2>/dev/null)" ||
+ die "cluster has no readable pre-gate sync marker"
+actual_worktree_id="$(jq -r '.data.worktreeId // ""' <<<"$sync_marker")"
+actual_head="$(jq -r '.data.gitHead // ""' <<<"$sync_marker")"
+actual_cluster_fingerprint="$(jq -r '.data.clusterFingerprint // ""' <<<"$sync_marker")"
+actual_gate="$(jq -r '.data.gate // ""' <<<"$sync_marker")"
+[ "$actual_worktree_id" = "$expected_worktree_id" ] ||
+ die "cluster ownership marker does not match this worktree"
+[ "$actual_head" = "$expected_head" ] ||
+ die "cluster HEAD marker ${actual_head:-missing} does not match ${expected_head}"
+[ "$actual_cluster_fingerprint" = "$expected_cluster_fingerprint" ] ||
+ die "cluster fingerprint marker does not match this worktree's last pre-gate sync"
+[ "$actual_gate" = "$E2E_EXPECTED_PRE_GATE_GATE" ] ||
+ die "cluster gate marker ${actual_gate:-missing} does not match expected ${E2E_EXPECTED_PRE_GATE_GATE}"
+kctl get nodes -o json |
+ jq -e 'any(.items[]; .metadata.labels["minikube.k8s.io/name"] != null)' >/dev/null ||
+ die "target context is not a minikube cluster"
+suite_resources_absent ||
+ die "stale ${SUITE_NAME} resources exist; inspect them before starting a new fault injection"
+acquire_hcc_watch_gate_lock ||
+ die "another disruptive HCC gate owns context ${E2E_KUBECONTEXT}"
+ok "branch helper, profile, exact HEAD/fingerprint/gate, and exclusive HCC lock verified"
+
+ORIGINAL_REPLICAS="$(kctl get deployment "$HCC_DEPLOY" -n "$HCC_NS" \
+ -o jsonpath='{.spec.replicas}')"
+[ "$ORIGINAL_REPLICAS" = 1 ] ||
+ die "expected exactly one HCC replica, found ${ORIGINAL_REPLICAS:-unknown}"
+ORIGINAL_DNS_POLICY="$(kctl get deployment "$HCC_DEPLOY" -n "$HCC_NS" \
+ -o jsonpath='{.spec.template.spec.dnsPolicy}')"
+ORIGINAL_DNS_POLICY="${ORIGINAL_DNS_POLICY:-ClusterFirst}"
+[ "$ORIGINAL_DNS_POLICY" = ClusterFirst ] ||
+ die "HCC already has non-default dnsPolicy ${ORIGINAL_DNS_POLICY}; refusing a non-restorable fixture"
+ORIGINAL_DNS_CONFIG="$(kctl get deployment "$HCC_DEPLOY" -n "$HCC_NS" -o json |
+ jq -c '.spec.template.spec.dnsConfig // null')"
+[ "$ORIGINAL_DNS_CONFIG" = null ] ||
+ die "HCC already has dnsConfig ${ORIGINAL_DNS_CONFIG}; refusing a non-restorable fixture"
+HCC_IMAGE="$(kctl get deployment "$HCC_DEPLOY" -n "$HCC_NS" \
+ -o jsonpath='{.spec.template.spec.containers[?(@.name=="host-context-controller")].image}')"
+[ -n "$HCC_IMAGE" ] || die "could not resolve the running HCC image"
+UPSTREAM_DNS_IP="$(kctl get service kube-dns -n kube-system -o jsonpath='{.spec.clusterIP}')"
+[ -n "$UPSTREAM_DNS_IP" ] || die "could not resolve kube-system/kube-dns ClusterIP"
+running_dns_pods="$(kctl get pods -n kube-system -l k8s-app=kube-dns \
+ --field-selector=status.phase=Running -o name)"
+[ -n "$running_dns_pods" ] ||
+ die "no Running kube-dns pod is available"
+
+DNS_BLOCKER_CREATED=1
+kctl apply -f - >/dev/null <<EOF
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: ${DNS_BLOCKER_NAME}
+ namespace: ${HCC_NS}
+ labels:
+ e2e.clerum.io/suite: ${SUITE_NAME}
+ e2e.clerum.io/run: "${RUN_LABEL}"
+spec:
+ replicas: 1
+ selector:
+ matchLabels:
+ app: ${DNS_BLOCKER_NAME}
+ template:
+ metadata:
+ labels:
+ app: ${DNS_BLOCKER_NAME}
+ e2e.clerum.io/suite: ${SUITE_NAME}
+ e2e.clerum.io/run: "${RUN_LABEL}"
+ spec:
+ automountServiceAccountToken: false
+ terminationGracePeriodSeconds: 1
+ containers:
+ - name: dns-blocker
+ image: ${HCC_IMAGE}
+ imagePullPolicy: IfNotPresent
+ command: [node, -e]
+ args:
+ - >-
+ const dgram=require('node:dgram'),http=require('node:http'),
+ net=require('node:net');
+ const target=process.env.TARGET_DNS,upstream=process.env.UPSTREAM_DNS;
+ const udp=dgram.createSocket('udp4');let released=false;const held=[];
+ function question(message){let offset=12,labels=[];while(offset<message.length){
+ const length=message[offset++];if(length===0)break;if(offset+length>message.length)
+ return null;labels.push(message.subarray(offset,offset+length).toString('ascii'));
+ offset+=length;}if(offset+4>message.length)return null;return
+ {name:labels.join('.'),type:message.readUInt16BE(offset),end:offset+4};}
+ function answer(message,parsed){const header=Buffer.from(message.subarray(0,12));
+ header.writeUInt16BE(0x8180,2);header.writeUInt16BE(1,6);
+ header.writeUInt16BE(0,8);header.writeUInt16BE(0,10);
+ const record=Buffer.from([0xc0,0x0c,0x00,0x01,0x00,0x01,0x00,0x00,
+ 0x00,0x1e,0x00,0x04,93,184,216,34]);
+ return Buffer.concat([header,message.subarray(12,parsed.end),record]);}
+ function tcpFrame(message){const frame=Buffer.alloc(message.length+2);
+ frame.writeUInt16BE(message.length,0);message.copy(frame,2);return frame;}
+ function respond(entry){const response=answer(entry.message,entry.parsed);
+ if(entry.transport==='udp'){udp.send(response,entry.rinfo.port,
+ entry.rinfo.address);console.log('released DNS A '+target+' via UDP');return;}
+ if(!entry.socket.destroyed){entry.socket.write(tcpFrame(response));
+ console.log('released DNS A '+target+' via TCP');}}
+ function forwardUdp(message,rinfo){const relay=dgram.createSocket('udp4');
+ const timer=setTimeout(()=>relay.close(),5000);relay.once('message',response=>{
+ clearTimeout(timer);udp.send(response,rinfo.port,rinfo.address);relay.close();});
+ relay.once('error',()=>{clearTimeout(timer);relay.close();});
+ relay.send(message,53,upstream);}
+ function forwardTcp(message,socket){const relay=net.createConnection(
+ {host:upstream,port:53},()=>relay.write(tcpFrame(message)));
+ let pending=Buffer.alloc(0);relay.setTimeout(5000,()=>relay.destroy());
+ relay.on('data',chunk=>{pending=Buffer.concat([pending,chunk]);
+ if(pending.length<2)return;const length=pending.readUInt16BE(0);
+ if(pending.length<length+2)return;if(!socket.destroyed)
+ socket.write(pending.subarray(0,length+2));relay.destroy();});
+ relay.once('error',()=>relay.destroy());}
+ function handle(message,entry){const parsed=question(message);
+ if(parsed&&parsed.name===target&&parsed.type===1){entry.message=message;
+ entry.parsed=parsed;if(released)respond(entry);else{held.push(entry);
+ console.log('holding DNS A '+target+' via '+entry.transport.toUpperCase());}
+ return;}if(entry.transport==='udp')forwardUdp(message,entry.rinfo);
+ else forwardTcp(message,entry.socket);}
+ let listeners=0;function listening(){listeners+=1;if(listeners===2)
+ console.log('dns hold proxy ready for '+target+' over UDP and TCP');}
+ udp.on('message',(message,rinfo)=>handle(message,{transport:'udp',rinfo}));
+ udp.bind(8053,'0.0.0.0',listening);
+ const tcp=net.createServer(socket=>{let pending=Buffer.alloc(0);
+ socket.on('data',chunk=>{pending=Buffer.concat([pending,chunk]);
+ while(pending.length>=2){const length=pending.readUInt16BE(0);
+ if(pending.length<length+2)return;const message=pending.subarray(2,length+2);
+ pending=pending.subarray(length+2);handle(message,{transport:'tcp',socket});}});
+ });tcp.listen(8053,'0.0.0.0',listening);
+ http.createServer((request,response)=>{if(request.method==='POST'&&
+ request.url==='/release'){released=true;while(held.length)respond(held.shift());
+ response.writeHead(200);response.end('released');return;}response.writeHead(404);
+ response.end();}).listen(8090,'127.0.0.1');
+ env:
+ - name: TARGET_DNS
+ value: ${TARGET_DNS}
+ - name: UPSTREAM_DNS
+ value: ${UPSTREAM_DNS_IP}
+ resources:
+ requests: {cpu: 5m, memory: 20Mi}
+ limits: {cpu: 75m, memory: 64Mi}
+ securityContext:
+ allowPrivilegeEscalation: false
+ capabilities: {drop: [ALL]}
+ readOnlyRootFilesystem: true
+ runAsNonRoot: true
+ runAsUser: 1000
+ runAsGroup: 1000
+ seccompProfile: {type: RuntimeDefault}
+---
+apiVersion: v1
+kind: Service
+metadata:
+ name: ${DNS_BLOCKER_NAME}
+ namespace: ${HCC_NS}
+ labels:
+ e2e.clerum.io/suite: ${SUITE_NAME}
+ e2e.clerum.io/run: "${RUN_LABEL}"
+spec:
+ selector:
+ app: ${DNS_BLOCKER_NAME}
+ ports:
+ - name: dns-udp
+ protocol: UDP
+ port: 53
+ targetPort: 8053
+ - name: dns-tcp
+ protocol: TCP
+ port: 53
+ targetPort: 8053
+---
+apiVersion: networking.k8s.io/v1
+kind: NetworkPolicy
+metadata:
+ name: ${DNS_BLOCKER_POLICY}
+ namespace: ${HCC_NS}
+ labels:
+ e2e.clerum.io/suite: ${SUITE_NAME}
+ e2e.clerum.io/run: "${RUN_LABEL}"
+spec:
+ podSelector:
+ matchLabels:
+ app: ${DNS_BLOCKER_NAME}
+ policyTypes: [Ingress, Egress]
+ ingress:
+ - from:
+ - podSelector:
+ matchLabels:
+ app: ${HCC_DEPLOY}
+ ports:
+ - {protocol: UDP, port: 8053}
+ - {protocol: UDP, port: 53}
+ - {protocol: TCP, port: 8053}
+ - {protocol: TCP, port: 53}
+ egress:
+ - to:
+ - namespaceSelector:
+ matchLabels:
+ kubernetes.io/metadata.name: kube-system
+ podSelector:
+ matchLabels:
+ k8s-app: kube-dns
+ ports:
+ - {protocol: UDP, port: 53}
+ - {protocol: TCP, port: 53}
+---
+apiVersion: networking.k8s.io/v1
+kind: NetworkPolicy
+metadata:
+ name: ${HCC_DNS_POLICY}
+ namespace: ${HCC_NS}
+ labels:
+ e2e.clerum.io/suite: ${SUITE_NAME}
+ e2e.clerum.io/run: "${RUN_LABEL}"
+spec:
+ podSelector:
+ matchLabels:
+ app: ${HCC_DEPLOY}
+ policyTypes: [Egress]
+ egress:
+ - to:
+ - podSelector:
+ matchLabels:
+ app: ${DNS_BLOCKER_NAME}
+ ports:
+ - {protocol: UDP, port: 53}
+ - {protocol: UDP, port: 8053}
+ - {protocol: TCP, port: 53}
+ - {protocol: TCP, port: 8053}
+EOF
+kctl rollout status deployment "$DNS_BLOCKER_NAME" -n "$HCC_NS" \
+ --timeout=90s >/dev/null || die "DNS blocker did not become ready"
+wait_until 30 "DNS blocker process to listen" \
+ dns_log_contains "dns hold proxy ready for ${TARGET_DNS}" ||
+ die "DNS blocker process did not start"
+DNS_BLOCKER_IP="$(kctl get service "$DNS_BLOCKER_NAME" -n "$HCC_NS" \
+ -o jsonpath='{.spec.clusterIP}')"
+[ -n "$DNS_BLOCKER_IP" ] || die "DNS blocker Service has no ClusterIP"
+ok "isolated DNS hold proxy is ready and forwards non-fixture UDP/TCP queries to CoreDNS"
+
+HCC_MUTATED=1
+kctl scale deployment "$HCC_DEPLOY" -n "$HCC_NS" --replicas=0 >/dev/null
+kctl wait pod -n "$HCC_NS" -l "app=${HCC_DEPLOY}" --for=delete \
+ --timeout=120s >/dev/null || die "existing HCC pod did not stop"
+
+CONTEXT_CREATED=1
+kctl apply -f - >/dev/null <<EOF
+apiVersion: clerum.io/v1alpha1
+kind: Context
+metadata:
+ name: ${CONTEXT_NAME}
+ namespace: ${MCP_NS}
+ labels:
+ e2e.clerum.io/suite: ${SUITE_NAME}
+ e2e.clerum.io/run: "${RUN_LABEL}"
+spec:
+ contextId: ${CONTEXT_ID}
+ description: E2E HCC readiness Context updated while initial MCP convergence is blocked.
+ mcpServers: []
+EOF
+
+MCP_CREATED=1
+kctl apply -f - >/dev/null <<EOF
+apiVersion: clerum.io/v1alpha1
+kind: McpServer
+metadata:
+ name: ${MCP_NAME}
+ namespace: ${MCP_NS}
+ labels:
+ e2e.clerum.io/suite: ${SUITE_NAME}
+ e2e.clerum.io/run: "${RUN_LABEL}"
+spec:
+ contextRef: ${CONTEXT_NAME}
+ description: E2E MCP fixture for initial fleet readiness.
+ image: clerum/mock-mcp-server:test
+ imagePullPolicy: IfNotPresent
+ transport:
+ type: streamableHttp
+ url: http://${MCP_NAME}.${MCP_NS}.svc.cluster.local:3000/mcp
+ port: 3000
+ egressBindings:
+ - dns: ${TARGET_DNS}
+ port: 443
+ protocol: TCP
+EOF
+
+dns_patch="$(jq -cn --arg nameserver "$DNS_BLOCKER_IP" '
+ {spec:{template:{spec:{
+ dnsPolicy:"None",
+ dnsConfig:{
+ nameservers:[$nameserver],
+ options:[
+ {name:"ndots",value:"1"},
+ {name:"timeout",value:"30"},
+ {name:"attempts",value:"20"}
+ ]
+ }
+ }}}}
+')"
+kctl patch deployment "$HCC_DEPLOY" -n "$HCC_NS" --type=strategic \
+ -p "$dns_patch" >/dev/null
+kctl scale deployment "$HCC_DEPLOY" -n "$HCC_NS" --replicas=1 >/dev/null
+
+capture_hcc() {
+ NEW_HCC_POD="$(running_hcc_pod)"
+ [ -n "$NEW_HCC_POD" ]
+}
+wait_until 120 "replacement HCC pod to enter Running" capture_hcc ||
+ die "replacement HCC pod did not start"
+identity="$(kctl get pod "$NEW_HCC_POD" -n "$HCC_NS" \
+ -o jsonpath='{.metadata.uid}{" "}{.status.containerStatuses[?(@.name=="host-context-controller")].restartCount}')"
+read -r HCC_UID HCC_RESTARTS <<<"$identity"
+[ -n "$HCC_UID" ] && [ -n "$HCC_RESTARTS" ] ||
+ die "could not capture replacement HCC pod identity"
+
+wait_until 120 "fixture external-egress DNS query to reach the hold proxy" \
+ dns_log_contains "holding DNS A ${TARGET_DNS}" ||
+ die "initial McpServer external-egress convergence never reached the DNS hold boundary"
+wait_until 60 "HCC to begin initial external-egress convergence" \
+ hcc_log_contains "Reconciling external egress before startup runtime reconciliation" ||
+ die "HCC did not log initial McpServer external-egress convergence"
+wait_until 120 "replacement HCC pod and Deployment to become Kubernetes Ready during the hold" \
+ hcc_kubernetes_readiness_is_exact ||
+ die "HCC did not become Kubernetes Ready while initial McpServer convergence remained blocked"
+dns_log_contains "holding DNS A ${TARGET_DNS}" ||
+ die "DNS hold ended before Kubernetes reported HCC Ready"
+if dns_log_contains "released DNS A ${TARGET_DNS}"; then
+ die "DNS blocker released the McpServer query before Kubernetes reported HCC Ready"
+fi
+fixture_mcp_convergence_absent ||
+ die "fixture runtime, policy, or Ready status appeared before Kubernetes reported HCC Ready"
+blocked_probe="$(probe_hcc_during_block)" ||
+ die "HCC readiness/discovery was unavailable while MCP convergence was blocked"
+echo "$blocked_probe" | jq -e \
+ --arg fixture "$MCP_NAME" \
+ '.readyStatus == 200 and .discoveryStatus == 200 and
+ .fixture == $fixture and .fixtureReady != true' >/dev/null ||
+ die "HCC blocked-state probe returned an invalid result: ${blocked_probe}"
+fixture_mcp_convergence_absent ||
+ die "fixture runtime or external-egress policy converged before the held DNS query was released"
+context_policies_absent ||
+ die "Context policy existed before the Context watch update"
+baseline_policies_exist ||
+ die "baseline safety NetworkPolicies are absent while HCC reports Ready"
+hcc_identity_is_stable ||
+ die "HCC restarted while the MCP external-egress query was held"
+ok "/ready is 200 and discovery contains the exact McpServer while its real initial convergence is blocked"
+ok "baseline NetworkPolicies exist and no fixture runtime/policy was created prematurely"
+
+initial_empty_context_log="[NetPol] Reconciling context \"${CONTEXT_ID}\" — allowed servers: []"
+wait_until 120 "initial NetworkPolicy pass to reconcile the fixture's empty Context snapshot" \
+ hcc_log_contains "$initial_empty_context_log" ||
+ die "initial NetworkPolicy pass never reconciled the fixture's empty Context"
+startup_convergence_window_is_clean ||
+ die "startup NetworkPolicy or fixture external-egress convergence failed/retried before the Context update"
+context_policies_absent ||
+ die "Context policy appeared before the isolated MODIFIED event"
+
+context_patch="$(jq -cn --arg server "$MCP_NAME" '{spec:{mcpServers:[$server]}}')"
+kctl patch context "$CONTEXT_NAME" -n "$MCP_NS" --type=merge \
+ -p "$context_patch" >/dev/null
+wait_until 60 "Context API to expose the latest server membership" context_watch_has_latest_spec ||
+ die "Context update did not persist"
+wait_until 60 "HCC Context watch to observe the update during the blocked fleet pass" \
+ hcc_log_contains "Context watch event: MODIFIED for ${CONTEXT_NAME}" ||
+ die "HCC did not observe the real Context update while initial MCP convergence was blocked"
+modified_context_log="[NetPol] Reconciling context \"${CONTEXT_ID}\" — allowed servers: [${MCP_NAME}]"
+wait_until 60 "MODIFIED handler to reconcile the fixture's latest Context snapshot" \
+ hcc_log_contains "$modified_context_log" ||
+ die "the observed MODIFIED event never reconciled the latest Context membership"
+wait_until 120 "all three latest-Context NetworkPolicies to converge during the MCP hold" \
+ context_policies_converged ||
+ die "Context policies remained blocked behind the held McpServer convergence"
+startup_convergence_window_is_clean ||
+ die "startup NetworkPolicy or fixture external-egress convergence failed/retried during the isolation window"
+fixture_mcp_convergence_absent ||
+ die "McpServer runtime or external-egress policy escaped the deterministic DNS hold boundary"
+dns_log_contains "holding DNS A ${TARGET_DNS}" ||
+ die "DNS hold evidence disappeared before Context policy convergence"
+if dns_log_contains "released DNS A ${TARGET_DNS}"; then
+ die "DNS blocker released the McpServer query before the Context isolation assertion"
+fi
+post_context_probe="$(probe_hcc_during_block)" ||
+ die "HCC readiness/discovery regressed after Context policy convergence during the MCP hold"
+echo "$post_context_probe" | jq -e \
+ --arg fixture "$MCP_NAME" \
+ '.readyStatus == 200 and .discoveryStatus == 200 and
+ .fixture == $fixture and .fixtureReady != true' >/dev/null ||
+ die "HCC post-Context blocked-state probe returned an invalid result: ${post_context_probe}"
+hcc_kubernetes_readiness_is_exact ||
+ die "HCC lost Kubernetes readiness while Context policies converged during the MCP hold"
+hcc_identity_is_stable ||
+ die "HCC restarted while Context policies converged around the held MCP entity"
+ok "the MODIFIED handler, not the initial empty-Context pass, converged all three policies"
+ok "McpServer runtime and external-egress remained absent until release; readiness stayed 200"
+
+release_dns_blocker ||
+ die "could not release the fixture DNS query"
+wait_until 30 "DNS blocker to answer the held query" \
+ dns_log_contains "released DNS A ${TARGET_DNS}" ||
+ die "DNS blocker did not answer the held query"
+wait_until 300 "McpServer runtime, status, and latest Context NetworkPolicies to converge" \
+ fixture_converged ||
+ die "McpServer/Context/NetworkPolicy convergence did not complete after DNS release"
+wait_until 60 "initial NetworkPolicy full pass to run" \
+ hcc_log_contains "Running initial NetworkPolicy background reconciliation" ||
+ die "initial NetworkPolicy convergence was not observed after releasing MCP convergence"
+startup_convergence_window_is_clean ||
+ die "startup NetworkPolicy or fixture external-egress convergence failed/retried before final convergence"
+hcc_identity_is_stable ||
+ die "HCC restarted instead of completing the released background convergence"
+final_probe="$(probe_hcc_final_context)" ||
+ die "HCC final Context-scoped discovery did not expose the converged fixture"
+echo "$final_probe" | jq -e \
+ --arg fixture "$MCP_NAME" --arg context "$CONTEXT_NAME" '
+ .readyStatus == 200 and .scopedDiscoveryStatus == 200 and
+ .fixture == $fixture and .fixtureReady == true and .contextRef == $context
+ ' >/dev/null ||
+ die "HCC final probe returned an invalid result: ${final_probe}"
+ok "released MCP convergence created the real runtime and external-egress policy"
+ok "Context ingress, mcp-host egress, and rpc-proxy egress policies reflect the latest watch state"
+ok "HCC stayed Ready on the same pod throughout blocked and released convergence"
+
+header "HCC McpServer/Context readiness gate passed"
+echo "$blocked_probe"
+echo "$post_context_probe"
+echo "$final_probe"
diff --git a/scripts/e2e/e2e-hcc-readiness-bootstrap.sh b/scripts/e2e/e2e-hcc-readiness-bootstrap.sh
index c90fa3a05..7b76b3437 100755
--- a/scripts/e2e/e2e-hcc-readiness-bootstrap.sh
+++ b/scripts/e2e/e2e-hcc-readiness-bootstrap.sh
@@ -12,6 +12,9 @@ set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=scripts/e2e/e2e-lib.sh
source "${SCRIPT_DIR}/e2e-lib.sh"
+# shellcheck source=scripts/e2e/_lib/hcc-watch-recovery-lock.sh
+# shellcheck disable=SC1091
+source "${SCRIPT_DIR}/_lib/hcc-watch-recovery-lock.sh"
[ -n "$E2E_KUBECONTEXT" ] || {
echo "KUBECONTEXT or E2E_K8S_CONTEXT must select an explicit branch-scoped minikube context." >&2
@@ -46,6 +49,15 @@ HOST_REF=""
RUNTIME_SECRET=""
HCC_MUTATED=0
BLOCKER_CREATED=0
+# Read and mutated by the sourced compare-and-swap lock helper.
+# shellcheck disable=SC2034
+HCC_GATE_LOCK_ACQUIRED=0
+# shellcheck disable=SC2034
+HCC_GATE_LOCK_NAME=""
+# shellcheck disable=SC2034
+HCC_GATE_LOCK_UID=""
+# shellcheck disable=SC2034
+HCC_GATE_FINALIZATION_FAILURE=""
die() {
if [ -n "${new_hcc_pod:-}" ]; then
@@ -69,6 +81,16 @@ wait_until() {
return 1
}
+profile_env_value() {
+ local key=$1 file=$2
+ awk -v key="$key" '
+ index($0, key "=") == 1 {
+ print substr($0, length(key) + 2)
+ exit
+ }
+ ' "$file"
+}
+
running_hcc_pod() {
kctl get pods -n "$HCC_NS" -l "app=${HCC_DEPLOY}" \
--field-selector=status.phase=Running \
@@ -98,44 +120,129 @@ secret_restored() {
kctl get secret "$RUNTIME_SECRET" -n "$HOST_NS" >/dev/null 2>&1
}
+readiness_blocker_suite_absent() {
+ local resources
+ resources="$(
+ kctl get deployment,service,networkpolicy -n "$HCC_NS" \
+ -l 'e2e.clerum.io/hcc-readiness' -o name 2>/dev/null
+ )" || return 1
+ [ -z "$resources" ]
+}
+
+probe_hcc_ready_pod() {
+ local pod
+ pod="$(ready_pod_name "$HCC_NS" "app=${HCC_DEPLOY}")" || return 1
+ kctl exec "pod/${pod}" -n "$HCC_NS" -c host-context-controller -- \
+ node -e '
+ const http = require("node:http");
+ const request = http.get(
+ {host: "127.0.0.1", port: 8081, path: "/ready"},
+ response => {
+ let body = "";
+ response.setEncoding("utf8");
+ response.on("data", chunk => { body += chunk; });
+ response.on("end", () => {
+ let parsed;
+ try { parsed = JSON.parse(body); } catch { process.exit(2); }
+ process.exit(response.statusCode === 200 && parsed?.ready === true ? 0 : 3);
+ });
+ }
+ );
+ request.setTimeout(5000, () => request.destroy(new Error("timeout")));
+ request.once("error", () => process.exit(4));
+ ' >/dev/null 2>&1
+}
+
+hcc_restore_is_verified() {
+ local deployment
+ deployment="$(kctl get deployment "$HCC_DEPLOY" -n "$HCC_NS" -o json)" || return 1
+ jq -e \
+ --arg controlApiBaseUrl "$ORIGINAL_CONTROL_API_BASE_URL" \
+ --argjson replicas "${ORIGINAL_REPLICAS:-1}" '
+ .spec.replicas == $replicas and
+ .status.observedGeneration == .metadata.generation and
+ (.status.updatedReplicas // 0) == $replicas and
+ (.status.readyReplicas // 0) == $replicas and
+ (.status.availableReplicas // 0) == $replicas and
+ (.status.unavailableReplicas // 0) == 0 and
+ any(.spec.template.spec.containers[]?;
+ .name == "host-context-controller" and
+ any(.env[]?;
+ .name == "CONTROL_API_BASE_URL" and .value == $controlApiBaseUrl
+ )
+ )
+ ' <<<"$deployment" >/dev/null || return 1
+ secret_restored && probe_hcc_ready_pod
+}
+
+delete_blocker_fixture() {
+ local failed=0
+ kctl delete networkpolicy "$BLOCKER_EGRESS_POLICY_NAME" "$BLOCKER_NAME" -n "$HCC_NS" \
+ --ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 || failed=1
+ kctl delete service "$BLOCKER_NAME" -n "$HCC_NS" \
+ --ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 || failed=1
+ kctl delete deployment "$BLOCKER_NAME" -n "$HCC_NS" \
+ --ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 || failed=1
+ [ "$failed" = 0 ]
+}
+
+print_repair_instructions() {
+ cat >&2 <<EOF
+HCC readiness bootstrap cleanup could not restore a verified clean state.
+Context: ${E2E_KUBECONTEXT}
+HCC: ${HCC_NS}/${HCC_DEPLOY}
+Runtime Secret: ${HOST_NS}/${RUNTIME_SECRET:-unknown}
+Retained blocker: ${HCC_NS}/${BLOCKER_NAME}
+
+Inspect before changing anything:
+ kubectl --context=${E2E_KUBECONTEXT} -n ${HCC_NS} get deployment ${HCC_DEPLOY} -o yaml
+ kubectl --context=${E2E_KUBECONTEXT} -n ${HOST_NS} get secret ${RUNTIME_SECRET:-unknown}
+ kubectl --context=${E2E_KUBECONTEXT} -n ${HCC_NS} get deployment,service,networkpolicy -l e2e.clerum.io/hcc-readiness
+
+Do not remove the blocker or HCC gate lock until HCC configuration, rollout, Pod readiness,
+/ready, runtime Secret restoration, and fixture absence are verified.
+EOF
+}
+
cleanup() {
- local status=$? cleanup_failed=0
+ local status=$? cleanup_failed=0 restore_ok=1
+ trap - EXIT
set +e
if [ "$HCC_MUTATED" = 1 ] && [ -n "$ORIGINAL_CONTROL_API_BASE_URL" ]; then
kctl set env deployment/"$HCC_DEPLOY" -n "$HCC_NS" \
"CONTROL_API_BASE_URL=${ORIGINAL_CONTROL_API_BASE_URL}" >/dev/null 2>&1 ||
- cleanup_failed=1
+ restore_ok=0
kctl scale deployment "$HCC_DEPLOY" -n "$HCC_NS" \
--replicas="${ORIGINAL_REPLICAS:-1}" >/dev/null 2>&1 ||
- cleanup_failed=1
- kctl rollout status deployment "$HCC_DEPLOY" -n "$HCC_NS" --timeout=180s >/dev/null 2>&1 ||
- cleanup_failed=1
- if [ -n "$RUNTIME_SECRET" ]; then
- wait_until 180 "HCC to restore ${RUNTIME_SECRET}" secret_restored >/dev/null 2>&1 ||
- cleanup_failed=1
+ restore_ok=0
+ kctl rollout status deployment "$HCC_DEPLOY" -n "$HCC_NS" --timeout=180s \
+ >/dev/null 2>&1 || restore_ok=0
+ if [ "$restore_ok" = 1 ]; then
+ wait_until 180 \
+ "restored HCC config, rollout, Ready pod, /ready, and ${RUNTIME_SECRET}" \
+ hcc_restore_is_verified >/dev/null 2>&1 || restore_ok=0
+ fi
+ fi
+
+ if [ "$restore_ok" = 1 ]; then
+ if [ "$BLOCKER_CREATED" = 1 ]; then
+ delete_blocker_fixture || cleanup_failed=1
fi
+ wait_until 60 "all HCC readiness blocker resources to disappear" \
+ readiness_blocker_suite_absent >/dev/null 2>&1 || cleanup_failed=1
+ else
+ cleanup_failed=1
fi
- if [ "$BLOCKER_CREATED" = 1 ]; then
- kctl delete networkpolicy "$BLOCKER_EGRESS_POLICY_NAME" -n "$HCC_NS" \
- --ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 ||
- cleanup_failed=1
- kctl delete networkpolicy "$BLOCKER_NAME" -n "$HCC_NS" \
- --ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 ||
- cleanup_failed=1
- kctl delete service "$BLOCKER_NAME" -n "$HCC_NS" \
- --ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 ||
- cleanup_failed=1
- kctl delete deployment "$BLOCKER_NAME" -n "$HCC_NS" \
- --ignore-not-found --wait=true --timeout=60s >/dev/null 2>&1 ||
- cleanup_failed=1
+ if ! finalize_hcc_watch_gate_lock "$cleanup_failed" "$restore_ok"; then
+ cleanup_failed=1
fi
if [ "$cleanup_failed" -ne 0 ]; then
echo "HCC readiness gate cleanup failed on context ${E2E_KUBECONTEXT}." >&2
- echo "Verify deployment/${HCC_DEPLOY}, secret/${RUNTIME_SECRET:-unknown}, and ${BLOCKER_NAME}." >&2
- exit 1
+ [ "$restore_ok" = 1 ] || print_repair_instructions
+ [ "$status" = 0 ] && status=1
fi
exit "$status"
}
@@ -148,19 +255,62 @@ repo_root="$(git -C "${SCRIPT_DIR}/../.." rev-parse --show-toplevel)"
die "worktree has uncommitted changes; commit and pre-gate sync before runtime proof"
expected_worktree_id="$(printf '%s' "$repo_root" | shasum | awk '{print $1}')"
expected_head="$(git -C "$repo_root" rev-parse HEAD)"
-actual_worktree_id="$(kctl get configmap clerum-pre-gate-sync-state -n "$HCC_NS" \
- -o jsonpath='{.data.worktreeId}' 2>/dev/null || true)"
-actual_head="$(kctl get configmap clerum-pre-gate-sync-state -n "$HCC_NS" \
- -o jsonpath='{.data.gitHead}' 2>/dev/null || true)"
+expected_short_head="$(git -C "$repo_root" rev-parse --short=8 HEAD)"
+expected_branch="$(git -C "$repo_root" branch --show-current)"
+[ -n "$expected_branch" ] ||
+ die "branch-owned runtime proof requires a named branch, not detached HEAD"
+[ -z "${MINIKUBE_PROFILE:-}" ] || [ "$MINIKUBE_PROFILE" = "$E2E_KUBECONTEXT" ] ||
+ die "MINIKUBE_PROFILE ${MINIKUBE_PROFILE} disagrees with context ${E2E_KUBECONTEXT}"
+
+profile_env="${E2E_BRANCH_PROFILE_ENV:-${HOME}/.cache/clerum/minikube-profiles/${E2E_KUBECONTEXT}/profile.env}"
+[ -r "$profile_env" ] ||
+ die "branch-profile helper evidence is missing at ${profile_env}; run a state-writing branch-profile helper action from this worktree"
+[ "$(profile_env_value PROFILE "$profile_env")" = "$E2E_KUBECONTEXT" ] ||
+ die "branch-profile helper output does not select context ${E2E_KUBECONTEXT}"
+[ "$(profile_env_value REPO_DIR "$profile_env")" = "$repo_root" ] ||
+ die "branch-profile helper output belongs to a different worktree"
+[ "$(profile_env_value BRANCH "$profile_env")" = "$expected_branch" ] ||
+ die "branch-profile helper output belongs to a different branch"
+[ "$(profile_env_value SHA_SHORT "$profile_env")" = "$expected_short_head" ] ||
+ die "branch-profile helper output belongs to a different HEAD"
+[ "$(profile_env_value DIRTY "$profile_env")" = false ] ||
+ die "branch-profile helper recorded a dirty worktree; refresh it after committing"
+
+pre_gate_state_root="${E2E_PRE_GATE_STATE_ROOT:-${TMPDIR:-/tmp}/clerum-pre-gate-sync}"
+cluster_fingerprint_file="${pre_gate_state_root}/${expected_worktree_id}/cluster.sha"
+[ -r "$cluster_fingerprint_file" ] ||
+ die "pre-gate fingerprint evidence is missing at ${cluster_fingerprint_file}"
+expected_cluster_fingerprint="$(sed -n '1p' "$cluster_fingerprint_file")"
+printf '%s\n' "$expected_cluster_fingerprint" | grep -Eq '^[0-9a-f]{40}$' ||
+ die "pre-gate fingerprint evidence is malformed"
+[ -n "${E2E_EXPECTED_PRE_GATE_GATE:-}" ] ||
+ die "E2E_EXPECTED_PRE_GATE_GATE must name the gate recorded by the branch-owned pre-gate sync"
+
+sync_marker="$(kctl get configmap clerum-pre-gate-sync-state -n "$HCC_NS" -o json \
+ 2>/dev/null)" ||
+ die "cluster has no readable pre-gate sync marker"
+actual_worktree_id="$(jq -r '.data.worktreeId // ""' <<<"$sync_marker")"
+actual_head="$(jq -r '.data.gitHead // ""' <<<"$sync_marker")"
+actual_cluster_fingerprint="$(jq -r '.data.clusterFingerprint // ""' <<<"$sync_marker")"
+actual_gate="$(jq -r '.data.gate // ""' <<<"$sync_marker")"
[ "$actual_worktree_id" = "$expected_worktree_id" ] ||
die "cluster ownership marker does not match this worktree"
[ "$actual_head" = "$expected_head" ] ||
die "cluster HEAD marker ${actual_head:-missing} does not match ${expected_head}"
-ok "branch-scoped cluster ownership matches this clean worktree and HEAD"
+[ "$actual_cluster_fingerprint" = "$expected_cluster_fingerprint" ] ||
+ die "cluster fingerprint marker does not match this worktree's last pre-gate sync"
+[ "$actual_gate" = "$E2E_EXPECTED_PRE_GATE_GATE" ] ||
+ die "cluster gate marker ${actual_gate:-missing} does not match expected ${E2E_EXPECTED_PRE_GATE_GATE}"
+ok "branch helper, profile, exact HEAD/fingerprint/gate verified"
kctl get nodes -o json |
jq -e 'any(.items[]; .metadata.labels["minikube.k8s.io/name"] != null)' >/dev/null ||
die "target context is not a minikube cluster"
+readiness_blocker_suite_absent ||
+ die "stale HCC readiness blocker resources exist; inspect them before fault injection"
+acquire_hcc_watch_gate_lock ||
+ die "another disruptive HCC gate owns context ${E2E_KUBECONTEXT}"
+ok "exclusive HCC fault-injection lock acquired"
ORIGINAL_REPLICAS="$(kctl get deployment "$HCC_DEPLOY" -n "$HCC_NS" \
-o jsonpath='{.spec.replicas}')"
@@ -175,6 +325,8 @@ HOST_REF="${E2E_HCC_READY_HOST_REF:-$(kctl get hosts -n "$HOST_NS" -o json |
jq -r '.items | sort_by(.metadata.name) | .[0].metadata.name // empty')}"
[ -n "$HOST_REF" ] || die "no Host exists in ${HOST_NS}"
RUNTIME_SECRET="host-${HOST_REF}-mcp-host-runtime-tokens"
+kctl get secret "$RUNTIME_SECRET" -n "$HOST_NS" >/dev/null 2>&1 ||
+ die "selected Host ${HOST_REF} has no existing runtime Secret ${RUNTIME_SECRET}; refusing a pre-degraded fixture"
ok "selected existing Host ${HOST_REF} as the real initial-fleet work item"
BLOCKER_CREATED=1
diff --git a/scripts/tests/test-hcc-watch-recovery-gate.sh b/scripts/tests/test-hcc-watch-recovery-gate.sh
index 50104032d..296dd0515 100755
--- a/scripts/tests/test-hcc-watch-recovery-gate.sh
+++ b/scripts/tests/test-hcc-watch-recovery-gate.sh
@@ -4,7 +4,10 @@ set -u
FAIL=0
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
SCRIPT_DIR="${ROOT}/scripts/e2e"
-GATE="${SCRIPT_DIR}/e2e-hcc-communicationchannel-watch-recovery.sh"
+WATCH_GATE="${SCRIPT_DIR}/e2e-hcc-communicationchannel-watch-recovery.sh"
+READINESS_GATE="${SCRIPT_DIR}/e2e-hcc-readiness-bootstrap.sh"
+MCP_READINESS_GATE="${SCRIPT_DIR}/e2e-hcc-mcp-context-readiness.sh"
+GATES=("$WATCH_GATE" "$READINESS_GATE" "$MCP_READINESS_GATE")
LOCK_HELPER="${SCRIPT_DIR}/_lib/hcc-watch-recovery-lock.sh"
LOG_HELPER="${SCRIPT_DIR}/_lib/hcc-watch-recovery-logs.sh"
MOCK_STATE_FILE="$(mktemp "${TMPDIR:-/tmp}/hcc-lock-test.XXXXXX")"
@@ -15,7 +18,7 @@ trap 'rm -f "$MOCK_STATE_FILE" "$MOCK_LOG_FILE"' EXIT
pass() { echo "PASS: $1"; }
fail() { echo "FAIL: $1"; FAIL=1; }
-for script in "$GATE" "$LOCK_HELPER" "$LOG_HELPER"; do
+for script in "${GATES[@]}" "$LOCK_HELPER" "$LOG_HELPER"; do
if bash -n "$script"; then
pass "$(basename "$script") has valid bash syntax"
else
@@ -82,18 +85,28 @@ else
fail "the second recovery cycle was not isolated from the first"
fi
-acquire_line="$(grep -nF 'acquire_hcc_watch_gate_lock || die' "$GATE" | cut -d: -f1)"
-# Literal source-code assertion.
-# shellcheck disable=SC2016
-mutation_line="$(grep -nF 'kctl get deployment "$HCC_DEPLOY"' "$GATE" | head -1 | cut -d: -f1)"
-# Literal source-code assertion.
-# shellcheck disable=SC2016
-if [ -n "$acquire_line" ] && [ -n "$mutation_line" ] && [ "$acquire_line" -lt "$mutation_line" ] &&
- grep -Fq 'finalize_hcc_watch_gate_lock "$cleanup_failed" "$restore_ok" || cleanup_failed=1' "$GATE"; then
- pass "gate acquires before HCC access and finalizes ownership from cleanup"
-else
- fail "gate lock is not held across the full HCC fault-injection window"
-fi
+for gate in "${GATES[@]}"; do
+ acquire_line="$(grep -nF 'acquire_hcc_watch_gate_lock' "$gate" | tail -1 | cut -d: -f1)"
+ case "$gate" in
+ "$WATCH_GATE")
+ # Literal source-code assertion.
+ # shellcheck disable=SC2016
+ mutation_line="$(grep -nF 'kctl patch deployment "$HCC_DEPLOY"' "$gate" | tail -1 | cut -d: -f1)"
+ ;;
+ *)
+ mutation_line="$(grep -nF 'HCC_MUTATED=1' "$gate" | tail -1 | cut -d: -f1)"
+ ;;
+ esac
+ # The grep pattern intentionally matches literal shell variable references.
+ # shellcheck disable=SC2016
+ if [ -n "$acquire_line" ] && [ -n "$mutation_line" ] &&
+ [ "$acquire_line" -lt "$mutation_line" ] &&
+ grep -Fq 'finalize_hcc_watch_gate_lock "$cleanup_failed" "$restore_ok"' "$gate"; then
+ pass "$(basename "$gate") acquires before mutation and finalizes ownership from cleanup"
+ else
+ fail "$(basename "$gate") does not hold the shared lock across its full fault-injection window"
+ fi
+done
kctl() {
local action=$1 body expected_rv current_rv current_uid next_rv
@@ -253,8 +266,8 @@ else
fi
unset MOCK_CREATE_WITHOUT_UID
-cleanup_fail_line="$(grep -nF 'fail "fixture cleanup, HCC restoration, or lock finalization did not complete' "$GATE" | cut -d: -f1)"
-results_line="$(grep -nF ' print_results' "$GATE" | head -1 | cut -d: -f1)"
+cleanup_fail_line="$(grep -nF 'fail "fixture cleanup, HCC restoration, or lock finalization did not complete' "$WATCH_GATE" | cut -d: -f1)"
+results_line="$(grep -nF ' print_results' "$WATCH_GATE" | head -1 | cut -d: -f1)"
if [ -n "$cleanup_fail_line" ] && [ -n "$results_line" ] && [ "$cleanup_fail_line" -lt "$results_line" ]; then
pass "cleanup failure is counted before the final result summary"
else