repositories

NixDaemon

NixOS pentest workstation as one flake — IceBreaker's successor

clonegit clone https://git.daemon-sec.xyz/NixDaemon.git
2026-06-07-foundation-core-perf.mdMarkdown684 lines23.2 KiBrendered raw download
# Foundation: Repo Scaffold + core.zsh Performance Rebuild — Implementation Plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.

**Goal:** Build the `~/.dotfiles` foundation — a fast, OMZ-free zsh that boots in <2s via a thin `.zshrc` orchestrator + `core.zsh`, with a reversible `~/.zshenv` cutover and a dependency-free test harness — without disturbing the user's live shell until cutover.

**Architecture:** zsh reads `~/.zshenv` (written by `setup.sh`) → exports `ZDOTDIR=$HOME/.dotfiles` → loads `~/.dotfiles/.zshrc` → sources `config/*.zsh` in a fixed, guarded order. OMZ and its 24 plugins are replaced by a manual loader sourcing 6 cloned plugins + a single cached `compinit`. All work happens in `~/.dotfiles`; the live `~/.zshrc` is never modified, only superseded by `~/.zshenv` at cutover and revertible with `rm ~/.zshenv`.

**Tech Stack:** zsh 5.9, git 2.54, plain-zsh assertion harness (no bats), `ZDOTDIR`-isolated test runs.

---

## File structure (this plan)

- `~/.dotfiles/.zshrc` — orchestrator: interactive guard, locate `$DOTFILES`, source `config/*.zsh` guarded + in order.
- `~/.dotfiles/config/core.zsh` — env, PATH, history, completion (single cached compinit), plugin loader, tool integrations (atuin/zsh-abbr/fzf/deno/docker/mise/gpg).
- `~/.dotfiles/config/plugins/` — cloned plugin repos (gitignored).
- `~/.dotfiles/scripts/setup.sh` — backup + write `~/.zshenv` (cutover) + `--check`/`--revert` modes.
- `~/.dotfiles/scripts/tests/lib.zsh` — assertion helpers.
- `~/.dotfiles/scripts/tests/core.test.zsh` — core/boot tests.
- `~/.dotfiles/scripts/test.zsh` — runner for all `*.test.zsh`.
- `~/.dotfiles/.gitignore` — ignore plugins/, ~/.pentest data, backups.
- `~/.dotfiles/README.md` — install + revert instructions (stub, expanded in Plan 4).

Out of scope here (later plans): `theme.zsh`, `database.zsh`, `pentesting.zsh`, `aliases.zsh`, `functions.zsh`, `animations.zsh`, `.tmux.conf`, docs. The orchestrator sources them **only if present**, so this plan stands alone.

---

## Task 1: Test harness + .gitignore

**Files:**
- Create: `~/.dotfiles/scripts/tests/lib.zsh`
- Create: `~/.dotfiles/scripts/test.zsh`
- Create: `~/.dotfiles/.gitignore`

- [ ] **Step 1: Write the assertion library**

Create `~/.dotfiles/scripts/tests/lib.zsh`:

```zsh
#!/usr/bin/env zsh
# Minimal dependency-free test helpers. Source from *.test.zsh files.
typeset -gi T_RUN=0 T_FAIL=0
export DOTFILES="${DOTFILES:-$HOME/.dotfiles}"

# Run the new config in isolation and capture a snippet's stdout.
# Usage: out=$(zboot 'print -r -- $EDITOR')
zboot() { ZDOTDIR="$DOTFILES" HOME="$HOME" zsh -ic "$1" 2>/dev/null }

assert_eq() {   # desc expected actual
  (( T_RUN++ ))
  if [[ "$2" == "$3" ]]; then print -P "%F{green}ok%f   $1"
  else print -P "%F{red}FAIL%f $1\n       expected: [$2]\n       actual:   [$3]"; (( T_FAIL++ )); fi
}
assert_contains() {  # desc haystack needle
  (( T_RUN++ ))
  if [[ "$2" == *"$3"* ]]; then print -P "%F{green}ok%f   $1"
  else print -P "%F{red}FAIL%f $1 (missing: $3)"; (( T_FAIL++ )); fi
}
assert_ok() {  # desc cmd...
  (( T_RUN++ )); local d="$1"; shift
  if "$@" >/dev/null 2>&1; then print -P "%F{green}ok%f   $d"
  else print -P "%F{red}FAIL%f $d (exit $?)"; (( T_FAIL++ )); fi
}
t_summary() {
  print -P "\n%F{cyan}── $((T_RUN-T_FAIL))/$T_RUN passed ──%f"
  (( T_FAIL == 0 ))
}
```

