From 32cba922ce4ef3af581e7552bea3bd6fe11680dc Mon Sep 17 00:00:00 2001 From: jesus Date: Wed, 18 Nov 2026 08:54:20 +0100 Subject: [PATCH] feat(update): safely activate staged Desktop Commander with rollback --- bin/dotfiles-dc-activate | 165 ++++++++++ docs/UPDATE.md | 62 +++- .../bin/symlink_dotfiles-dc-activate.tmpl | 1 + scripts/dc/validate.cjs | 80 +++++ scripts/update/lib/dc_local.sh | 2 +- tests/Makefile.tests | 8 +- tests/bats/system/dc-activate.bats | 292 ++++++++++++++++++ 7 files changed, 606 insertions(+), 4 deletions(-) create mode 100755 bin/dotfiles-dc-activate create mode 100644 dot_local/bin/symlink_dotfiles-dc-activate.tmpl create mode 100644 scripts/dc/validate.cjs create mode 100644 tests/bats/system/dc-activate.bats diff --git a/bin/dotfiles-dc-activate b/bin/dotfiles-dc-activate new file mode 100755 index 0000000..f1d863a --- /dev/null +++ b/bin/dotfiles-dc-activate @@ -0,0 +1,165 @@ +#!/usr/bin/env bash +# Human-only activation. Updaters and agents must never invoke --apply on a live HOME. +set -euo pipefail +umask 077 +repo="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/.." && pwd)" +validator="$repo/scripts/dc/validate.cjs" +mode=dry-run +version= +health_url='http://127.0.0.1:49187/readyz' +for_arg_mode=0 +while (($#)); do + case "$1" in + --help | -h) + cat <<'HELP' +Usage: dotfiles-dc-activate [--status|--dry-run|--apply] [VERSION] [--health-url URL] +Default: read-only status, or preflight/dry-run when VERSION is supplied. +VERSION must be exact stable semver. --apply requires VERSION; default readiness endpoint is http://127.0.0.1:49187/readyz. +Health URL must be HTTP loopback without credentials or query parameters. +HUMAN ONLY: invoke --apply from a separate WSL terminal; disconnects the tunnel. +Never invoke --apply from updater/agent sessions. Failed candidates remain staged. +HELP + exit 0 + ;; + --apply | --dry-run | --status) + ((for_arg_mode == 0)) || { + echo 'ERROR: conflicting modes' >&2 + exit 1 + } + mode="${1#--}" + for_arg_mode=1 + ;; + --health-url) + (($# >= 2)) || exit 1 + health_url="$2" + shift + ;; + -*) + echo 'ERROR: unknown option' >&2 + exit 1 + ;; + *) + [[ -z "$version" ]] || exit 1 + version="$1" + ;; + esac + shift +done +fail() { + echo "ERROR: $*" >&2 + exit 1 +} +share="$HOME/.local/share" +active="$share/ixatu-mcp" +stages="$share/ixatu-mcp-staged" +service=ixatu-wsl-mcp.service +node "$validator" paths "$active" "$share" +old="$(node "$validator" version "$active")" +if [[ -z "$version" || "$mode" == status ]]; then + [[ "$mode" != apply ]] || fail '--apply requires VERSION' + printf 'ACTIVE %s; status only; no changes made\n' "$old" + if [[ -d "$stages" && ! -L "$stages" ]]; then + find "$stages" -mindepth 1 -maxdepth 1 -type d -printf 'STAGED %f\n' + fi + exit 0 +fi +[[ "$version" =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]] || fail 'exact stable semver required' +if [[ "$version" == "$old" ]]; then + echo "ACTIVE $old; already active; no changes made" + exit 0 +fi +[[ "$(printf '%s\n%s\n' "$version" "$old" | sort -V | tail -n 1)" == "$version" ]] || fail 'version must be newer than active' +stage="$stages/$version" +node "$validator" paths "$stage" "$active" +node "$validator" stage "$stage" "$version" "$(command -v npm)" +[[ "$(systemctl --user show "$service" --property=LoadState --value)" == loaded ]] || fail 'service is not present' +systemctl --user is-active --quiet "$service" || fail 'service is not active' +node "$validator" url "$health_url" +if [[ "$mode" != apply ]]; then + echo "DRY-RUN: validated STAGED $version; ACTIVE $old; no changes made" + exit 0 +fi +# Lock the owned share directory inode: no lockfile/symlink opening or dry-run writes. +exec {lock_fd}<"$share" +flock -n -x "$lock_fd" || fail 'another activation is running' +# Repeat preflight while holding the lock, before any service mutation. +node "$validator" paths "$stage" "$active" +[[ "$(node "$validator" version "$active")" == "$old" ]] || fail 'active changed during preflight' +node "$validator" stage "$stage" "$version" "$(command -v npm)" +systemctl --user is-active --quiet "$service" || fail 'service is not active' +# Renames use -T and an empty reserved destination, never merge directories. +[[ "$(stat -c %d "$active")" == "$(stat -c %d "$stage")" ]] || fail 'cross-device activation refused' +transaction=0 +child_ready() { + local main pid command count=0 + local -a pending + main="$(systemctl --user show "$service" --property=MainPID --value)" || return 1 + [[ "$main" =~ ^[1-9][0-9]*$ ]] || return 1 + pending=("$main") + while ((${#pending[@]} && count < 256)); do + pid="${pending[0]}" + pending=("${pending[@]:1}") + count=$((count + 1)) + while read -r pid command; do + [[ "$pid" =~ ^[1-9][0-9]*$ ]] || continue + if [[ "$command" == *"$active/node_modules/@wonderwhy-er/desktop-commander/"* ]]; then return 0; fi + pending+=("$pid") + done < <(pgrep -a -P "$pid" 2>/dev/null || true) + done + return 1 +} +ready() { + local expected_version="$1" deadline=$((SECONDS + 30)) http_code + while ((SECONDS < deadline)); do + if systemctl --user is-active --quiet "$service" && + [[ "$(node "$validator" version "$active" 2>/dev/null)" == "$expected_version" ]] && + child_ready && + http_code="$(curl --disable --noproxy '*' --proto '=http' --fail --silent --output /dev/null --write-out '%{http_code}' --connect-timeout 1 --max-time 1 "$health_url")" && + [[ "$http_code" == 2[0-9][0-9] ]]; then + return 0 + fi + sleep 1 + done + return 1 +} +# shellcheck disable=SC2329 +cleanup() { + local rc=$? + trap - EXIT + trap '' HUP INT TERM + if ((transaction)); then + # Do not move a possibly running candidate. Keep both copies if stopping fails. + if systemctl --user stop "$service" >/dev/null 2>&1; then + if [[ -d "$backup/node_modules" ]]; then + if [[ -d "$active" ]]; then mv -T -- "$active" "$stage" || rc=1; fi + if [[ ! -e "$active" ]]; then mv -T -- "$backup" "$active" || rc=1; fi + fi + else + echo 'ERROR: rollback stop failed; copies retained for manual recovery' >&2 + fi + if systemctl --user start "$service" >/dev/null 2>&1 && ready "$old"; then + echo 'ROLLBACK: previous runtime restored' >&2 + else + echo 'ERROR: rollback requires manual service recovery; backup retained' >&2 + fi + rc=1 + fi + # Only remove our empty reservation, never a runtime or an old backup. + rmdir -- "$backup" 2>/dev/null || true + exit "$rc" +} +backup="$(mktemp -d "$share/ixatu-mcp-rollback-$old-XXXXXXXX")" +trap cleanup EXIT +trap 'exit 129' HUP +trap 'exit 130' INT +trap 'exit 143' TERM +transaction=1 +systemctl --user stop "$service" >/dev/null 2>&1 || fail 'service stop failed' +mv -T -- "$active" "$backup" +mv -T -- "$stage" "$active" +systemctl --user start "$service" >/dev/null 2>&1 || fail 'service start failed' +ready "$version" || fail 'readiness timed out; rolling back' +# Success is committed before best-effort output (e.g. a closed terminal pipe). +transaction=0 +printf 'ACTIVE %s; rollback backup: %s\n' "$version" "${backup##*/}" || true +exit 0 diff --git a/docs/UPDATE.md b/docs/UPDATE.md index eecd939..cd21caa 100644 --- a/docs/UPDATE.md +++ b/docs/UPDATE.md @@ -357,12 +357,72 @@ latest stable release respectively. A newer Desktop Commander is installed with its exact version, npm integrity verification, lockfile, and scripts disabled into `~/.local/share/ixatu-mcp-staged/` only. The running MCP is never replaced or restarted: a `STAGED`/`ACTIVATION_PENDING` warning describes the -manual activation needed. The snapshot continues to report the **active** +manual activation command (`dotfiles-dc-activate --apply`). The snapshot continues to report the **active** installed version, not the staged version. A newer Tunnel Client is reported as available for separately verified, manual update; the running binary is never overwritten by the updater. Network failures are warnings, never reported as successful upgrades. No credentials are needed for these checks. +#### Explicit activation (human only) + +`dotfiles-dc-activate` is published through the existing Chezmoi symlink +pattern. Before materialization, use `./bin/dotfiles-dc-activate` from the +checkout. The updater never calls activation. Agents must only test with +mocked commands and a temporary HOME; never activate the live tunnel. + +```bash +dotfiles-dc-activate --status # default: read-only active/staged listing +dotfiles-dc-activate 0.3.4 # validate staged candidate; dry-run +# HUMAN ONLY, from a separate WSL terminal: interrupts ChatGPT's tunnel. +# Default health URL is http://127.0.0.1:49187/readyz +dotfiles-dc-activate 0.3.4 --apply +# Optional override if this computer uses a different tunnel port: +# dotfiles-dc-activate 0.3.4 --apply --health-url http://127.0.0.1:49188/readyz +``` + +An exact stable version newer than active is required. Already active is a +no-op; absent stages, prereleases, downgrades and conflicting modes fail. +Preflight requires a loaded, active `ixatu-wsl-mcp.service`, matching package +metadata, exact root dependency and package versions in npm lockfiles, +matching valid sha512 SRI in the install and hidden lockfile, and Node engine +compatibility with the invoking Node using the installed npm's semver library. This checks the +recorded integrity metadata; npm verified archive bytes when staging. It does +not independently authenticate an installed tree modified by its owner. +No candidate code or install scripts run during validation; no network +package resolution occurs. + +HOME and ancestors down to both runtime roots must be real, owned directories, +without group/other write access. Candidate contents reject external/dangling +symlinks, special files, hardlinks and writes by other users; internal npm +symlinks are allowed. Correct unsafe permissions manually after reviewing +ownership. Activation uses same-filesystem directory renames, an exclusive +`flock` on the share directory and a unique +`ixatu-mcp-rollback--` backup, preserving older backups. +Dry-run/status create no locks, backups or logs. The lock serializes this CLI; +do not run the updater or modify staging concurrently with human activation. + +Only `--apply` stops the service, moves active to backup, moves staged to +active, and starts the service. For up to 30 seconds it retries service +readiness, active metadata version, a Desktop Commander process under the +service's MainPID (including nested descendants, with the active package path +in its command), and HTTP health. The health URL must use literal HTTP +loopback, without credentials, queries or fragments. Curl ignores `.curlrc`, bypasses proxies, accepts only HTTP 2xx, +does not follow redirects and discards response bodies. Use a read-only `/health` +or `/health/control-plane` endpoint; the script never invokes MCP tools or +prints service environment/health bodies. There is no guessed default port. + +Failure or HUP/INT/TERM triggers rollback: stop the candidate before moving +it back to staging, restore the backup and start/check the previous runtime. +The command exits nonzero even after successful rollback; the failing stage +is retained for inspection/retry. If stopping or restoration fails, copies +are retained and manual recovery is reported. SIGKILL, power loss and storage +failure cannot be recovered by a shell trap: inspect the preserved backup +from a separate terminal. Success keeps the previous runtime as a rollback +backup; final output failure cannot reverse a successful activation. + +Regression tests: `make bats-dc-activate` (temporary HOME, mocked +systemctl/curl/pgrep); also included in `make test-ci`. + The Python CI quality step uses Ruff's correctness rules for the existing Python tree, and initially gates ty and Pyright on the winget log parser; expanding full-repository typing requires resolving older typing diagnostics. diff --git a/dot_local/bin/symlink_dotfiles-dc-activate.tmpl b/dot_local/bin/symlink_dotfiles-dc-activate.tmpl new file mode 100644 index 0000000..675b756 --- /dev/null +++ b/dot_local/bin/symlink_dotfiles-dc-activate.tmpl @@ -0,0 +1 @@ +{{ .chezmoi.homeDir }}/dotfiles/bin/dotfiles-dc-activate diff --git a/scripts/dc/validate.cjs b/scripts/dc/validate.cjs new file mode 100644 index 0000000..e556cb8 --- /dev/null +++ b/scripts/dc/validate.cjs @@ -0,0 +1,80 @@ +// Read metadata only: never require code from a candidate installation. +const fs = require('node:fs'); +const path = require('node:path'); +const { createRequire } = require('node:module'); +const [mode, root, expected, npm] = process.argv.slice(2); +const name = '@wonderwhy-er/desktop-commander'; +const key = `node_modules/${name}`; +const stable = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/; +const read = file => JSON.parse(fs.readFileSync(file, 'utf8')); +const check = (condition) => { if (!condition) throw new Error('validation'); }; +try { + if (mode === 'url') { + const url = new URL(root); + check(url.protocol === 'http:' && ['127.0.0.1', '[::1]'].includes(url.hostname)); + check(!url.username && !url.password && !url.search && !url.hash); + } else if (mode === 'paths') { + // All ancestors down from HOME must be owned, real directories, not writable by others. + const home = path.resolve(process.env.HOME); + check(home === process.env.HOME && fs.realpathSync(home) === home); + for (const target of [home, root, expected]) { + check(target === home || target.startsWith(home + '/')); + let current = target; + while (current.startsWith(home)) { + const st = fs.lstatSync(current); + check(st.isDirectory() && st.uid === process.getuid() && !(st.mode & 0o022)); + if (current === home) break; + current = path.dirname(current); + } + } + } else { + const metadata = path.join(root, key, 'package.json'); + check(fs.realpathSync(metadata).startsWith(root + '/')); + const pkg = read(metadata); + check(stable.test(pkg.version)); + if (mode === 'version') { + console.log(pkg.version); + } else { + check(mode === 'stage' && stable.test(expected) && pkg.name === name && pkg.version === expected); + const semver = createRequire(fs.realpathSync(npm))('semver'); + const manifest = read(path.join(root, 'package.json')); + check(manifest.dependencies[name] === expected); + const main = path.resolve(root, key, pkg.main); + check(main.startsWith(path.join(root, key) + '/') && fs.statSync(main).isFile()); + const lock = read(path.join(root, 'package-lock.json')); + const hidden = read(path.join(root, 'node_modules/.package-lock.json')); + const entry = lock.packages[key]; + check(lock.lockfileVersion >= 2 && entry.version === expected); + check(lock.packages[''].dependencies[name] === expected); + check(typeof entry.integrity === 'string' && /^sha512-[A-Za-z0-9+/]{86}==$/.test(entry.integrity)); + check(Buffer.from(entry.integrity.slice(7), 'base64').length === 64); + check(Buffer.from(entry.integrity.slice(7), 'base64').toString('base64') === entry.integrity.slice(7)); + check(hidden.packages[key].version === expected && hidden.packages[key].integrity === entry.integrity); + if (pkg._integrity) check(pkg._integrity === entry.integrity); + check(typeof pkg.engines?.node === 'string' && semver.satisfies(process.version, pkg.engines.node)); + for (const dependency of Object.values(lock.packages)) { + if (dependency.engines?.node) check(semver.satisfies(process.version, dependency.engines.node)); + } + const walk = dir => { + for (const item of fs.readdirSync(dir)) { + const file = path.join(dir, item); + const st = fs.lstatSync(file); + check(st.uid === process.getuid()); + if (st.isSymbolicLink()) { + const dest = fs.realpathSync(file); + check(dest.startsWith(root + '/')); + } else { + check(!(st.mode & 0o022)); + check(st.isDirectory() || (st.isFile() && st.nlink === 1)); + if (st.isDirectory()) walk(file); + } + } + }; + walk(root); + check(fs.statSync(root).dev === fs.statSync(path.dirname(path.dirname(root))).dev); + } + } +} catch { + console.error('ERROR: metadata, paths, integrity, URL or Node compatibility validation failed'); + process.exitCode = 1; +} diff --git a/scripts/update/lib/dc_local.sh b/scripts/update/lib/dc_local.sh index 24428d0..cb58057 100644 --- a/scripts/update/lib/dc_local.sh +++ b/scripts/update/lib/dc_local.sh @@ -57,7 +57,7 @@ update_dc_local() { [[ -d "$tmp" ]] && rm -rf "$tmp" fi if [[ -f "$candidate" ]] && [[ "$(node -p "require(process.argv[1]).version" "$candidate" 2>/dev/null)" == "$latest" ]]; then - result_warn "WSL" "Desktop Commander" "STAGED $latest; ACTIVE $installed; ACTIVATION_PENDING (restart is manual, not performed)" + result_warn "WSL" "Desktop Commander" "STAGED $latest; ACTIVE $installed; ACTIVATION_PENDING; human separate WSL terminal: dotfiles-dc-activate $latest --apply (not performed)" fi else result_info "WSL" "Desktop Commander" "Installed $installed; latest stable $latest; unchanged" diff --git a/tests/Makefile.tests b/tests/Makefile.tests index 17c917a..a4b8ffe 100644 --- a/tests/Makefile.tests +++ b/tests/Makefile.tests @@ -17,7 +17,7 @@ SHELLCHECK_EXCLUDED_SCRIPTS := $(ZSH_SCRIPTS) # understand Go template delimiters reliably unless templates are rendered. SHELL_SCRIPTS_ALL := $(shell find $(DOTFILES_DIR) -name '*.sh' -type f | grep -v '/\.git/' | grep -v '/\.venv/' | grep -v '/node_modules/' | grep -v '/vendor/' | grep -v '/__pycache__/') SHELL_SCRIPTS := $(filter-out $(SHELLCHECK_EXCLUDED_SCRIPTS),$(SHELL_SCRIPTS_ALL)) -SHELL_LAUNCHERS := $(shell find $(DOTFILES_DIR)/bin -type f \( -name 'mcp-*-launcher' -o -name 'tmux-dotfiles' -o -name 'playwright-docker' \) 2>/dev/null || true) +SHELL_LAUNCHERS := $(shell find $(DOTFILES_DIR)/bin -type f \( -name 'mcp-*-launcher' -o -name 'tmux-dotfiles' -o -name 'playwright-docker' -o -name 'dotfiles-dc-activate' \) 2>/dev/null || true) GIT_HOOKS := $(shell find $(DOTFILES_DIR)/.githooks -type f 2>/dev/null || true) PROMPT_LAUNCHERS := $(shell find $(DOTFILES_DIR)/local/bin -name 'prompt-*' -type f 2>/dev/null || true) AI_PROMPT_CLI := $(wildcard $(DOTFILES_DIR)/local/bin/ai-prompt) @@ -531,7 +531,7 @@ test-ci: test-lint test-bats-ci test-chezmoi @echo "" @echo "$(GREEN)==>$(NC) CI tests completed" -test-bats-ci: bats-helpers bats-filesystem bats-chezmoi-mcp-launchers bats-mcp-launcher-contract bats-git bats-governance bats-chezmoi bats-skills bats-git-flow bats-gitnexus bats-git-hooks bats-docs +test-bats-ci: bats-dc-activate bats-helpers bats-filesystem bats-chezmoi-mcp-launchers bats-mcp-launcher-contract bats-git bats-governance bats-chezmoi bats-skills bats-git-flow bats-gitnexus bats-git-hooks bats-docs # ============================================ # Combined tests @@ -657,3 +657,7 @@ materialize-commands: test-commands: bats-commands validate-commands @echo "$(GREEN)==>$(NC) Commands tests passed" + +.PHONY: bats-dc-activate +bats-dc-activate: + @bats $(BATS_DIR)/system/dc-activate.bats $(BATS_DIR)/system/dc-local-update.bats diff --git a/tests/bats/system/dc-activate.bats b/tests/bats/system/dc-activate.bats new file mode 100644 index 0000000..ba524f4 --- /dev/null +++ b/tests/bats/system/dc-activate.bats @@ -0,0 +1,292 @@ +#!/usr/bin/env bats + +setup() { + bats_require_minimum_version 1.5.0 + umask 077 + REPO="$(cd "$BATS_TEST_DIRNAME/../../.." && pwd)" + export HOME="$BATS_TEST_TMPDIR/home" + export DC_TEST="$BATS_TEST_TMPDIR/state" + mkdir -p "$HOME/.local/share" "$DC_TEST" "$BATS_TEST_TMPDIR/bin" + export PATH="$BATS_TEST_TMPDIR/bin:$PATH" + CLI="$REPO/bin/dotfiles-dc-activate" + ACTIVE="$HOME/.local/share/ixatu-mcp" + STAGE="$HOME/.local/share/ixatu-mcp-staged/0.3.4" + fixture "$ACTIVE" 0.3.3 + fixture "$STAGE" 0.3.4 + printf active >"$DC_TEST/service" + cat >"$BATS_TEST_TMPDIR/bin/systemctl" <<'MOCK' +#!/usr/bin/env bash +printf '%s\n' "$*" >> "$DC_TEST/systemctl" +case "$*" in + *LoadState*) echo "${LOAD_STATE:-loaded}" ;; + *MainPID*) echo 100 ;; + *is-active*) [[ "$(cat "$DC_TEST/service")" == active ]] ;; + *stop*) echo inactive > "$DC_TEST/service" ;; + *start*) + if [[ -f "$DC_TEST/fail-start" ]]; then rm "$DC_TEST/fail-start"; exit 1; fi + echo active > "$DC_TEST/service" ;; + *) exit 1 ;; +esac +MOCK + cat >"$BATS_TEST_TMPDIR/bin/pgrep" <<'MOCK' +#!/usr/bin/env bash +[[ ! -f "$DC_TEST/no-child" ]] || exit 1 +if [[ -f "$DC_TEST/retry-child" ]]; then rm "$DC_TEST/retry-child"; exit 1; fi +[[ "${*: -1}" == 100 ]] || exit 1 +printf '101 node %s/.local/share/ixatu-mcp/node_modules/@wonderwhy-er/desktop-commander/dist/index.js\n' "$HOME" +MOCK + cat >"$BATS_TEST_TMPDIR/bin/curl" <<'MOCK' +#!/usr/bin/env bash +printf '%s\n' "$*" >> "$DC_TEST/curl" +if [[ -f "$DC_TEST/fail-curl" ]]; then exit 1; fi +if [[ -f "$DC_TEST/retry" ]]; then rm "$DC_TEST/retry"; exit 1; fi +printf 200 +MOCK + chmod +x "$BATS_TEST_TMPDIR/bin/"* +} + +fixture() { + local root="$1" version="$2" + mkdir -p "$root/node_modules/@wonderwhy-er/desktop-commander" + node - "$root" "$version" <<'JS' +const fs = require('fs'); +const [root, version] = process.argv.slice(2); +const name = '@wonderwhy-er/desktop-commander'; +const entry = {version, integrity: 'sha512-' + Buffer.alloc(64, 1).toString('base64')}; +const packages = {'': {dependencies: {[name]: version}}, ['node_modules/' + name]: entry}; +fs.writeFileSync(root + '/node_modules/' + name + '/package.json', JSON.stringify({name, version, main: 'dist/index.js', engines: {node: '>=16'}})); +fs.mkdirSync(root + '/node_modules/' + name + '/dist', {recursive: true}); +fs.writeFileSync(root + '/node_modules/' + name + '/dist/index.js', '// fixture'); +fs.writeFileSync(root + '/package.json', JSON.stringify({dependencies: {[name]: version}})); +for (const file of ['/package-lock.json', '/node_modules/.package-lock.json']) { + fs.writeFileSync(root + file, JSON.stringify({lockfileVersion: 3, packages})); +} +JS +} + +apply_candidate() { + run "$CLI" --apply 0.3.4 --health-url http://127.0.0.1:9999/health +} + +assert_old() { + [ "$(cat "$DC_TEST/service")" = active ] + [[ "$(cat "$ACTIVE/node_modules/@wonderwhy-er/desktop-commander/package.json")" == *'"version":"0.3.3"'* ]] + [ -f "$STAGE/package-lock.json" ] +} + +@test "activation help and status never mutate or contact service" { + run "$CLI" --help + [ "$status" -eq 0 ] + [[ "$output" == *'HUMAN ONLY'* ]] + run "$CLI" --status + [ "$status" -eq 0 ] + [[ "$output" == *'ACTIVE 0.3.3'*'STAGED 0.3.4'* ]] + [ ! -e "$DC_TEST/systemctl" ] + assert_old +} + +@test "activation defaults to validated dry-run and already active is no-op" { + run "$CLI" 0.3.4 + [ "$status" -eq 0 ] + [[ "$output" == *'DRY-RUN'* ]] + run ! grep -Eq 'stop|start' "$DC_TEST/systemctl" + run "$CLI" --apply 0.3.3 + [ "$status" -eq 0 ] + [[ "$output" == *'already active'* ]] + assert_old +} + +@test "activation succeeds and preserves pre-existing backups" { + mkdir -p "$HOME/.local/share/ixatu-mcp-rollback-0.3.2-old" + echo keep >"$HOME/.local/share/ixatu-mcp-rollback-0.3.2-old/marker" + apply_candidate + [ "$status" -eq 0 ] + [[ "$output" == *'ACTIVE 0.3.4'* ]] + [ ! -d "$STAGE" ] + [ "$(cat "$HOME/.local/share/ixatu-mcp-rollback-0.3.2-old/marker")" = keep ] + [ "$(find "$HOME/.local/share" -maxdepth 1 -name 'ixatu-mcp-rollback-0.3.3-*' | wc -l)" -eq 1 ] + [ "$(grep -c 'stop' "$DC_TEST/systemctl")" -eq 1 ] + [ "$(grep -c 'start' "$DC_TEST/systemctl")" -eq 1 ] +} + +@test "activation uses IXATU readiness default without extra flags" { + run "$CLI" --apply 0.3.4 + [ "$status" -eq 0 ] + [[ "$output" == *'ACTIVE 0.3.4'* ]] + grep -Fq 'http://127.0.0.1:49187/readyz' "$DC_TEST/curl" +} + +@test "activation retries initial HTTP failure" { + touch "$DC_TEST/retry" + apply_candidate + [ "$status" -eq 0 ] + [ "$(wc -l <"$DC_TEST/curl")" -eq 2 ] +} + +@test "activation rolls back start failure and candidate can be retried" { + touch "$DC_TEST/fail-start" + apply_candidate + [ "$status" -ne 0 ] + [[ "$output" == *'ROLLBACK: previous runtime restored'* ]] + assert_old + apply_candidate + [ "$status" -eq 0 ] +} + +@test "activation waits at most 30 seconds then rolls back failed health" { + # Fail health only for the new runtime; rollback health succeeds. + cat >"$BATS_TEST_TMPDIR/bin/curl" <<'MOCK' +#!/usr/bin/env bash +[[ "$(cat "$HOME/.local/share/ixatu-mcp/node_modules/@wonderwhy-er/desktop-commander/package.json")" == *'"version":"0.3.3"'* ]] || exit 1 +printf 200 +MOCK + local started=$SECONDS + apply_candidate + [ "$status" -ne 0 ] + [ "$((SECONDS - started))" -ge 29 ] + [ "$((SECONDS - started))" -lt 36 ] + [[ "$output" == *'ROLLBACK: previous runtime restored'* ]] + assert_old +} + +@test "activation trap restores runtime on TERM during readiness" { + cat >"$BATS_TEST_TMPDIR/bin/curl" <<'MOCK' +#!/usr/bin/env bash +if [[ ! -f "$DC_TEST/signalled" ]]; then + touch "$DC_TEST/signalled" + kill -TERM "$PPID" + exit 1 +fi +printf 200 +MOCK + apply_candidate + [ "$status" -ne 0 ] + assert_old +} + +@test "activation refuses absent staging and downgrade and malformed version" { + rm -rf "$STAGE" + for version in 0.3.4 0.3.2 0.3.4-rc1 00.3.4 '../0.3.4'; do + run "$CLI" --apply "$version" + [ "$status" -ne 0 ] + done + [ ! -e "$DC_TEST/systemctl" ] +} + +@test "activation refuses incompatible Node or invalid lock metadata before stop" { + for mutation in version integrity engine hidden; do + fixture "$STAGE" 0.3.4 + node - "$STAGE" "$mutation" <<'JS' +const fs = require('fs'); +const [root, mutation] = process.argv.slice(2); +const file = mutation === 'hidden' ? '/node_modules/.package-lock.json' : '/package-lock.json'; +const lock = JSON.parse(fs.readFileSync(root + file)); +const entry = lock.packages['node_modules/@wonderwhy-er/desktop-commander']; +if (mutation === 'version') entry.version = '0.3.5'; +if (mutation === 'integrity') entry.integrity = 'sha512-bad'; +if (mutation === 'engine') entry.engines = {node: '>=999'}; +if (mutation === 'hidden') entry.integrity = 'sha512-' + Buffer.alloc(64, 2).toString('base64'); +fs.writeFileSync(root + file, JSON.stringify(lock)); +JS + apply_candidate + [ "$status" -ne 0 ] + done + [ ! -e "$DC_TEST/systemctl" ] + assert_old +} + +@test "activation rejects hostile symlinks and writable trees; accepts internal npm links" { + ln -s /tmp "$STAGE/escape" + apply_candidate + [ "$status" -ne 0 ] + rm "$STAGE/escape" + chmod o+w "$STAGE/node_modules" + apply_candidate + [ "$status" -ne 0 ] + chmod o-w "$STAGE/node_modules" + ln -s node_modules/@wonderwhy-er/desktop-commander/package.json "$STAGE/internal" + run "$CLI" 0.3.4 + [ "$status" -eq 0 ] + run ! grep -Eq 'stop|start' "$DC_TEST/systemctl" +} + +@test "activation requires loaded active service and safe explicit health URL" { + run env LOAD_STATE=not-found "$CLI" --apply 0.3.4 --health-url http://127.0.0.1/health + [ "$status" -ne 0 ] + echo inactive >"$DC_TEST/service" + apply_candidate + [ "$status" -ne 0 ] + echo active >"$DC_TEST/service" + for url in '' 'https://example.com/health' 'http://user:secret@127.0.0.1/health' 'http://127.0.0.1/health?token=secret'; do + run "$CLI" --apply 0.3.4 --health-url "$url" + [ "$status" -ne 0 ] + [[ "$output" != *'secret'* ]] + done + run ! grep -Eq 'stop|start' "$DC_TEST/systemctl" +} + +@test "activation refuses concurrent invocation without stopping service" { + exec {guard}<"$HOME/.local/share" + flock -x "$guard" + apply_candidate + [ "$status" -ne 0 ] + [[ "$output" == *'another activation is running'* ]] + run ! grep -Eq 'stop|start' "$DC_TEST/systemctl" + exec {guard}<&- + assert_old +} + +@test "activation retries missing MCP child before accepting HTTP readiness" { + touch "$DC_TEST/retry-child" + apply_candidate + [ "$status" -eq 0 ] + [ ! -e "$DC_TEST/retry-child" ] + [ "$(wc -l <"$DC_TEST/curl")" -eq 1 ] +} + +@test "activation restores service if candidate directory move fails" { + local real_mv + real_mv="$(command -v mv)" + export REAL_MV="$real_mv" + cat >"$BATS_TEST_TMPDIR/bin/mv" <<'MOCK' +#!/usr/bin/env bash +if [[ "$*" == *ixatu-mcp-staged/0.3.4* && ! -f "$DC_TEST/move-failed" ]]; then + touch "$DC_TEST/move-failed" + exit 1 +fi +exec "$REAL_MV" "$@" +MOCK + chmod +x "$BATS_TEST_TMPDIR/bin/mv" + apply_candidate + [ "$status" -ne 0 ] + [[ "$output" == *'ROLLBACK: previous runtime restored'* ]] + assert_old +} + +@test "activation rejects symlinked runtime roots before service operations" { + mv "$STAGE" "$STAGE-real" + ln -s "$STAGE-real" "$STAGE" + apply_candidate + [ "$status" -ne 0 ] + [ ! -e "$DC_TEST/systemctl" ] + mv "$ACTIVE" "$ACTIVE-real" + ln -s "$ACTIVE-real" "$ACTIVE" + run "$CLI" --status + [ "$status" -ne 0 ] +} + +@test "activation success survives failed final log output" { + run bash -c '"$1" --apply 0.3.4 --health-url http://127.0.0.1:9999/health > /dev/full' _ "$CLI" + [ "$status" -eq 0 ] + [ ! -d "$STAGE" ] + [ "$(grep -c 'stop' "$DC_TEST/systemctl")" -eq 1 ] +} + +@test "activation works through the published symlink pattern" { + mkdir -p "$HOME/.local/bin" + ln -s "$CLI" "$HOME/.local/bin/dotfiles-dc-activate" + run "$HOME/.local/bin/dotfiles-dc-activate" 0.3.4 + [ "$status" -eq 0 ] + [[ "$output" == *DRY-RUN* ]] + assert_old +}