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
1 change: 1 addition & 0 deletions .chezmoiignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,6 @@
!.local/share/chezmoi/bin
!.local/share/chezmoi/bin/**
!.zshrc
!.zshenv
!.p10k.zsh
!.aliases
6 changes: 4 additions & 2 deletions .chezmoiscripts/run_before_00_backup_rc_files.sh.tmpl
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/usr/bin/env bash
# Backup seguro de symlinks gestionados antes de que Chezmoi cree los destinos:
# ~/.zshrc -> $HOME/dotfiles/zshrc
# ~/.zshenv -> $HOME/dotfiles/zshenv
# ~/.p10k.zsh -> $HOME/dotfiles/powerlevel10k/p10k.zsh
# ~/.aliases -> $HOME/dotfiles/aliases
# ~/.tmux.conf -> $HOME/dotfiles/tmux.conf
Expand All @@ -13,7 +14,7 @@
# - Si es fichero regular con contenido custom no reconocido: abortar con
# mensaje accionable, salvo que el usuario haya pasado ZSH_RC_APPLY=1
# (flag histórico; cubre también ~/.tmux.conf además de los RC de zsh).
# - Nunca borra sin backup. Sin sudo. Solo toca los cuatro ficheros del scope.
# - Nunca borra sin backup. Sin sudo. Solo toca los cinco ficheros del scope.
#
# RCM/rcup queda fuera del flujo activo: este hook no lo invoca ni asume.
set -euo pipefail
Expand Down Expand Up @@ -94,7 +95,7 @@ handle_target() {
cat >&2 <<EOF
[run_before_00_backup_rc_files] ABORT: ${target} already exists with custom content.
- Expected target: ${expected}
- Applies to: ~/.zshrc, ~/.p10k.zsh, ~/.aliases, ~/.tmux.conf
- Applies to: ~/.zshenv, ~/.zshrc, ~/.p10k.zsh, ~/.aliases, ~/.tmux.conf
- To allow backup + replacement, re-run with:
ZSH_RC_APPLY=1 make install-dotfiles DOTFILES_APPLY=1
- To keep your file as-is, move/rename it manually before running apply.
Expand All @@ -106,6 +107,7 @@ EOF
HOME_DIR="${HOME}"
DOTFILES_DIR="${HOME_DIR}/dotfiles"

handle_target "${HOME_DIR}/.zshenv" "${DOTFILES_DIR}/zshenv"
handle_target "${HOME_DIR}/.zshrc" "${DOTFILES_DIR}/zshrc"
handle_target "${HOME_DIR}/.p10k.zsh" "${DOTFILES_DIR}/powerlevel10k/p10k.zsh"
handle_target "${HOME_DIR}/.aliases" "${DOTFILES_DIR}/aliases"
Expand Down
52 changes: 51 additions & 1 deletion docs/CHEZMOI.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ Override: `DOTFILES_DIR=/ruta/al/repo dotfiles-apply`. No sustituye `chezmoi` av
| `~/.config/ai/runtime/` | Runtime (venv) — ver `ai/README.md` |
| `~/.local/share/chezmoi/bin/mcp-*-launcher` | `dot_local/share/chezmoi/bin/executable_mcp-*-launcher.tmpl` (`filesystem`, `git`, `gitnexus`, `postgres`) |
| `~/.zshrc` | `symlink_dot_zshrc.tmpl` → `$HOME/dotfiles/zshrc` |
| `~/.zshenv` | `symlink_dot_zshenv.tmpl` → `$HOME/dotfiles/zshenv` (PATH mínimo para todos los procesos zsh) |
| `~/.p10k.zsh` | `symlink_dot_p10k.zsh.tmpl` → `$HOME/dotfiles/powerlevel10k/p10k.zsh` |
| `~/.aliases` | `symlink_dot_aliases.tmpl` → `$HOME/dotfiles/aliases` |
| `~/.tmux.conf` | `symlink_dot_tmux.conf.tmpl` → `$HOME/dotfiles/tmux.conf` |
Expand All @@ -60,14 +61,63 @@ Override: `DOTFILES_DIR=/ruta/al/repo dotfiles-apply`. No sustituye `chezmoi` av

### Backup seguro de symlinks gestionados (RC + tmux)

El hook `.chezmoiscripts/run_before_00_backup_rc_files.sh.tmpl` se ejecuta antes de `chezmoi apply` y aplica esta política sobre `~/.zshrc`, `~/.p10k.zsh`, `~/.aliases` y `~/.tmux.conf`:
El hook `.chezmoiscripts/run_before_00_backup_rc_files.sh.tmpl` se ejecuta antes de `chezmoi apply` y aplica esta política sobre `~/.zshenv`, `~/.zshrc`, `~/.p10k.zsh`, `~/.aliases` y `~/.tmux.conf`:

- Si el target no existe o ya es un symlink correcto: no-op (idempotente).
- Si es un symlink al destino equivocado o un fichero **trivial** (vacío, solo whitespace, o exactamente `. "$HOME/.local/bin/env"` — el stub que escribe el instalador oficial de `uv`): se mueve a `~/<name>.backup.YYYYMMDD-HHMMSS` y Chezmoi crea el symlink limpio.
- Si es un fichero regular con **contenido custom**: el hook aborta con mensaje accionable, salvo que se pase `ZSH_RC_APPLY=1`. Con el flag, se hace backup con timestamp y se reemplaza. El nombre del flag es histórico (zsh stack); **también autoriza el reemplazo de un `~/.tmux.conf` custom**.

Nunca se borra sin backup; nunca se usa `sudo`.

### PATH de agentes y Desktop Commander sin TTY (#30)

`~/.zshenv` configura únicamente PATH, sin salida, credenciales ni comandos
externos. Ante un PATH heredado mínimo añade, por orden, `$HOME/.local/bin`,
`$HOME/.npm-global/bin`, `/usr/local/bin`, `/usr/bin` y `/bin`; conserva después
las entradas heredadas y elimina duplicados. No instala CLI ni selecciona
versiones de Node. `uv`, `claude` y `chezmoi` se esperan en `.local/bin`,
`codex` en `.npm-global/bin`; `gh` y `node` pueden resolver en `/usr/bin`.

| Invocación sin TTY | Inicialización del repo |
|--------------------|------------------------|
| `zsh -c` | `.zshenv`: PATH mínimo |
| `zsh -lc` | Igual; no se añade `.zprofile` al repo |
| `zsh -lic` | Igual; `.zshrc` retorna antes de Instant Prompt, OMZ, ZLE, NVM y overrides locales |

En una terminal interactiva con stdin/stdout TTY se mantiene el orden de
Instant Prompt, módulos, NVM y Powerlevel10k classic con rutas completas.
Los archivos globales de `/etc/zsh/` y un `.zprofile`/`.zlogin` local pueden
añadir comportamiento ajeno al repo. `zsh -f` omite el `.zshenv` del usuario;
un `ZDOTDIR` personalizado requiere gestionar allí el startup correspondiente.

En DC `start_process`, elegir explícitamente `shell: "/usr/bin/zsh"` para
comandos de agentes; no es necesario forzar `-i` para obtener PATH. Por ejemplo:

```json
{"shell":"/usr/bin/zsh","command":"for cli in uv gh codex claude node; do command -v \"$cli\"; done","timeout_ms":10000}
```

Para exigir sintaxis Bash, usar `shell: "/bin/bash"` y declarar su PATH
explícitamente en el comando: Bash no lee `.zshenv`. La corrección se aplica
a hijos zsh de DC; no cambia el entorno del proceso MCP padre ni de
`systemd --user`, ni requiere reiniciar servicios. Los launchers ejecutados
directamente deben mantener su propio contrato de entorno.

Diagnóstico seguro: ejecutar cada modo con `env -i HOME="$HOME"
PATH=/usr/bin:/bin /usr/bin/zsh -c 'command -v uv; command -v codex'`,
sustituyendo `-c` por `-lc` y `-lic`, con stdin redirigido desde `/dev/null`
y stdout/stderr a archivos temporales. No volcar `env` ni archivos de secretos.
Las pruebas `tests/bats/zsh/agent_startup.bats` usan HOME aislado, CLI fixture,
captura sin TTY y pseudo-TTY para verificar ambas ramas sin aplicar al HOME real.

Tras merge y **GO humano**, revisar `chezmoi --source="$HOME/dotfiles" diff
"$HOME/.zshenv" "$HOME/.zshrc"` y después usar
`DOTFILES_DIR="$HOME/dotfiles" dotfiles-apply --apply "$HOME/.zshenv" "$HOME/.zshrc"`.
Revisar primero cualquier startup custom; no activar `ZSH_RC_APPLY=1` a ciegas.
El hook de backup evalúa los cinco RC incluso en apply acotado: comprobar
también `.p10k.zsh`, `.aliases` y `.tmux.conf` antes del GO. Abrir nuevos hijos
de DC y una terminal normal para validar; hasta ese apply el HOME sigue sin corregir.

---

## Dato Chezmoi: ruta del vault Obsidian (`ai.obsidian_vault_path`)
Expand Down
1 change: 1 addition & 0 deletions symlink_dot_zshenv.tmpl
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{{ .chezmoi.homeDir }}/dotfiles/zshenv
1 change: 1 addition & 0 deletions tests/Makefile.tests
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,7 @@ bats-docs:
@$(call run_bats,$(BATS_DIR)/docs/github-token-policy.bats)

bats-zsh:
@$(call run_bats,$(BATS_DIR)/zsh/agent_startup.bats)
@echo "$(BLUE)==>$(NC) Running zsh stack RC symlink tests..."
@$(call run_bats,$(BATS_DIR)/zsh/rc_symlinks.bats)
@echo "$(BLUE)==>$(NC) Running Oh My Zsh plugin list tests..."
Expand Down
126 changes: 126 additions & 0 deletions tests/bats/zsh/agent_startup.bats
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
#!/usr/bin/env bats

setup() {
load '../helpers/common'
skip_if_command_missing zsh
REPO_DIR="$(cd "${BATS_TEST_DIRNAME}/../../.." && pwd)"
TEST_HOME="${BATS_TEST_TMPDIR}/home"
mkdir -p "$TEST_HOME/dotfiles" "$TEST_HOME/.local/bin" "$TEST_HOME/.npm-global/bin" "$TEST_HOME/.cache"
cp -r "$REPO_DIR/zsh" "$TEST_HOME/dotfiles/"
cp "$REPO_DIR/zshrc" "$TEST_HOME/.zshrc"
[[ ! -f "$REPO_DIR/zshenv" ]] || cp "$REPO_DIR/zshenv" "$TEST_HOME/.zshenv"
for cli in uv claude chezmoi; do
printf '#!/bin/sh\nexit 0\n' >"$TEST_HOME/.local/bin/$cli"
chmod +x "$TEST_HOME/.local/bin/$cli"
done
printf '#!/bin/sh\nexit 0\n' >"$TEST_HOME/.npm-global/bin/codex"
chmod +x "$TEST_HOME/.npm-global/bin/codex"
# Fail loudly if any interactive-only startup runs without a terminal.
mkdir -p "$TEST_HOME/.oh-my-zsh" "$TEST_HOME/.nvm"
printf 'print OMZ_LOADED\n' >"$TEST_HOME/.oh-my-zsh/oh-my-zsh.sh"
printf 'print NVM_LOADED\n' >"$TEST_HOME/.nvm/nvm.sh"
printf 'print LOCAL_LOADED\n' >"$TEST_HOME/.zshrc.local"
printf 'print P10K_LOADED\n' >"$TEST_HOME/.p10k.zsh"
printf 'print INSTANT_LOADED\n' >"$TEST_HOME/.cache/p10k-instant-prompt-$(id -un).zsh"
}

@test "agent shells resolve user CLIs with minimal inherited PATH and no startup output" {
for mode in -c -lc -lic; do
run env -i HOME="$TEST_HOME" PATH=/usr/bin:/bin TERM=dumb /usr/bin/zsh "$mode" '
[[ ! -t 0 && ! -t 1 && ! -t 2 ]] || exit 10
for cli in uv claude chezmoi; do
[[ $(command -v "$cli") == "$HOME/.local/bin/$cli" ]] || exit 11
done
[[ $(command -v codex) == "$HOME/.npm-global/bin/codex" ]] || exit 12
for cli in gh node; do
[[ ! -x /usr/bin/$cli ]] || [[ $(command -v "$cli") == /usr/bin/$cli ]] || exit 13
done
print PASS
' </dev/null
[[ "$status" -eq 0 && "$output" == PASS ]]
done
}

@test "minimal PATH is idempotent, deduplicated and inherited by child processes" {
run env -i HOME="$TEST_HOME" PATH=/usr/bin:/bin:/usr/bin:/opt/agent:/opt/agent /usr/bin/zsh -c '
before=$PATH
source "$HOME/.zshenv"
[[ $PATH == $before && ${#path} == ${#${(u)path}} ]] || exit 1
[[ $path[1] == "$HOME/.local/bin" && $path[2] == "$HOME/.npm-global/bin" ]] || exit 2
[[ ${path[(Ie)/opt/agent]} -gt 0 ]] || exit 3
[[ $(/bin/sh -c "command -v uv") == "$HOME/.local/bin/uv" ]] || exit 4
print PASS
'
[[ "$status" -eq 0 && "$output" == PASS ]]
}

@test "interactive terminal still loads instant prompt, NVM, OMZ, p10k and local config" {
skip_if_command_missing python3
run python3 - "$TEST_HOME" <<'PY'
import errno
import os
import pty
import select
import sys
import time

pid, fd = pty.fork()
if pid == 0:
os.execve('/usr/bin/zsh', ['zsh', '-lic', 'print TERMINAL_OK'],
{'HOME': sys.argv[1], 'PATH': '/usr/bin:/bin', 'TERM': 'xterm-256color'})
output = b''
deadline = time.monotonic() + 15
try:
while True:
if time.monotonic() > deadline:
os.kill(pid, 9)
raise AssertionError('terminal startup timed out')
if not select.select([fd], [], [], 0.1)[0]:
continue
try:
chunk = os.read(fd, 65536)
except OSError as error:
if error.errno != errno.EIO:
raise
break
if not chunk:
break
output += chunk
finally:
os.close(fd)
_, status = os.waitpid(pid, 0)
text = output.decode(errors='replace')
assert status == 0, text
for marker in ('INSTANT_LOADED', 'NVM_LOADED', 'OMZ_LOADED', 'P10K_LOADED', 'LOCAL_LOADED', 'TERMINAL_OK'):
assert marker in text, text
assert text.index('INSTANT_LOADED') < text.index('OMZ_LOADED'), text
PY
[[ "$status" -eq 0 ]]
}

@test "Chezmoi manages zshenv, refuses custom content and preserves authorized backups" {
skip_if_command_missing chezmoi
TEST_HOME="$BATS_TEST_TMPDIR/chezmoi-home"
mkdir -p "$TEST_HOME/dotfiles"
local source_dir="$BATS_TEST_TMPDIR/source"
mkdir -p "$source_dir/.chezmoiscripts"
cp "$REPO_DIR/symlink_dot_zshenv.tmpl" "$REPO_DIR/.chezmoiignore" "$source_dir/"
cp "$REPO_DIR/.chezmoiscripts/run_before_00_backup_rc_files.sh.tmpl" "$source_dir/.chezmoiscripts/"
cp "$REPO_DIR/zshenv" "$TEST_HOME/dotfiles/zshenv"
rm -f "$TEST_HOME/.zshenv"
run env HOME="$TEST_HOME" chezmoi --source="$source_dir" --destination="$TEST_HOME" apply
[[ "$status" -eq 0 ]]
[[ $(readlink "$TEST_HOME/.zshenv") == "$TEST_HOME/dotfiles/zshenv" ]]
run env HOME="$TEST_HOME" chezmoi --source="$source_dir" --destination="$TEST_HOME" apply
[[ "$status" -eq 0 ]]
[[ -z $(find "$TEST_HOME" -name '.zshenv.backup.*' -print) ]]
rm "$TEST_HOME/.zshenv"
printf '# custom startup\n' >"$TEST_HOME/.zshenv"
run env -u ZSH_RC_APPLY HOME="$TEST_HOME" chezmoi --source="$source_dir" --destination="$TEST_HOME" apply
[[ "$status" -ne 0 && "$output" == *ABORT* ]]
[[ $(cat "$TEST_HOME/.zshenv") == '# custom startup' ]]
run env HOME="$TEST_HOME" ZSH_RC_APPLY=1 chezmoi --source="$source_dir" --destination="$TEST_HOME" apply --force
[[ "$status" -eq 0 ]]
[[ $(readlink "$TEST_HOME/.zshenv") == "$TEST_HOME/dotfiles/zshenv" ]]
[[ $(cat "$TEST_HOME"/.zshenv.backup.*) == '# custom startup' ]]
}
4 changes: 2 additions & 2 deletions tests/bats/zsh/local_startup.bats
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ setup() {
grep -q 'gh auth switch' "${LOCAL_ZSH}"
}

@test "interactive zsh startup does not export GH_TOKEN from dotfiles modules" {
@test "90-local startup module does not export GH_TOKEN" {
skip_if_command_missing "zsh"

local fake_home
Expand All @@ -45,7 +45,7 @@ setup() {

run env -u GH_TOKEN -u GITHUB_TOKEN -u GITHUB_PERSONAL_ACCESS_TOKEN \
HOME="${fake_home}" zsh -fc '
source "$HOME/dotfiles/zshrc"
source "$HOME/dotfiles/zsh/90-local.zsh"
env | grep -E "^(GH_TOKEN|GITHUB_TOKEN)=" && exit 1 || exit 0
'
rm -rf "${fake_home}"
Expand Down
6 changes: 6 additions & 0 deletions zshenv
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Minimal environment for every zsh process, including agents without a TTY.
# Keep this file silent: no prompt, plugins, runtime managers or secrets.
# Preserve inherited entries after the canonical user and system commands.
typeset -U path PATH
path=("$HOME/.local/bin" "$HOME/.npm-global/bin" /usr/local/bin /usr/bin /bin "${path[@]}")
export PATH
6 changes: 5 additions & 1 deletion zshrc
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# Prompt, plugins and ZLE require a real interactive terminal. Agents use
# ~/.zshenv for PATH; even `zsh -lic` must stay silent when run through pipes.
[[ -o interactive && -t 0 && -t 1 ]] || return 0

# Enable Powerlevel10k instant prompt. Keep close to the top.
if [[ -r "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" ]]; then
source "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh"
Expand All @@ -21,4 +25,4 @@ for f in \
"$ZSH_DOTFILES_DIR/90-local.zsh"
do
[[ -f "$f" ]] && source "$f"
done
done
Loading