- [ ] **Step 2: Write the runner**

Create `~/.dotfiles/scripts/test.zsh`:

```zsh
#!/usr/bin/env zsh
# Runs every scripts/tests/*.test.zsh, returns nonzero if any assertion failed.
set -uo pipefail
DOTFILES="${0:A:h:h}"; export DOTFILES
source "$DOTFILES/scripts/tests/lib.zsh"
for f in "$DOTFILES"/scripts/tests/*.test.zsh(N); do
  print -P "%F{yellow}▸ ${f:t}%f"
  source "$f"
done
t_summary
```

- [ ] **Step 3: Write .gitignore**

Create `~/.dotfiles/.gitignore`:

```gitignore
config/plugins/
*.zwc
.DS_Store
# engagement data lives in ~/.pentest, never in repo (defense-in-depth)
.pentest/
backups/
*.db
```

- [ ] **Step 4: Verify harness self-runs (no tests yet = pass)**

Run: `cd ~/.dotfiles && zsh scripts/test.zsh`
Expected: prints `── 0/0 passed ──` and exits 0.

- [ ] **Step 5: Commit**

```bash
cd ~/.dotfiles && git add scripts/tests/lib.zsh scripts/test.zsh .gitignore
git commit -m "test: add dependency-free zsh assertion harness + gitignore"
```

---

## Task 2: core.zsh — environment & PATH

**Files:**
- Create: `~/.dotfiles/config/core.zsh`
- Create: `~/.dotfiles/.zshrc`
- Create: `~/.dotfiles/scripts/tests/core.test.zsh`

- [ ] **Step 1: Write failing tests**

Create `~/.dotfiles/scripts/tests/core.test.zsh`:

```zsh
# Boots the new config via ZDOTDIR and asserts core env is set.
assert_eq   "EDITOR is hx (helix present)"        "hx" "$(zboot 'print -r -- ${EDITOR:t}')"
assert_contains "PATH has homebrew bin"           "$(zboot 'print -r -- $PATH')" "/opt/homebrew/bin"
assert_contains "PATH has ~/.local/bin"           "$(zboot 'print -r -- $PATH')" "$HOME/.local/bin"
assert_eq   "HOMEBREW_NO_AUTO_UPDATE set"         "1"  "$(zboot 'print -r -- $HOMEBREW_NO_AUTO_UPDATE')"
assert_eq   "CLICOLOR set"                        "1"  "$(zboot 'print -r -- $CLICOLOR')"
assert_eq   "no oh-my-zsh sourced"                ""   "$(zboot 'print -r -- $ZSH')"
```

- [ ] **Step 2: Run to verify failure**

Run: `cd ~/.dotfiles && zsh scripts/test.zsh`
Expected: FAIL — `.zshrc`/`core.zsh` don't exist so `zboot` returns empty for every value.

- [ ] **Step 3: Write core.zsh env block**

Create `~/.dotfiles/config/core.zsh` (env section first):

```zsh
#!/usr/bin/env zsh
# ── core.zsh : environment, PATH, perf, loader ───────────────────────────────

# Homebrew (Apple Silicon) — guarded so Linux skips it cleanly.
if [[ -x /opt/homebrew/bin/brew ]]; then
  export HOMEBREW_PREFIX=/opt/homebrew
  export HOMEBREW_CELLAR=/opt/homebrew/Cellar
  export HOMEBREW_REPOSITORY=/opt/homebrew
  path=(/opt/homebrew/bin /opt/homebrew/sbin $path)
  [[ -d /opt/homebrew/lib/ruby/gems ]] && \
    path=(/opt/homebrew/lib/ruby/gems/*/bin(N) $path)
fi
export HOMEBREW_NO_AUTO_UPDATE=1

# PATH additions (zsh `path` array auto-dedupes with `typeset -U`).
typeset -U path PATH
path=("$HOME/.local/bin" "$HOME/.cargo/bin" "$HOME/go/bin" $path)

# Colors
export CLICOLOR=1
export LSCOLORS=ExGxBxDxCxEgEdxbxgxcxd

# Editor preference: helix > vim > vi
if (( $+commands[hx] )); then export EDITOR=hx VISUAL=hx
elif (( $+commands[vim] )); then export EDITOR=vim VISUAL=vim
else export EDITOR=vi VISUAL=vi; fi

# GPG
export GPG_TTY=$TTY
```

