diff --git a/changelog.d/2791-native-worker-deploy.md b/changelog.d/2791-native-worker-deploy.md new file mode 100644 index 00000000..93068848 --- /dev/null +++ b/changelog.d/2791-native-worker-deploy.md @@ -0,0 +1 @@ +- `scripts/a2a-termux-native-worker-deploy.sh` (#2791 stage 3, owner decision 2026-11-27: the deploy side restarts a redeployed `worker.js`, and its script lives here): canonical tar deploy of the Termux-native worker artifact, replacing per-rollout ad-hoc scripts. Dry-run by default (plan + idle gate, nothing changes); `--apply` runs the idle gate via `restart-worker --if-idle --dry-run`, backs up the worker root and each replaced `node_modules` package, copies `dist/`/`scripts/`/`handlers/`, checks the build revision, the artifact's own rollout guard and an optional `--smoke-cmd`, then restarts only `worker.js` through `restart-worker --if-idle` (verified by `registered with` + health `sup_count=1 workers=1 tunnel=UP`) and writes `.deploy-source-sha`. Any failure rolls the root back exactly (20 before restart; 30 after an unverified restart, which also restarts on the old files); busy exits 10 without signaling the worker. Tar members with absolute paths, `..`, devices or escaping links are refused. diff --git a/docs/a2a-claude-worker.md b/docs/a2a-claude-worker.md index d5145352..31f3b4f2 100644 --- a/docs/a2a-claude-worker.md +++ b/docs/a2a-claude-worker.md @@ -236,6 +236,55 @@ self-update only warns about it. Self-update may restart a stale supervise loop of its own checkout only on nodes that opt in with `CCC_SELF_UPDATE_NATIVE_SUPERVISOR_RESTART=1` (default 0, docs/self-update.md). +### Deploying `dist/worker.js` (#2791 stage 3) + +`scripts/a2a-termux-native-worker-deploy.sh` is the canonical tar deploy of +the worker artifact. It replaces the per-rollout ad-hoc scripts and owns the +worker restart after a redeploy. It is **dry-run by default**: + +```bash +# Plan + idle gate only; nothing on the node changes. +scripts/a2a-termux-native-worker-deploy.sh --env-file /path/canonical.env \ + --artifact /path/artifact.tgz --target-sha <40-hex> +# Perform it. +scripts/a2a-termux-native-worker-deploy.sh --env-file /path/canonical.env \ + --artifact /path/artifact.tgz --target-sha <40-hex> --apply +``` + +`--artifact` is a directory or a tar(.gz) whose top level (or one wrapping +directory) holds `dist/worker.js`; tar members with absolute paths, `..`, +device nodes or escaping links are refused. With `--apply` the order is: + +1. idle gate — `restart-worker --if-idle --dry-run` (busy → exit 10, nothing changed); +2. backups of the worker root (without `node_modules`) and of each + `node_modules` package the artifact replaces (default + `$HOME/a2a-nexus-local-deploy-backups`, `--backup-dir`); +3. copy `dist/`, `scripts/`, `handlers/` (overwrite) and replace the artifact's packages; +4. pre-restart checks: build revision = target, the artifact's own + `scripts/worker-artifact-rollout-guard.mjs --deployed` when shipped + (`--no-guard` skips it), then `--smoke-cmd` (run with `A2A_WORKER_ROOT`); + failure → exact rollback, exit 20, no restart; +5. `restart-worker --if-idle` — verified by `registered with` + health + `sup_count=1 workers=1 tunnel=UP`. Busy by now → rollback, exit 10 (never + signaled); not verified → rollback and restart on the old files, exit 30; +6. write `/.deploy-source-sha`. + +| rc | meaning | +|----|----------------------------------------------------------------------| +| 0 | deployed and verified (dry-run: plan + gate ok) | +| 2 | usage, invalid artifact, or revision ≠ `--target-sha` | +| 3 | no canonical supervisor / worker — nothing changed | +| 4 | another deploy holds the lock | +| 10 | busy — nothing changed (or files rolled back before any signal) | +| 11 | idle state unknown — nothing changed | +| 20 | pre-restart check failed — rolled back, no restart | +| 30 | restart not verified — rolled back and restarted on the old files | +| 31 | rollback failed — restore manually from the printed backups | + +Run it from the same checkout the supervisor runs (`restart-worker` only acts +on the supervisor whose script is beside it). Live rollouts still need the +usual per-node approval. + ## No-provider adapter smoke Before any real provider canary, run the bridge with a fake Claude binary so the JSON contract, executable path, and Node runtime are proven without spending provider quota: diff --git a/scripts/a2a-termux-native-worker-deploy.sh b/scripts/a2a-termux-native-worker-deploy.sh new file mode 100755 index 00000000..3eb126f1 --- /dev/null +++ b/scripts/a2a-termux-native-worker-deploy.sh @@ -0,0 +1,375 @@ +#!/usr/bin/env bash +# Canonical tar deploy of the Termux-native A2A worker artifact (#2791 stage 3). +# +# Owner decision 2026-11-27: restarting a redeployed dist/worker.js is the +# DEPLOY side's job (self-update only warns), and the deploy script lives here. +# This replaces the per-rollout ad-hoc scripts that each re-implemented the +# same idle gate / backup / restart / rollback steps. +# +# Usage: +# a2a-termux-native-worker-deploy.sh --env-file --artifact +# [--target-sha <40-hex>] [--backup-dir ] [--smoke-cmd ] +# [--no-guard] [--apply] +# +# Dry-run by default: validates the artifact, prints the plan and runs the idle +# gate (`restart-worker --if-idle --dry-run`) — nothing on the node changes. +# --apply performs, in order: +# 1. idle gate: `a2a-termux-native-worker.sh restart-worker --if-idle --dry-run` +# (busy → exit 10, nothing changed) +# 2. backups of the worker root (without node_modules) and of every +# node_modules package the artifact replaces; both archives are listed +# before anything is touched +# 3. copy dist/ scripts/ handlers/ (overwrite) and replace each artifact +# node_modules package +# 4. pre-restart checks: build revision == target, the artifact's own +# scripts/worker-artifact-rollout-guard.mjs (when shipped, unless +# --no-guard), then --smoke-cmd (run with A2A_WORKER_ROOT set). Any +# failure → rollback, exit 20, no restart +# 5. `restart-worker --if-idle`: SIGTERM only worker.js; the supervise loop +# relaunches it; the harness verifies "registered with" + health +# sup_count=1 workers=1 tunnel=UP. Busy now → rollback, exit 10 (the +# worker was never signaled). Not verified → rollback, restart again on +# the old files, exit 30 +# 6. write /.deploy-source-sha +# +# Exit codes: 0 ok (dry-run: plan ok), 2 usage / invalid artifact, 3 no +# supervisor or worker (nothing changed), 4 another deploy holds the lock, +# 10 busy (nothing changed — or files rolled back before any signal), +# 11 idle state unknown (nothing changed), 20 pre-restart check failed (rolled +# back, no restart), 30 restart not verified (rolled back + restarted), +# 31 rollback failed — MANUAL RESTORE from the printed backups. +# +# Env: A2A_DEPLOY_BACKUP_DIR (default $HOME/a2a-nexus-local-deploy-backups), +# A2A_NATIVE_WORKER_HARNESS (default: the harness beside this script; the +# running supervisor must be that same checkout's harness). +set -uo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +HARNESS="${A2A_NATIVE_WORKER_HARNESS:-$SCRIPT_DIR/a2a-termux-native-worker.sh}" +DEPLOY_DIRS=(dist scripts handlers) + +ENV_FILE=""; ARTIFACT=""; TARGET_SHA=""; SMOKE_CMD=""; APPLY=0; GUARD=1 +BACKUP_DIR="${A2A_DEPLOY_BACKUP_DIR:-$HOME/a2a-nexus-local-deploy-backups}" +STAGE_TMP=""; STAGE=""; ROOT="" + +say() { printf 'deploy: %s\n' "$*"; } +die() { printf 'deploy: %s\n' "$2" >&2; exit "$1"; } + +usage() { + sed -n '2,/^set -uo/{/^set -uo/d;s/^# \{0,1\}//;p}' "${BASH_SOURCE[0]}" >&2 + exit 2 +} + +cleanup() { if [[ -n "$STAGE_TMP" ]]; then rm -rf "$STAGE_TMP"; fi; } +trap cleanup EXIT + +# Same quoting rules as the Python validator. +extract_env_value() { + python3 - "$1" "$2" <<'PY' +import shlex, sys +key, path = sys.argv[1], sys.argv[2] +try: + for raw in open(path, encoding='utf-8'): + line = raw.strip() + if not line or line.startswith('#'): + continue + if line.startswith('export '): + line = line[len('export '):].strip() + if '=' not in line: + continue + k, v = line.split('=', 1) + if k.strip() != key: + continue + v = v.strip() + if v.startswith(('"', "'")): + try: + parts = shlex.split(v, posix=True) + if len(parts) == 1: + v = parts[0] + except ValueError: + pass + print(v) + break +except FileNotFoundError: + pass +PY +} + +build_rev() { # : first 40-hex in dist/build-info.json, empty if none + [[ -r "$1/dist/build-info.json" ]] || return 0 + grep -oE '[0-9a-f]{40}' "$1/dist/build-info.json" 2>/dev/null | head -n 1 +} + +# Extract a tar artifact into a private staging dir, refusing absolute paths, +# `..`, device nodes and links that escape the stage. +extract_tar() { # + python3 - "$1" "$2" <<'PY' +import os +import sys +import tarfile + +src, dest = sys.argv[1], os.path.realpath(sys.argv[2]) + + +def inside(path): + real = os.path.realpath(path) + return real == dest or real.startswith(dest + os.sep) + + +try: + with tarfile.open(src) as tf: + for m in tf.getmembers(): + parts = m.name.split("/") + if m.name.startswith("/") or ".." in parts: + sys.exit("unsafe member path: %s" % m.name) + if m.isdev() or m.isfifo(): + sys.exit("device/fifo member refused: %s" % m.name) + if m.issym() or m.islnk(): + base = dest if m.islnk() else os.path.dirname(os.path.join(dest, m.name)) + if os.path.isabs(m.linkname) or not inside(os.path.join(base, m.linkname)): + sys.exit("link escapes the artifact: %s -> %s" % (m.name, m.linkname)) + try: + tf.extractall(dest, filter="data") + except TypeError: # Python < 3.12 has no extraction filters + tf.extractall(dest) +except (OSError, tarfile.TarError) as exc: + sys.exit("unreadable artifact: %s" % exc) +PY +} + +# Resolve the artifact to a directory whose dist/worker.js exists. +stage_artifact() { + local src="$ARTIFACT" sub + if [[ -f "$src" ]]; then + STAGE_TMP=$(mktemp -d "${TMPDIR:-/tmp}/a2a-worker-deploy.XXXXXX") || die 2 "mktemp failed" + extract_tar "$src" "$STAGE_TMP" || die 2 "artifact tar rejected: $src" + src="$STAGE_TMP" + elif [[ ! -d "$src" ]]; then + die 2 "artifact not found: $src" + fi + if [[ -f "$src/dist/worker.js" ]]; then + STAGE="$(cd "$src" && pwd)" + return 0 + fi + # Accept one wrapping directory (e.g. a tar of artifact/). + local -a subs=() + for sub in "$src"/*/; do + [[ -f "$sub/dist/worker.js" ]] && subs+=("${sub%/}") + done + (( ${#subs[@]} == 1 )) || die 2 "artifact has no dist/worker.js (top level or one wrapping dir): $ARTIFACT" + STAGE="$(cd "${subs[0]}" && pwd)" +} + +# Top-level node_modules entries the artifact ships (scoped dirs as a unit; +# dot entries such as .bin are left alone, as the ad-hoc rollouts did). +artifact_packages() { + [[ -d "$STAGE/node_modules" ]] || return 0 + local p + for p in "$STAGE/node_modules"/*; do + [[ -e "$p" ]] || continue + printf '%s\n' "${p##*/}" + done +} + +# Run the gate/restart through the harness; echo its output, return its rc. +harness() { bash "$HARNESS" "$@" --env-file "$ENV_FILE"; } + +ROOT_BACKUP=""; NM_BACKUP=""; NM_REPLACED=(); NM_NEW=(); ROOT_MEMBERS=() + +make_backups() { # + local parent base ts nm_existing=() p + parent="$(dirname "$ROOT")"; base="$(basename "$ROOT")" + ts="$(date -u +%Y%m%dT%H%M%SZ)" + mkdir -p "$BACKUP_DIR" || return 1 + ROOT_BACKUP="$BACKUP_DIR/$base.pre-$1.$ts.tgz" + NM_BACKUP="$BACKUP_DIR/$base-node_modules.pre-$1.$ts.tgz" + tar czf "$ROOT_BACKUP" -C "$parent" --exclude="$base/node_modules" \ + --exclude="$base/dist.bak*" "$base" || return 1 + tar tzf "$ROOT_BACKUP" >/dev/null || return 1 + for p in "${NM_REPLACED[@]}"; do + if [[ -e "$ROOT/node_modules/$p" ]]; then nm_existing+=("$p"); else NM_NEW+=("$p"); fi + done + if (( ${#nm_existing[@]} )); then + tar czf "$NM_BACKUP" -C "$ROOT/node_modules" -- "${nm_existing[@]}" || return 1 + tar tzf "$NM_BACKUP" >/dev/null || return 1 + else + NM_BACKUP="" + fi + # Which deploy dirs (and the sha marker) existed before: rollback restores + # exactly these and removes what the artifact added. + local d + for d in "${DEPLOY_DIRS[@]}" .deploy-source-sha; do + [[ -e "$ROOT/$d" ]] && ROOT_MEMBERS+=("$base/$d") + done + return 0 +} + +rollback() { + local parent d p rc=0 + parent="$(dirname "$ROOT")" + say "ROLLBACK from $ROOT_BACKUP${NM_BACKUP:+ + $NM_BACKUP}" + for d in "${DEPLOY_DIRS[@]}" .deploy-source-sha; do rm -rf "${ROOT:?}/$d" || rc=1; done + if (( ${#ROOT_MEMBERS[@]} )); then + tar xzf "$ROOT_BACKUP" -C "$parent" -- "${ROOT_MEMBERS[@]}" || rc=1 + fi + for p in "${NM_REPLACED[@]}"; do rm -rf "${ROOT:?}/node_modules/$p" || rc=1; done + if [[ -n "$NM_BACKUP" ]]; then + tar xzf "$NM_BACKUP" -C "$ROOT/node_modules" || rc=1 + fi + return "$rc" +} + +rollback_or_die() { # + if ! rollback; then + die 31 "ROLLBACK FAILED after: $2 — MANUAL RESTORE from $ROOT_BACKUP${NM_BACKUP:+ and $NM_BACKUP}" + fi + die "$1" "$2; rolled back" +} + +copy_artifact() { + local d p + for d in "${DEPLOY_DIRS[@]}"; do + [[ -d "$STAGE/$d" ]] || continue + mkdir -p "$ROOT/$d" && cp -a "$STAGE/$d/." "$ROOT/$d/" || return 1 + done + if (( ${#NM_REPLACED[@]} )); then + mkdir -p "$ROOT/node_modules" || return 1 + for p in "${NM_REPLACED[@]}"; do + rm -rf "${ROOT:?}/node_modules/$p" && cp -a "$STAGE/node_modules/$p" "$ROOT/node_modules/$p" || return 1 + done + fi +} + +run_guard() { # the artifact's own rollout guard, when it ships one + local guard="$ROOT/scripts/worker-artifact-rollout-guard.mjs" out + (( GUARD )) && [[ -f "$guard" ]] || return 0 + out=$(A2A_WORKER_ROOT="$ROOT" ${TARGET_SHA:+A2A_WORKER_TARGET_REVISION="$TARGET_SHA"} \ + node "$guard" --deployed 2>&1) || { say "guard rc!=0: ${out##*$'\n'}"; return 1; } + python3 - "$out" <<'PY' +import json, sys +s = sys.argv[1] +try: + d = json.loads(s[s.index("{"):]) +except ValueError: + sys.exit("guard output is not JSON") +sys.exit(0 if d.get("ok") is True else "guard ok=%s" % d.get("ok")) +PY +} + +main() { + while [[ $# -gt 0 ]]; do + case "$1" in + --env-file|--artifact|--target-sha|--backup-dir|--smoke-cmd) + [[ $# -ge 2 ]] || die 2 "$1 requires a value" + case "$1" in + --env-file) ENV_FILE="$2" ;; + --artifact) ARTIFACT="$2" ;; + --target-sha) TARGET_SHA="$2" ;; + --backup-dir) BACKUP_DIR="$2" ;; + --smoke-cmd) SMOKE_CMD="$2" ;; + esac + shift 2 ;; + --apply) APPLY=1; shift ;; + --dry-run) APPLY=0; shift ;; + --no-guard) GUARD=0; shift ;; + -h|--help) usage ;; + *) printf 'deploy: unknown arg: %s\n' "$1" >&2; usage ;; + esac + done + [[ -n "$ENV_FILE" && -n "$ARTIFACT" ]] || { printf 'deploy: --env-file and --artifact are required\n' >&2; usage; } + [[ -f "$ENV_FILE" ]] || die 2 "env file not found: $ENV_FILE" + [[ -z "$TARGET_SHA" || "$TARGET_SHA" =~ ^[0-9a-f]{40}$ ]] || die 2 "--target-sha must be 40 lowercase hex" + [[ -f "$HARNESS" ]] || die 2 "harness not found: $HARNESS" + + ROOT=$(extract_env_value A2A_WORKER_ROOT "$ENV_FILE") + ROOT="${ROOT/#\~/$HOME}" + [[ -n "$ROOT" && -d "$ROOT" ]] || die 2 "A2A_WORKER_ROOT missing or not a directory in $ENV_FILE" + ROOT="$(cd "$ROOT" && pwd)" + local script + script=$(extract_env_value A2A_WORKER_SCRIPT "$ENV_FILE") + if [[ -n "$script" && "$(realpath -m "${script/#\~/$HOME}")" != "$(realpath -m "$ROOT/dist/worker.js")" ]]; then + die 2 "A2A_WORKER_SCRIPT is not /dist/worker.js; this deploy only handles the default layout" + fi + + stage_artifact + local staged_rev current_rev source_sha + staged_rev=$(build_rev "$STAGE"); current_rev=$(build_rev "$ROOT") + if [[ -n "$TARGET_SHA" && -n "$staged_rev" && "$staged_rev" != "$TARGET_SHA" ]]; then + die 2 "artifact revision $staged_rev != --target-sha $TARGET_SHA" + fi + source_sha="${TARGET_SHA:-$staged_rev}" + [[ -n "$source_sha" ]] || die 2 "no source revision: artifact has no dist/build-info.json revision; pass --target-sha" + mapfile -t NM_REPLACED < <(artifact_packages) + local -a present=() + local d + for d in "${DEPLOY_DIRS[@]}"; do [[ -d "$STAGE/$d" ]] && present+=("$d/"); done + + say "plan mode=$([[ $APPLY = 1 ]] && echo apply || echo dry-run) root=$ROOT" + say "plan rev ${current_rev:-unknown} -> $source_sha (artifact ${staged_rev:-no build-info})" + say "plan copy ${present[*]} node_modules=[${NM_REPLACED[*]}] guard=$([[ $GUARD = 1 ]] && echo auto || echo off) smoke=$([[ -n $SMOKE_CMD ]] && echo yes || echo no)" + say "plan backups -> $BACKUP_DIR; restart via $(basename "$HARNESS") restart-worker --if-idle" + + # 1. idle gate (nothing changes on refusal). + local out rc + out=$(harness restart-worker --if-idle --dry-run 2>&1); rc=$? + printf '%s\n' "$out" + case "$rc" in + 0) ;; + 10) die 10 "BUSY: worker is running a task — nothing changed, retry later" ;; + 11) die 11 "idle state unknown — nothing changed" ;; + 3) die 3 "no canonical supervisor / worker — nothing changed" ;; + *) die 2 "idle gate failed rc=$rc — nothing changed" ;; + esac + if (( ! APPLY )); then + say "DRY-RUN OK — nothing changed (re-run with --apply)" + return 0 + fi + + mkdir -p "$BACKUP_DIR" || die 2 "cannot create backup dir $BACKUP_DIR" + exec 9>"$BACKUP_DIR/.deploy.lock" + flock -n 9 || die 4 "another deploy holds $BACKUP_DIR/.deploy.lock" + + # 2. backups. + make_backups "${source_sha:0:12}" || die 20 "backup failed — nothing changed" + say "backup $ROOT_BACKUP${NM_BACKUP:+ + $NM_BACKUP}" + + # 3. copy. + copy_artifact || rollback_or_die 20 "artifact copy failed (no restart)" + + # 4. pre-restart checks. + local new_rev + new_rev=$(build_rev "$ROOT") + if [[ -n "$staged_rev" && "$new_rev" != "$staged_rev" ]]; then + rollback_or_die 20 "deployed revision ${new_rev:-none} != artifact $staged_rev (no restart)" + fi + run_guard || rollback_or_die 20 "rollout guard failed (no restart)" + if [[ -n "$SMOKE_CMD" ]]; then + A2A_WORKER_ROOT="$ROOT" bash -c "$SMOKE_CMD" || rollback_or_die 20 "smoke command failed (no restart)" + fi + + # 5. restart worker.js only; the harness verifies registration + health. + out=$(harness restart-worker --if-idle 2>&1); rc=$? + printf '%s\n' "$out" + case "$rc" in + 0) ;; + 10|11) rollback_or_die 10 "worker became busy before the restart (never signaled)" ;; + 3) rollback_or_die 30 "no worker to restart" ;; + *) + rollback || die 31 "ROLLBACK FAILED after unverified restart — MANUAL RESTORE from $ROOT_BACKUP${NM_BACKUP:+ and $NM_BACKUP}" + local again arc + again=$(harness restart-worker --if-idle 2>&1); arc=$? + printf '%s\n' "$again" + die 30 "restart not verified (rc=$rc); rolled back to ${current_rev:-previous}, restart on old files rc=$arc" + ;; + esac + + # 6. record what is now serving. + printf '%s\n' "$source_sha" > "$ROOT/.deploy-source-sha.tmp" && + mv -f "$ROOT/.deploy-source-sha.tmp" "$ROOT/.deploy-source-sha" || + say "WARN could not write $ROOT/.deploy-source-sha" + say "OK rev ${current_rev:-unknown} -> $source_sha | ${out##*$'\n'}" +} + +if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then + main "$@" +fi diff --git a/scripts/a2a-termux-native-worker-deploy.test.sh b/scripts/a2a-termux-native-worker-deploy.test.sh new file mode 100755 index 00000000..18ca0a4d --- /dev/null +++ b/scripts/a2a-termux-native-worker-deploy.test.sh @@ -0,0 +1,198 @@ +#!/usr/bin/env bash +# Tests for the canonical Termux-native worker deploy (#2791 stage 3). +# +# The harness's restart-worker (tested in a2a-termux-native-worker-restart.test.sh) +# is replaced by a recorder via A2A_NATIVE_WORKER_HARNESS: its gate rc comes +# from $TMP/gate.rc and each real restart pops the next rc from +# $TMP/restart.rcs. A fake `node` on PATH plays the artifact's rollout guard. +set -uo pipefail +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +DEPLOY="$ROOT/scripts/a2a-termux-native-worker-deploy.sh" +# shellcheck source=claude/hooks/lib/test-stub.sh +. "$ROOT/claude/hooks/lib/test-stub.sh" +ccc_test_reset_hook_env + +pass=0; fail=0 +TMP="$(ccc_test_tmpdir)" || exit 1 +trap 'rm -rf "$TMP"' EXIT + +ok() { + if eval "$2"; then + pass=$((pass+1)) + else + fail=$((fail+1)) + echo "FAIL: $1" + echo " cond: $2" + [[ -n "${out:-}" ]] && printf ' out: %s\n' "$out" + fi +} + +OLD_SHA=1111111111111111111111111111111111111111 +NEW_SHA=2222222222222222222222222222222222222222 +WROOT="$TMP/home/a2a-broker-worker" +BK="$TMP/backups" +ENVF="$TMP/canonical.env" +printf 'A2A_WORKER_ROOT=%s\nA2A_TUNNEL_SSH_TARGET=fake\n' "$WROOT" > "$ENVF" + +# Live worker root: old build, an extra dist file the artifact does not ship, +# a node_modules package the artifact replaces and one it must not touch. +reset_root() { + rm -rf "$WROOT"; mkdir -p "$WROOT/dist" "$WROOT/scripts" "$WROOT/node_modules/a2a-core" "$WROOT/node_modules/left-alone" + echo 'old worker' > "$WROOT/dist/worker.js" + echo 'old only' > "$WROOT/dist/legacy.js" + printf '{"revision":"%s"}\n' "$OLD_SHA" > "$WROOT/dist/build-info.json" + echo 'old script' > "$WROOT/scripts/tool.mjs" + echo 'old core' > "$WROOT/node_modules/a2a-core/index.js" + echo 'keep' > "$WROOT/node_modules/left-alone/index.js" + echo "$OLD_SHA" > "$WROOT/.deploy-source-sha" + echo 'state' > "$WROOT/worker-state.json" +} +snapshot() { (cd "$WROOT" && find . -type f -print0 | sort -z | xargs -0 sha256sum; find . | sort) | sha256sum; } + +# Artifact: new build + a new handlers/ dir + replaced and new packages. +ART="$TMP/stage/artifact" +mkdir -p "$ART/dist" "$ART/scripts" "$ART/handlers" "$ART/node_modules/a2a-core" "$ART/node_modules/a2a-new" +echo 'new worker' > "$ART/dist/worker.js" +printf '{"revision":"%s"}\n' "$NEW_SHA" > "$ART/dist/build-info.json" +echo 'new script' > "$ART/scripts/tool.mjs" +echo 'handler' > "$ART/handlers/h.mjs" +echo 'new core' > "$ART/node_modules/a2a-core/index.js" +echo 'brand new' > "$ART/node_modules/a2a-new/index.js" +tar czf "$TMP/artifact.tgz" -C "$TMP/stage" artifact + +cat > "$TMP/fake-harness.sh" <> "$TMP/harness.calls" +if [[ " \$* " == *" --dry-run "* ]]; then + rc=\$(cat "$TMP/gate.rc" 2>/dev/null || echo 0) +else + rc=\$(head -n1 "$TMP/restart.rcs" 2>/dev/null); rc=\${rc:-0} + sed -i '1d' "$TMP/restart.rcs" 2>/dev/null || true + printf 'worker.js at restart: %s\n' "\$(cat "$WROOT/dist/worker.js")" >> "$TMP/harness.calls" +fi +echo "restart-worker: result=fake rc=\$rc sup_count=1 workers=1 tunnel=UP" +exit "\$rc" +EOF +chmod +x "$TMP/fake-harness.sh" +mkdir -p "$TMP/bin" +cat > "$TMP/bin/node" <> "$TMP/node.calls" +cat "$TMP/guard.out" 2>/dev/null || echo '{"ok":true}' +EOF +chmod +x "$TMP/bin/node" +export PATH="$TMP/bin:$PATH" +export A2A_NATIVE_WORKER_HARNESS="$TMP/fake-harness.sh" +export A2A_DEPLOY_BACKUP_DIR="$BK" + +# shellcheck disable=SC2034 # BEFORE is read by the eval-based ok() assertions. +fresh() { reset_root; rm -rf "$BK" "$TMP/harness.calls" "$TMP/restart.rcs" "$TMP/gate.rc" "$TMP/guard.out" "$TMP/node.calls"; BEFORE=$(snapshot); } +mkdir -p "$TMP/stagetmp" +deploy() { TMPDIR="$TMP/stagetmp" bash "$DEPLOY" --env-file "$ENVF" "$@" 2>&1; } +restart_calls() { grep -c -- '--if-idle --env-file' "$TMP/harness.calls" 2>/dev/null | head -n1; } +gate_calls() { grep -c -- '--if-idle --dry-run --env-file' "$TMP/harness.calls" 2>/dev/null | head -n1; } + +# ---- 1. usage / artifact validation (rc=2, nothing touched) ------------------ +fresh +out=$(bash "$DEPLOY" 2>&1); rc=$? +ok "no args prints usage rc=2" '[ "$rc" = 2 ] && grep -q "Usage:" <<<"$out"' +out=$(deploy --artifact "$TMP/nope"); rc=$? +ok "missing artifact rc=2" '[ "$rc" = 2 ] && grep -q "artifact not found" <<<"$out"' +mkdir -p "$TMP/empty-art" +out=$(deploy --artifact "$TMP/empty-art"); rc=$? +ok "artifact without dist/worker.js rc=2" '[ "$rc" = 2 ] && grep -q "no dist/worker.js" <<<"$out"' +out=$(deploy --artifact "$ART" --target-sha "$OLD_SHA"); rc=$? +ok "artifact revision != --target-sha rc=2" '[ "$rc" = 2 ] && grep -q "!= --target-sha" <<<"$out"' +out=$(deploy --artifact "$ART" --target-sha nothex); rc=$? +ok "malformed --target-sha rc=2" '[ "$rc" = 2 ]' +python3 - "$TMP/evil.tgz" <<'PY' +import io, sys, tarfile +with tarfile.open(sys.argv[1], "w:gz") as tf: + data = b"x" + info = tarfile.TarInfo("../escape.js"); info.size = len(data) + tf.addfile(info, io.BytesIO(data)) +PY +out=$(deploy --artifact "$TMP/evil.tgz"); rc=$? +ok "tar member with .. is refused rc=2" '[ "$rc" = 2 ] && grep -q "unsafe member" <<<"$out" && [ ! -e "$TMP/escape.js" ]' +ok "validation failures never reach the gate or the root" '[ ! -e "$TMP/harness.calls" ] && [ "$(snapshot)" = "$BEFORE" ]' + +# ---- 2. dry-run is the default ---------------------------------------------- +fresh +out=$(deploy --artifact "$ART"); rc=$? +ok "dry-run (default) exits 0 with a plan" \ + '[ "$rc" = 0 ] && grep -q "plan mode=dry-run" <<<"$out" && grep -q "plan rev $OLD_SHA -> $NEW_SHA" <<<"$out" && grep -q "DRY-RUN OK" <<<"$out"' +ok "dry-run plan lists dirs and replaced packages" \ + 'grep -q "plan copy dist/ scripts/ handlers/ node_modules=\[a2a-core a2a-new\]" <<<"$out"' +ok "dry-run runs only the gate (restart-worker --if-idle --dry-run)" \ + '[ "$(gate_calls)" = 1 ] && [ "$(restart_calls)" = 0 ]' +ok "dry-run changes nothing and writes no backup" '[ "$(snapshot)" = "$BEFORE" ] && [ ! -e "$BK" ]' + +# ---- 3. idle refusal ---------------------------------------------------------- +fresh; echo 10 > "$TMP/gate.rc" +out=$(deploy --artifact "$ART" --apply); rc=$? +ok "busy at the gate: --apply exits 10 with the reason" '[ "$rc" = 10 ] && grep -q "BUSY" <<<"$out" && grep -q "nothing changed" <<<"$out"' +ok "busy at the gate: no restart, no backup, root untouched" \ + '[ "$(restart_calls)" = 0 ] && [ ! -e "$BK" ] && [ "$(snapshot)" = "$BEFORE" ]' +fresh; echo 3 > "$TMP/gate.rc" +out=$(deploy --artifact "$ART" --apply); rc=$? +ok "no supervisor/worker at the gate: exit 3, nothing changed" '[ "$rc" = 3 ] && [ "$(snapshot)" = "$BEFORE" ]' + +# ---- 4. successful apply (directory and tar artifacts) ---------------------- +for kind in dir tar; do + fresh + src="$ART"; [[ "$kind" = tar ]] && src="$TMP/artifact.tgz" + out=$(deploy --artifact "$src" --target-sha "$NEW_SHA" --apply); rc=$? + ok "$kind artifact: --apply succeeds" '[ "$rc" = 0 ] && grep -q "OK rev $OLD_SHA -> $NEW_SHA" <<<"$out"' + ok "$kind artifact: files and packages replaced, others kept" \ + '[ "$(cat "$WROOT/dist/worker.js")" = "new worker" ] && [ -f "$WROOT/handlers/h.mjs" ] && [ "$(cat "$WROOT/node_modules/a2a-core/index.js")" = "new core" ] && [ -f "$WROOT/node_modules/a2a-new/index.js" ] && [ "$(cat "$WROOT/node_modules/left-alone/index.js")" = keep ] && [ -f "$WROOT/dist/legacy.js" ]' + ok "$kind artifact: .deploy-source-sha names the new revision" '[ "$(cat "$WROOT/.deploy-source-sha")" = "$NEW_SHA" ]' + ok "$kind artifact: one gate + one restart, restart saw the new files" \ + '[ "$(gate_calls)" = 1 ] && [ "$(restart_calls)" = 1 ] && grep -q "worker.js at restart: new worker" "$TMP/harness.calls"' + ok "$kind artifact: root + node_modules backups exist" \ + '[ "$(compgen -G "$BK/a2a-broker-worker.pre-222222222222.*.tgz" | wc -l)" = 1 ] && [ "$(compgen -G "$BK/a2a-broker-worker-node_modules.pre-*.tgz" | wc -l)" = 1 ]' +done +ok "tar artifact staging is cleaned up" '[ -z "$(ls -A "$TMP/stagetmp")" ]' + +# ---- 5. rollback paths -------------------------------------------------------- +# 5a. pre-restart smoke failure -> exact rollback, no restart. +fresh +out=$(deploy --artifact "$ART" --apply --smoke-cmd 'test "$(cat "$A2A_WORKER_ROOT/dist/worker.js")" = "never"'); rc=$? +ok "smoke failure: exit 20, rolled back" '[ "$rc" = 20 ] && grep -q "smoke command failed (no restart); rolled back" <<<"$out"' +ok "smoke failure: root restored exactly (added files removed) and no restart" \ + '[ "$(snapshot)" = "$BEFORE" ] && [ "$(restart_calls)" = 0 ]' + +# 5b. the artifact's own rollout guard says not ok -> rollback. +fresh; mkdir -p "$ART/scripts"; : > "$ART/scripts/worker-artifact-rollout-guard.mjs"; echo '{"ok":false}' > "$TMP/guard.out" +out=$(deploy --artifact "$ART" --apply); rc=$? +ok "guard ok=false: exit 20, rolled back, no restart" \ + '[ "$rc" = 20 ] && grep -q "rollout guard failed" <<<"$out" && [ "$(snapshot)" = "$BEFORE" ] && [ "$(restart_calls)" = 0 ] && grep -q -- "--deployed" "$TMP/node.calls"' +fresh; echo '{"ok":false}' > "$TMP/guard.out" +out=$(deploy --artifact "$ART" --apply --no-guard); rc=$? +ok "--no-guard skips the shipped guard" '[ "$rc" = 0 ] && [ ! -e "$TMP/node.calls" ]' +rm -f "$ART/scripts/worker-artifact-rollout-guard.mjs" + +# 5c. restart not verified -> rollback + a second restart on the old files. +fresh; printf '30\n0\n' > "$TMP/restart.rcs" +out=$(deploy --artifact "$ART" --apply); rc=$? +ok "unverified restart: exit 30" '[ "$rc" = 30 ] && grep -q "restart not verified (rc=30); rolled back to $OLD_SHA, restart on old files rc=0" <<<"$out"' +ok "unverified restart: root restored and re-restarted on old code" \ + '[ "$(snapshot)" = "$BEFORE" ] && [ "$(restart_calls)" = 2 ] && [ "$(grep "worker.js at restart" "$TMP/harness.calls" | tail -n1)" = "worker.js at restart: old worker" ]' + +# 5d. worker became busy between gate and restart -> rollback, never signaled. +fresh; printf '10\n' > "$TMP/restart.rcs" +out=$(deploy --artifact "$ART" --apply); rc=$? +ok "busy at restart: exit 10, rolled back, single (refused) restart call" \ + '[ "$rc" = 10 ] && grep -q "became busy" <<<"$out" && [ "$(snapshot)" = "$BEFORE" ] && [ "$(restart_calls)" = 1 ]' + +# ---- 6. concurrent deploys are refused ----------------------------------------- +fresh; mkdir -p "$BK" +exec 8>"$BK/.deploy.lock"; flock -n 8 +out=$(deploy --artifact "$ART" --apply) +# shellcheck disable=SC2034 # rc is read by the eval-based ok() assertion. +rc=$? +ok "a held deploy lock: exit 4, nothing changed" '[ "$rc" = 4 ] && [ "$(snapshot)" = "$BEFORE" ] && [ "$(restart_calls)" = 0 ]' +exec 8>&- + +echo "----" +echo "PASS=$pass FAIL=$fail" +[ "$fail" = 0 ]