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
31 changes: 24 additions & 7 deletions bin/dotfiles-dc-activate
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
#!/usr/bin/env bash
# Human-only activation. Updaters and agents must never invoke --apply on a live HOME.
# Verified activation; updater mode additionally enforces conservative compatibility.
set -euo pipefail
umask 077
repo="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/.." && pwd)"
validator="$repo/scripts/dc/validate.cjs"
updater=0
mode=dry-run
version=
health_url='http://127.0.0.1:49187/readyz'
Expand All @@ -16,11 +17,17 @@ Usage: dotfiles-dc-activate [--status|--dry-run|--apply] [VERSION] [--health-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.
Manual --apply: use a separate WSL terminal; disconnects the tunnel.
--updater-apply: authorized daily updater; compatible versions only.
Failed candidates remain staged. Agents test only with fixtures.
HELP
exit 0
;;
--updater-apply)
updater=1
set -- --apply "${@:2}"
continue
;;
--apply | --dry-run | --status)
((for_arg_mode == 0)) || {
echo 'ERROR: conflicting modes' >&2
Expand Down Expand Up @@ -69,6 +76,16 @@ if [[ "$version" == "$old" ]]; then
exit 0
fi
[[ "$(printf '%s\n%s\n' "$version" "$old" | sort -V | tail -n 1)" == "$version" ]] || fail 'version must be newer than active'
if ((updater)); then
[[ "${DOTFILES_MCP_AUTO_ACTIVATE:-1}" != 0 && "${DOTFILES_UPDATE_MOCK:-0}" == 0 ]] || fail 'updater activation disabled'
IFS=. read -r old_major old_minor _ <<<"$old"
IFS=. read -r new_major new_minor _ <<<"$version"
[[ "$old_major" == "$new_major" && ("$old_major" != 0 || "$old_minor" == "$new_minor") ]] || fail 'incompatible updater version'
# A CLI inside this service would be killed by stop; leave it staged instead.
if grep -Fq '/ixatu-wsl-mcp.service' /proc/self/cgroup; then
fail 'caller belongs to DC service; run updater in a separate WSL terminal'
fi
fi
stage="$stages/$version"
node "$validator" paths "$stage" "$active"
node "$validator" stage "$stage" "$version" "$(command -v npm)"
Expand Down Expand Up @@ -129,15 +146,15 @@ cleanup() {
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 timeout 45 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
if timeout 45 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
Expand All @@ -154,10 +171,10 @@ 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'
timeout 45 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'
timeout 45 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
Expand Down
9 changes: 9 additions & 0 deletions docs/MCP_QUICKREF.md
Original file line number Diff line number Diff line change
Expand Up @@ -233,3 +233,12 @@ npx/python/wrapper DSN/credentials/env
4. Run `make ai-mcp-validate`.
5. Regenerate Chezmoi MCP templates when needed: `make ai-mcp-generate APPLY=1` (after governance passes).
6. Run `make ai-mcp-governance` or `bin/validate-mcp-governance` before commit when touching MCP intent or templates.

## Actualización de los MCP locales IXATU

`dotfiles-update` activa DC compatible (0.x: mismo minor; 1+: mismo major) y Azure
MCP del mismo major, con preflight y rollback. Ejecutar desde terminal WSL
independiente. `DOTFILES_MCP_AUTO_ACTIVATE=0` desactiva ambas activaciones;
versiones incompatibles quedan pendientes. Tunnel Client sigue siendo manual.
Detalles: [DC](UPDATE.md#ixatu-desktop-commander-local) y
[Azure](ops/azure-mcp-pilot.md#versiones-en-dotfiles-update).
43 changes: 26 additions & 17 deletions docs/UPDATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -355,25 +355,31 @@ under `~/.local/share/ixatu-mcp`) and **Tunnel Client** (the executable under
`~/.local/bin`) in the `Tool snapshot`. The updater checks npm and GitHub's
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 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.
into `~/.local/share/ixatu-mcp-staged/<version>`. By default it then invokes
verified activation: DC 0.x accepts only patches within the same minor; DC 1+
accepts minor/patch updates within the same major. Other versions remain
`PREPARED` / `ACTIVATION_PENDING`. `DOTFILES_MCP_AUTO_ACTIVATE=0` disables automatic
activation of both local MCPs (DC staging and version checks continue).
The snapshot reports the active version after successful activation. Tunnel
Client remains a separate manual, checksum-verified update; its shared binary
is never overwritten. Network/activation failures warn and leave the global
updater running. Activation logs live beside the existing per-run tool logs.

#### Verified activation

`dotfiles-dc-activate` is published through the existing Chezmoi symlink pattern;
the updater calls the activator from its own checkout. The explicit internal
`--updater-apply` mode enforces the conservative version policy and opt-out.
Ordinary `--apply` retains its existing manual, verified behavior.
Run the daily updater from an independent WSL terminal. When the caller belongs
to `ixatu-wsl-mcp.service`, automatic DC activation stays pending to avoid killing
the caller before its summary. No detached daemon or background job is added.
Agents exercise mutations only with mocked commands and a temporary HOME.

```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.
# Manual activation 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:
Expand Down Expand Up @@ -401,15 +407,15 @@ ownership. Activation uses same-filesystem directory renames, an exclusive
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
`--apply` and authorized `--updater-apply` stop 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.
prints service environment/health bodies. The default is the dedicated DC port 49187; Azure uses 49188 independently.

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.
Expand All @@ -426,3 +432,6 @@ 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.

Azure MCP uses an independent pinned-launcher transaction, including offline MCP
catalog/schema preflight and rollback: [Azure pilot updates](ops/azure-mcp-pilot.md#versiones-en-dotfiles-update).
57 changes: 44 additions & 13 deletions docs/ops/azure-mcp-pilot.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

Receta pequeña para PC-IXATU-09, independiente de Desktop Commander. Ejecutar
manualmente desde el checkout; no se instala ni registra en Cursor/Codex,
Chezmoi o el MANIFEST global. `dotfiles-update` solo reporta versiones del piloto
si está presente. No requiere abrir Cursor.
Chezmoi o el MANIFEST global. `dotfiles-update` mantiene el piloto local existente
cuando está presente y activo (también PC08). No requiere abrir Cursor.

## Preparación y preview

Expand Down Expand Up @@ -93,17 +93,48 @@ La sección `tools` lee el pin de
`~/.local/share/ixatu-azure-mcp-pilot/start.sh` y consulta el JSON de PyPI para
`msmcp-azure` (con timeouts de conexión/total de 5/15 segundos). Solo considera
versiones finales `x.y.z` con archivos no retirados; ignora beta/rc/dev.
El snapshot incluye `Azure MCP` con el pin antes/después idéntico, incluso si
PyPI falla o se ejecuta otra sección. `PINNED` representa configuración, no una
comprobación de la versión cargada en un proceso vivo ni de la caché uvx.

Si aparece una estable posterior, emite `ACTIVATION_PENDING`: revisar manualmente
la compatibilidad, cambiar el pin del launcher dedicado y activar/reiniciar el
piloto en una terminal humana separada. El updater no descarga/ejecuta uvx, no
escribe el launcher ni modifica servicios, autenticación o túneles. `--apply`
de la receta seguirá rechazando un launcher con un pin distinto del generado.
Sin piloto: `SKIP`; sin versión remota válida: `WARN` y pin conservado. En mock
no hay consulta de red. Tunnel Client conserva su reporte separado existente.
El snapshot incluye el pin antes/después; tras una activación verificada muestra
la nueva versión. Con versiones iguales no ejecuta uvx ni opera servicios.
`DOTFILES_MCP_AUTO_ACTIVATE=0` conserva solo el reporte (modo mantenimiento/CI).
Mock no consulta red ni ejecuta paquetes o servicios.

Una estable posterior del mismo major activa por defecto con supervisión humana
en la actualización diaria. Un major distinto queda `ACTIVATION_PENDING`.
El helper `scripts/update/azure-mcp-activate.py`:

1. Verifica propietario, modo, rutas reales sin symlinks, launcher conocido y
flags exactos: stdio, mode all, namespaces containerapps/group y read-only.
Acepta uvx en PATH o `$HOME/.local/bin/uvx` absoluto. Rechaza otros comandos,
scopes y flags. Adquiere `flock` exclusivo del directorio del piloto.
2. Exige servicio activo y valida el pin actual con initialize + tools/list
offline. Descarga el candidato fijado con `uvx --from msmcp-azure==X.Y.Z`
y `azmcp --help` (180 s máximo), sin cambiar el servicio.
3. Ejecuta el candidato desde caché (`--offline`), initialize + tools/list
(45 s máximo): exactamente `containerapps_list`, `group_list`,
`group_resource_list`, schemas de objeto válidos, sin readOnlyHint falso,
y schemas de entrada/salida idénticos al pin anterior. No hace tools/call.
Un fallo del contrato actual o candidato impide la activación.
4. Reporta `PREPARED`, reemplaza atómicamente solo el texto de la versión,
conservando propietario/grupo/modo y el resto del launcher, y reinicia
exclusivamente `ixatu-azure-mcp-pilot.service`.
5. Confirma servicio activo, pin del launcher y HTTP 2xx en
`127.0.0.1:49188/readyz` durante hasta 30 s. Cada operación systemd tiene
timeout de 45 s. Reporta `INSTALLED/ACTIVATED` o restaura atómicamente el
launcher previo, reinicia y comprueba su readiness: `ROLLBACK`.

Errores parciales son WARN; el updater continúa. Los logs de activación del run
contienen estados, sin salida del servidor, cuerpos HTTP ni entorno. Si falla
la recuperación, reporta `ROLLBACK FAILED` y requiere recuperación manual del
servicio dedicado. No lee ni modifica perfil, runtime.env o credenciales; no
cambia el tunnel-client compartido, DC ni 49187. Tampoco reinicia si el caller
pertenece al propio servicio Azure. No hay daemon adicional.

La caché uv del pin anterior debe existir para comprobar el contrato offline.
SIGKILL, pérdida de alimentación o disco no admiten rollback automático: revisar
el pin y servicio antes de reintentar. Las pruebas reales con versiones iguales
solo demuestran no-op; una actualización real compatible sigue pendiente de una
release futura. `--apply` de la receta inicial seguirá rechazando launchers
actualizados distintos del generado; no se usa para mantener instalaciones.

### Operación local

Expand Down
Loading
Loading