- [ ] **Step 4: Write the .zshrc orchestrator (minimal — sources core.zsh)**

Create `~/.dotfiles/.zshrc`:

```zsh
#!/usr/bin/env zsh
# ── ~/.dotfiles/.zshrc : module orchestrator ─────────────────────────────────
# Loaded because ~/.zshenv exports ZDOTDIR=$HOME/.dotfiles.

DOTFILES="${ZDOTDIR:-$HOME/.dotfiles}"

# Load order matters: core first, then leaves, then prompt, then splash.
for _m in core aliases functions theme database pentesting animations; do
  [[ -r "$DOTFILES/config/$_m.zsh" ]] && source "$DOTFILES/config/$_m.zsh"
done
unset _m
```

- [ ] **Step 5: Run tests to verify pass**

Run: `cd ~/.dotfiles && zsh scripts/test.zsh`
Expected: all 6 core env assertions `ok`. (`$ZSH` empty confirms OMZ gone.)

- [ ] **Step 6: Commit**

```bash
cd ~/.dotfiles && git add config/core.zsh .zshrc scripts/tests/core.test.zsh
git commit -m "feat(core): env, PATH, editor — OMZ-free orchestrator skeleton"
```

---

## Task 3: core.zsh — history & shell options

**Files:**
- Modify: `~/.dotfiles/config/core.zsh` (append)
- Modify: `~/.dotfiles/scripts/tests/core.test.zsh` (append)

- [ ] **Step 1: Write failing tests (append)**

Append to `~/.dotfiles/scripts/tests/core.test.zsh`:

```zsh
assert_eq "HISTSIZE large"       "100000" "$(zboot 'print -r -- $HISTSIZE')"
assert_eq "SAVEHIST large"       "100000" "$(zboot 'print -r -- $SAVEHIST')"
assert_contains "histfile set"   "$(zboot 'print -r -- $HISTFILE')" ".zsh_history"
assert_ok "SHARE_HISTORY on"     zsh -ic '[[ -o sharehistory ]]'
assert_ok "HIST_IGNORE_DUPS on"  zsh -ic '[[ -o histignorealldups ]]'
```

- [ ] **Step 2: Run to verify failure**

Run: `cd ~/.dotfiles && zsh scripts/test.zsh`
Expected: the 5 new lines FAIL (options/vars unset).

- [ ] **Step 3: Append history block to core.zsh**

```zsh
# ── history ──────────────────────────────────────────────────────────────────
HISTFILE="$HOME/.zsh_history"
HISTSIZE=100000
SAVEHIST=100000
setopt SHARE_HISTORY INC_APPEND_HISTORY HIST_IGNORE_ALL_DUPS \
       HIST_IGNORE_SPACE HIST_REDUCE_BLANKS HIST_VERIFY EXTENDED_HISTORY
setopt AUTO_CD AUTO_PUSHD PUSHD_IGNORE_DUPS INTERACTIVE_COMMENTS NO_BEEP
```

- [ ] **Step 4: Run tests to verify pass**

Run: `cd ~/.dotfiles && zsh scripts/test.zsh`
Expected: all assertions `ok`.

- [ ] **Step 5: Commit**

```bash
cd ~/.dotfiles && git add config/core.zsh scripts/tests/core.test.zsh
git commit -m "feat(core): history + shell options"
```

---

## Task 4: core.zsh — single cached compinit

**Files:**
- Modify: `~/.dotfiles/config/core.zsh` (append)
- Modify: `~/.dotfiles/scripts/tests/core.test.zsh` (append)

- [ ] **Step 1: Write failing tests (append)**

```zsh
assert_ok "compdef available (compinit ran)" zsh -ic 'whence -w compdef >/dev/null'
assert_ok "compdump created"                 test -f "$HOME/.cache/zsh/zcompdump"
assert_eq "compinit ran exactly once"        "1" "$(zboot 'print -r -- ${_CORE_COMPINIT_COUNT:-0}')"
```

- [ ] **Step 2: Run to verify failure**

Run: `cd ~/.dotfiles && zsh scripts/test.zsh`
Expected: FAIL (no compinit yet, no counter).

- [ ] **Step 3: Append completion block to core.zsh**

