Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
165 changes: 165 additions & 0 deletions bin/dotfiles-dc-activate
Original file line number Diff line number Diff line change
@@ -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
62 changes: 61 additions & 1 deletion docs/UPDATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<version>` 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 <version> --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-<active-version>-<random>` 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.
1 change: 1 addition & 0 deletions dot_local/bin/symlink_dotfiles-dc-activate.tmpl
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{{ .chezmoi.homeDir }}/dotfiles/bin/dotfiles-dc-activate
80 changes: 80 additions & 0 deletions scripts/dc/validate.cjs
Original file line number Diff line number Diff line change
@@ -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;
}
2 changes: 1 addition & 1 deletion scripts/update/lib/dc_local.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
8 changes: 6 additions & 2 deletions tests/Makefile.tests
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Loading
Loading