```zsh
# ── completion : single cached compinit ──────────────────────────────────────
# Rebuild the dump at most once/day; otherwise fast-path with -C (skip security
# scan). Counter proves we never double-init (the old config's bug).
typeset -gi _CORE_COMPINIT_COUNT=0
() {
  local zcd="$HOME/.cache/zsh/zcompdump"
  [[ -d ${zcd:h} ]] || mkdir -p ${zcd:h}
  autoload -Uz compinit
  # extra completion dirs (docker, custom)
  fpath=("$HOME/.docker/completions"(N) "$HOME/.zsh/completions"(N) $fpath)
  if [[ -n ${zcd}(#qN.mh+24) ]]; then
    compinit -d "$zcd"            # dump >24h old → full rebuild
  else
    compinit -C -d "$zcd"         # fresh → fast path
  fi
  (( _CORE_COMPINIT_COUNT++ ))
}
zstyle ':completion:*' menu select
zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}'
zstyle ':completion:*' list-colors "${(s.:.)LS_COLORS}"
```

- [ ] **Step 4: Run tests to verify pass**

Run: `cd ~/.dotfiles && zsh scripts/test.zsh`
Expected: all `ok`; counter == 1.

- [ ] **Step 5: Commit**

```bash
cd ~/.dotfiles && git add config/core.zsh scripts/tests/core.test.zsh
git commit -m "fix(core): single cached compinit (kills double-compinit bug)"
```

---

## Task 5: core.zsh — plugin loader (clone + source)

**Files:**
- Create: `~/.dotfiles/scripts/install-plugins.sh`
- Modify: `~/.dotfiles/config/core.zsh` (append)
- Modify: `~/.dotfiles/scripts/tests/core.test.zsh` (append)

Resolved fork: **zsh-syntax-highlighting** (not fast-).

- [ ] **Step 1: Write the plugin installer**

Create `~/.dotfiles/scripts/install-plugins.sh`:

```bash
#!/usr/bin/env bash
# Clone/update the 6 zsh plugins into config/plugins/. Idempotent.
set -euo pipefail
DOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
DEST="$DOT/config/plugins"; mkdir -p "$DEST"
declare -A repos=(
  [zsh-autosuggestions]=https://github.com/zsh-users/zsh-autosuggestions
  [zsh-syntax-highlighting]=https://github.com/zsh-users/zsh-syntax-highlighting
  [zsh-completions]=https://github.com/zsh-users/zsh-completions
  [zsh-history-substring-search]=https://github.com/zsh-users/zsh-history-substring-search
  [fzf-tab]=https://github.com/Aloxaf/fzf-tab
  [zsh-you-should-use]=https://github.com/MichaelAquilina/zsh-you-should-use
)
for name in "${!repos[@]}"; do
  if [[ -d "$DEST/$name/.git" ]]; then
    git -C "$DEST/$name" pull --ff-only -q && echo "updated  $name"
  else
    git clone --depth 1 -q "${repos[$name]}" "$DEST/$name" && echo "cloned   $name"
  fi
done
```

- [ ] **Step 2: Run the installer**

Run: `chmod +x ~/.dotfiles/scripts/install-plugins.sh && ~/.dotfiles/scripts/install-plugins.sh`
Expected: 6 lines `cloned <name>`; `ls ~/.dotfiles/config/plugins` shows 6 dirs.

- [ ] **Step 3: Write failing tests (append)**

```zsh
assert_ok "autosuggestions loaded" zsh -ic 'typeset -f _zsh_autosuggest_start >/dev/null'
assert_ok "ysu loaded"             zsh -ic 'typeset -f _check_aliases >/dev/null || alias | grep -q .'
assert_eq "ASYNC autosuggest"      "1" "$(zboot 'print -r -- $ZSH_AUTOSUGGEST_USE_ASYNC')"
assert_ok "syntax-highlighting on" zsh -ic '(( ${+ZSH_HIGHLIGHT_VERSION} )) || typeset -f _zsh_highlight >/dev/null'
```

- [ ] **Step 4: Run to verify failure**

Run: `cd ~/.dotfiles && zsh scripts/test.zsh`
Expected: the 4 new lines FAIL (loader not wired yet).

- [ ] **Step 5: Append plugin loader to core.zsh**

```zsh
# ── plugins : manual loader (replaces oh-my-zsh) ─────────────────────────────
_PLUGIN_DIR="${ZDOTDIR:-$HOME/.dotfiles}/config/plugins"
export ZSH_AUTOSUGGEST_USE_ASYNC=1
export ZSH_AUTOSUGGEST_STRATEGY=(history completion)
export YSU_MESSAGE_POSITION=after
fpath=("$_PLUGIN_DIR/zsh-completions/src"(N) $fpath)
() {
  local p
  for p in zsh-autosuggestions/zsh-autosuggestions.zsh \
           zsh-history-substring-search/zsh-history-substring-search.zsh \
           fzf-tab/fzf-tab.plugin.zsh \
           zsh-you-should-use/you-should-use.plugin.zsh \
           zsh-syntax-highlighting/zsh-syntax-highlighting.zsh; do
    [[ -r "$_PLUGIN_DIR/$p" ]] && source "$_PLUGIN_DIR/$p"
  done
}
# history-substring-search keybinds (after plugin load)
bindkey '^[[A' history-substring-search-up
bindkey '^[[B' history-substring-search-down
```

> Note: zsh-syntax-highlighting must be sourced **last** among plugins (it wraps ZLE), which the loop ordering above ensures.

- [ ] **Step 6: Run tests to verify pass**

Run: `cd ~/.dotfiles && zsh scripts/test.zsh`
Expected: all `ok`.

- [ ] **Step 7: Commit**

```bash
cd ~/.dotfiles && git add scripts/install-plugins.sh config/core.zsh scripts/tests/core.test.zsh
git commit -m "feat(core): manual plugin loader (6 plugins, OMZ replacement)"
```

---

## Task 6: core.zsh — tool integrations (atuin/zsh-abbr/fzf/deno/mise)

**Files:**
- Modify: `~/.dotfiles/config/core.zsh` (append)
- Modify: `~/.dotfiles/scripts/tests/core.test.zsh` (append)

- [ ] **Step 1: Write failing tests (append)**

Guarded by tool presence so the suite passes on machines lacking a tool:

```zsh
if (( $+commands[atuin] )); then
  assert_ok "atuin widget bound" zsh -ic 'typeset -f _atuin_search_widget >/dev/null'
fi
if (( $+commands[mise] )); then
  assert_contains "mise shims on PATH" "$(zboot 'print -r -- $PATH')" "mise"
fi
assert_ok "fzf keybindings sourced (if fzf present)" \
  zsh -ic '(( ! $+commands[fzf] )) || typeset -f fzf-history-widget >/dev/null'
```

- [ ] **Step 2: Run to verify failure**

Run: `cd ~/.dotfiles && zsh scripts/test.zsh`
Expected: atuin/fzf lines FAIL (integrations not wired).

- [ ] **Step 3: Append integrations block to core.zsh**

```zsh
# ── integrations (all guarded; portable mac/linux) ───────────────────────────
(( $+commands[mise] ))    && eval "$(mise activate zsh)"
(( $+commands[atuin] ))   && eval "$(atuin init zsh)"

# fzf keybindings + completion (brew path or system path)
for _f in /opt/homebrew/opt/fzf/shell /usr/share/fzf /usr/share/doc/fzf/examples; do
  [[ -r "$_f/key-bindings.zsh" ]] && { source "$_f/key-bindings.zsh"; source "$_f/completion.zsh" 2>/dev/null; break }
done
[[ -r "$HOME/.fzf.zsh" ]] && source "$HOME/.fzf.zsh"
unset _f

# zsh-abbr (brew)
[[ -r /opt/homebrew/share/zsh-abbr/zsh-abbr.zsh ]] && source /opt/homebrew/share/zsh-abbr/zsh-abbr.zsh

# deno
[[ -r "$HOME/.deno/env" ]] && source "$HOME/.deno/env"
```

- [ ] **Step 4: Run tests to verify pass**

Run: `cd ~/.dotfiles && zsh scripts/test.zsh`
Expected: all present-tool assertions `ok`; absent-tool ones skipped.

- [ ] **Step 5: Commit**

```bash
cd ~/.dotfiles && git add config/core.zsh scripts/tests/core.test.zsh
git commit -m "feat(core): guarded tool integrations (atuin/mise/fzf/abbr/deno)"
```

---

## Task 7: Boot-time performance gate (<2s, target ~300ms)

**Files:**
- Create: `~/.dotfiles/scripts/tests/perf.test.zsh`

- [ ] **Step 1: Write the perf assertion**

Create `~/.dotfiles/scripts/tests/perf.test.zsh`:

```zsh
# Median of 5 interactive boots must be < 2000ms (hard cap).
() {
  local -a samples; local i start end ms
  for i in {1..5}; do
    start=$EPOCHREALTIME
    ZDOTDIR="$DOTFILES" zsh -ic 'exit' >/dev/null 2>&1
    end=$EPOCHREALTIME
    samples+=( $(( (end - start) * 1000 )) )
  done
  local median=${${(on)samples}[3]}
  printf -v median '%.0f' $median
  print -P "   boot median: ${median}ms"
  (( T_RUN++ ))
  if (( median < 2000 )); then print -P "%F{green}ok%f   boot under 2s (${median}ms)"
  else print -P "%F{red}FAIL%f boot too slow (${median}ms)"; (( T_FAIL++ )); fi
}
```

Requires `zmodload zsh/datetime` for `$EPOCHREALTIME` — add at top of the file:

```zsh
zmodload zsh/datetime
```

- [ ] **Step 2: Run the perf test**

Run: `cd ~/.dotfiles && zsh scripts/test.zsh`
Expected: prints `boot median: <N>ms` and `ok boot under 2s`. If FAIL, profile with `ZDOTDIR=~/.dotfiles zsh -ixc exit 2>&1 | tail -40` and report the slow line before adjusting.

- [ ] **Step 3: Commit**

```bash
cd ~/.dotfiles && git add scripts/tests/perf.test.zsh
git commit -m "test: boot-time perf gate (<2s)"
```

---

## Task 8: setup.sh — reversible cutover via ~/.zshenv

**Files:**
- Create: `~/.dotfiles/scripts/setup.sh`
- Create: `~/.dotfiles/scripts/tests/setup.test.zsh`

- [ ] **Step 1: Write failing tests**

Create `~/.dotfiles/scripts/tests/setup.test.zsh` (uses a throwaway `$HOME`):

```zsh
() {
  local sand="$(mktemp -d)"
  # seed a fake existing config to confirm it gets backed up, not destroyed
  print 'echo OLD' > "$sand/.zshrc"
  HOME="$sand" bash "$DOTFILES/scripts/setup.sh" --link >/dev/null 2>&1
  assert_contains "zshenv exports ZDOTDIR" "$(<"$sand/.zshenv")" 'export ZDOTDIR='
  assert_ok "old .zshrc backed up" bash -c "ls $sand/.dotfiles-backup-*/.zshrc >/dev/null 2>&1"
  assert_eq "old .zshrc untouched" "echo OLD" "$(<"$sand/.zshrc")"
  HOME="$sand" bash "$DOTFILES/scripts/setup.sh" --revert >/dev/null 2>&1
  assert_ok "revert removes zshenv" bash -c "[[ ! -f $sand/.zshenv ]]"
  rm -rf "$sand"
}
```

- [ ] **Step 2: Run to verify failure**

Run: `cd ~/.dotfiles && zsh scripts/test.zsh`
Expected: FAIL (`setup.sh` missing).

- [ ] **Step 3: Write setup.sh**

Create `~/.dotfiles/scripts/setup.sh`:

```bash
#!/usr/bin/env bash
# Foundation setup: backup existing zsh config, then write ~/.zshenv so zsh
# loads ~/.dotfiles. Fully reversible with --revert (rm ~/.zshenv).
set -euo pipefail
DOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
ZSHENV="$HOME/.zshenv"
MARK="# >>> dotfiles ZDOTDIR >>>"

backup() {
  local ts dir; ts="$(date +%Y%m%d-%H%M%S)"; dir="$HOME/.dotfiles-backup-$ts"
  mkdir -p "$dir"
  for f in .zshrc .zshenv .zprofile .pentest.zsh .pentest-mac.zsh .tmux.conf; do
    [[ -e "$HOME/$f" && ! -L "$HOME/$f" ]] && cp -a "$HOME/$f" "$dir/" && echo "backed up $f -> $dir"
  done
}

link() {
  backup
  "$DOT/scripts/install-plugins.sh"
  if ! grep -q "$MARK" "$ZSHENV" 2>/dev/null; then
    { echo "$MARK"; echo 'export ZDOTDIR="$HOME/.dotfiles"'; echo "# <<< dotfiles ZDOTDIR <<<"; } >> "$ZSHENV"
    echo "wrote ZDOTDIR to $ZSHENV"
  fi
  echo "Done. Open a new shell. Revert anytime: $0 --revert"
}

revert() {
  if [[ -f "$ZSHENV" ]] && grep -q "$MARK" "$ZSHENV"; then
    # strip only our block; remove file if it becomes empty
    sed -i.bak "/$MARK/,/# <<< dotfiles ZDOTDIR <<</d" "$ZSHENV" && rm -f "$ZSHENV.bak"
    [[ -s "$ZSHENV" ]] || rm -f "$ZSHENV"
    echo "reverted: old ~/.zshrc is active again"
  fi
}

case "${1:-}" in
  --link)   link ;;
  --revert) revert ;;
  --check)  echo "DOT=$DOT  ZSHENV=$ZSHENV"; [[ -f "$ZSHENV" ]] && grep -q "$MARK" "$ZSHENV" && echo "ACTIVE" || echo "INACTIVE" ;;
  *) echo "usage: setup.sh --link | --revert | --check"; exit 1 ;;
esac
```

- [ ] **Step 4: Run tests to verify pass**

Run: `cd ~/.dotfiles && chmod +x scripts/setup.sh && zsh scripts/test.zsh`
Expected: all setup assertions `ok`. (Live `~/.zshenv` untouched — tests use a sandbox HOME.)

- [ ] **Step 5: Commit**

```bash
cd ~/.dotfiles && git add scripts/setup.sh scripts/tests/setup.test.zsh
git commit -m "feat(setup): reversible ~/.zshenv cutover + config backup"
```

---

## Task 9: README stub + full suite green

**Files:**
- Create: `~/.dotfiles/README.md`

- [ ] **Step 1: Write README stub**

Create `~/.dotfiles/README.md`:

```markdown
# dotfiles — modular zsh / tmux / pentest environment

Fast, OMZ-free zsh. Engagement tracker, animated fetch, tmux, and docs land in
later phases.

## Install
```bash
git clone <this> ~/.dotfiles
~/.dotfiles/scripts/setup.sh --link   # backs up old config, writes ~/.zshenv
exec zsh
```

## Revert
```bash
~/.dotfiles/scripts/setup.sh --revert  # restores your previous ~/.zshrc
```

## Test
```bash
zsh ~/.dotfiles/scripts/test.zsh
```

## Layout
- `.zshrc` — orchestrator (sources `config/*.zsh` in order)
- `config/core.zsh` — env, PATH, history, compinit, plugin loader, integrations
- `scripts/` — setup, plugin install, tests
```

- [ ] **Step 2: Run the full suite**

Run: `cd ~/.dotfiles && zsh scripts/test.zsh`
Expected: every assertion `ok`, perf under 2s, summary all-passed exit 0.

- [ ] **Step 3: Commit**

```bash
cd ~/.dotfiles && git add README.md && git commit -m "docs: foundation README stub"
```

---

## Manual cutover (operator step — run only when ready)

Not part of automated tests; this switches your live shell.

```bash
~/.dotfiles/scripts/setup.sh --link   # backup + ~/.zshenv + clone plugins
exec zsh                              # load the new environment
zsh ~/.dotfiles/scripts/test.zsh      # confirm green in the live context
# If anything is wrong:
~/.dotfiles/scripts/setup.sh --revert && exec zsh
```

---

## Self-review notes

- **Spec coverage (§5, §4 load order, §14 cuts):** OMZ dropped (Task 2/5), single cached compinit (Task 4) — both perf bugs fixed; lightweight loader (Task 5); orchestrator with guarded ordered sourcing (Task 2); reversible cutover (Task 8); <2s gate (Task 7). `theme/database/pentesting/aliases/functions/animations` are sourced-if-present and built in Plans 2–4.
- **No placeholders:** every step has concrete code/commands + expected output.
- **Type/name consistency:** `zboot`, `assert_eq/contains/ok`, `t_summary`, `_CORE_COMPINIT_COUNT`, `_PLUGIN_DIR`, `$MARK`, `--link/--revert/--check` are used consistently across tasks.
- **Deferred to later plans:** OMZ-builtin reimplementations (extract/copypath/dirhistory/web-search/urltools/colored-man-pages) → `functions.zsh` (Plan 3); starship + target segment → `theme.zsh` (Plan 3); pentest lazy-load + merged `command_not_found_handler` → `pentesting.zsh` (Plan 3).
```