Skip to content
Back to skills

Linux Mirror

FSecurity

Mirror the current git dir/worktree/branch onto a Linux machine and continue the work session there instead of locally. Pushes the branch, checks it out remotely via SSH, and drops into a tmux session. Falls back to Slack if SSH is unreachable. Use when asked to move/continue work on the Linux box, hand off to it, or mirror this session to Linux.

  • 6 stars
  • 0 votes
  • 0 copies
  • 1 view
  • Added November 26, 2026
toolsrustgoshellbashreactnodetestinggit

Works with

  • claude code
  • cursor
  • terminal
  • cli

Security analysis

F25/100
  • criticalAccesses sensitive system or user directories
  • criticalReads or references SSH private keys
  • criticalModifies startup scripts or system services for persistence
  • criticalModifies startup scripts or system services for persistence
  • criticalSends environment variables or credentials to an external URL

Pro shows the line behind each finding and how to fix it

Scanned November 26, 2026

npx -y skills add jleechanorg/jleechan-skills --skill linux-mirror --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Linux Mirror?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Linux Mirror
[![Security: F — Skills Directory](https://www.skillsdirectory.com/api/skills/jleechanorg-linux-mirror/badge)](https://www.skillsdirectory.com/skills/jleechanorg-linux-mirror)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: linux-mirror
description: "Mirror the current git dir/worktree/branch onto a Linux machine and continue the work session there instead of locally. Pushes the branch, checks it out remotely via SSH, and drops into a tmux session. Falls back to Slack if SSH is unreachable. Use when asked to move/continue work on the Linux box, hand off to it, or mirror this session to Linux."
---

# Linux Mirror — hand this branch off to a Linux machine

Companion to [mac-mirror](../mac-mirror/SKILL.md) (same flow, opposite direction). Unlike a plain SSH-steering skill, this mirrors the **current repo's committed state** onto the target machine and resumes work there in a persistent tmux session.

Before every handoff, follow
[host load balancing](../parallelize-to-ceiling/references/host-load-balancing.md)
for fresh resource checks on both hosts, host selection and task ownership; this
skill owns Linux transport and response proof. Record the measurements and
decision before starting the remote checkout or agent.

If this host is blocked (disk full, CPU/memory admission gate, missing tool,
unavailable simulator, host-local auth), use this skill to move the work to
Linux and keep working there; do not stop or wait.

Follow the [lightweight caller contract](../linux-remote/SKILL.md#lightweight-caller-remote-execution-owner): the caller drives transport and verifies receipts; the target agent owns execution.

## Setup (once, per pair of machines)

This skill assumes you've already got:
- An SSH host alias for the Linux box in `~/.ssh/config` (LAN), e.g.:
  ```
  Host mylinux
      HostName 192.0.2.10
      User myusername
      IdentityFile ~/.ssh/id_ed25519
  ```
  (`ssh_config` does not expand environment variables — write your actual username literally, not `$USER`.)
- Your repo lives under `$HOME` on the source machine (any relative path). This skill resolves a writable target root with the target host's canonical `diskm scratch-dir` command, then mirrors the checkout under that Scratch root. Agent output and disposable tool files use a separate Scratch output directory. If the configured Scratch volume is unavailable, the resolver failure is fatal; do not fall back to `/tmp` or `$HOME/mirror`. A repo outside `$HOME` on the source side isn't supported — step 1 below checks for this and stops rather than silently producing a wrong path.
- (Optional, for off-LAN/travel use) Both machines joined to the same Tailscale tailnet. Note: a bare SSH alias like the one above resolves its `HostName` literally — it does NOT fail over to Tailscale automatically. Off-LAN, connect via the Tailscale IP directly with the identity file explicit: `ssh -i ~/.ssh/id_ed25519 myusername@<tailscale-ip>` (look it up with `tailscale status | grep <hostname>` — don't hardcode it, Tailscale IPs are stable per-device but you should still re-verify rather than assume).
- (Optional, for SSH-fully-down fallback) A messaging-gateway agent (e.g. a Hermes-style gateway, or anything that runs commands on your behalf) running on the Linux box, watching a Slack channel (or similar) you can post to.

Substitute your own host alias / IP / key path / username everywhere `mylinux` / `myusername` appears below.

## What this carries over

Only **committed and pushed** state — the current branch's HEAD. Uncommitted/staged local edits are NOT transferred (that's an explicit tradeoff for a simple, reliable git-based mirror; commit or stash first if you need them).

## Steps

### 1. Detect local state

```bash
REPO_ROOT=$(git rev-parse --show-toplevel)
BRANCH=$(git -C "$REPO_ROOT" branch --show-current)
REMOTE_URL=$(git -C "$REPO_ROOT" remote get-url origin)
INTENDED_SHA=$(git -C "$REPO_ROOT" rev-parse HEAD)
DIRTY=$(git -C "$REPO_ROOT" status --porcelain)

case "$REPO_ROOT" in
  "$HOME"/*) REL_PATH=${REPO_ROOT#"$HOME/"} ;;
  *) echo "ERROR: repo root ($REPO_ROOT) is not under \$HOME ($HOME) — this skill mirrors by \$HOME-relative path on both machines. Move or symlink the repo under \$HOME first." >&2; exit 1 ;;
esac
```

Also prepare `$CONTEXT`: a short, self-contained summary (1-3 sentences) of what should actually continue on the Linux machine — the real next action, not just "resume work." This isn't optional bookkeeping: step 4 types it as the first message to a freshly-launched coding agent on the target machine, which has no access to this conversation. Write it as if briefing a colleague who just walked in cold.

If `$CONTEXT` is empty, stop here before pushing or opening SSH. The remote launcher checks it again before validating the CLI.

Include a fresh dispatch marker in the handoff. Ask the Linux coder to perform the first task-specific action, then reply in **2–3 sentences** with the marker, the action it ran, the observed result or inspectable handle, and its next action or exact blocker. Use the same request for a resumed session or messaging-gateway handoff.

Also resolve `$AGENT_CLI`: the CLI **that is calling this skill**, i.e. the operator's live runtime (pi → `pi`, Claude Code → `claude`, Codex → `codex`, Antigravity → `agy`). This skill deliberately has no default CLI. Launching a CLI the operator is not using hands the work to an agent with different tools, skills, model and quota — that is a substitution to state explicitly in the report, never a silent default. Only set a different `$AGENT_CLI` when the calling CLI is genuinely unusable on the target host (for example its seat is quota-walled), and say why.

For Claude, preserve the selected profile without transferring credentials. Resolve `CLAUDE_LAUNCHER` before pushing: use `claudewa` when source `CLAUDE_CONFIG_DIR` explicitly ends in `.claude-wa`, and `claude` only when the profile is unset or selects the default `~/.claude`; stop for any other profile without a matching target wrapper. Keep `$AGENT_CLI=claude`. Before pushing, verify the selected target wrapper and intended profile/account; if unavailable or unverified, report the scoped blocker instead of falling back. Never copy credentials or silently switch profiles/accounts.

```bash
CLAUDE_LAUNCHER=""
if [ "$AGENT_CLI" = claude ]; then
  CLAUDE_LAUNCHER=claude
  case "${CLAUDE_CONFIG_DIR:-}" in
    */.claude-wa|.claude-wa) CLAUDE_LAUNCHER=claudewa ;;
    ""|"$HOME/.claude"|~/.claude) ;;
    *) echo "ERROR: explicitly selected Claude profile has no known matching target wrapper; refusing profile fallback" >&2; exit 75 ;;
  esac
fi
case "$AGENT_CLI" in
  pi|claude|codex|agy) ;;
  *) echo "ERROR: unsupported AGENT_CLI '$AGENT_CLI' (pi|claude|codex|agy)" >&2; exit 75 ;;
esac
```

If `$BRANCH` is empty (detached HEAD) or `$DIRTY` is non-empty, stop and tell the user — commit/name the branch first.

If `$REMOTE_URL` is an HTTPS URL with an embedded credential (`https://<token>@host/...`), warn the user before continuing: that URL gets written verbatim into the remote clone's `.git/config` in step 4, so the credential ends up live on the target machine too. Prefer an SSH remote, or a credential helper that doesn't embed the token in the URL. (Step 4's base64 encoding is not a confidentiality measure for this value — it only prevents argv re-tokenization/injection. A trivially-decodable token is still visible in the remote host's `ps` output during the mirror.)

### 2. Resolve the target and verify readiness

First run the [cross-machine-ssh-tier](../cross-machine-ssh-tier/SKILL.md) Tier 1→2 ladder with the configured peer alias, key and user. Resolve `SSH_ARGS`/`SSH_TARGET` before running the probe below, then retain that exact connection for step 4. An empty target selects Tier 3; it does not authorize dispatch yet. Publish and verify the branch in step 3 before sending any gateway handoff.

For a resolved SSH target, complete an authenticated command roundtrip and obtain a contemporaneous CPU sample. Failure stops the caller before publication or dispatch even when its shell does not use `set -e`:

```bash
mirror_readiness() {
  if [ -z "$SSH_TARGET" ]; then
    # Tier 3 readiness is checked by the receiving operator before execution.
    return 0
  fi
  if [ "$AGENT_CLI" = claude ]; then
    ssh "${SSH_ARGS[@]}" "$SSH_TARGET" bash -l -s -- "$CLAUDE_LAUNCHER" <<'EOF'
  command -v "$1" >/dev/null 2>&1 || {
    echo "ERROR: selected Claude wrapper is unavailable in the target login shell" >&2
    exit 127
  }
  CPU_SAMPLE=$(top -bn2 -d1 | grep "%Cpu" | tail -1)
  [ -n "$CPU_SAMPLE" ] || {
    echo "ERROR: top returned no CPU sample" >&2
    exit 75
  }
  printf "%s\n" "$CPU_SAMPLE"
EOF
  else
    ssh "${SSH_ARGS[@]}" "$SSH_TARGET" 'CPU_SAMPLE=$(top -bn2 -d1 | grep "%Cpu" | tail -1); [ -n "$CPU_SAMPLE" ] || { echo "ERROR: top returned no CPU sample" >&2; exit 75; }; printf "%s\n" "$CPU_SAMPLE"'
  fi
}
mirror_readiness || {
  echo "ERROR: resolved target failed readiness; stopping before push or dispatch" >&2
  exit 75
}
```

Ping, TCP reachability, and dated CPU samples do not establish readiness. Apply the task's recorded admission criterion; keep host selection and thresholds out of this portable skill.

For either Claude launcher, the probe above establishes command presence only. Before step 3, inspect the selected launcher definition in the target login shell (`type claude` or `type claudewa`) to confirm its profile selection and any authentication-environment overrides. Then use the installed CLI's read-only `auth status` command in that same authentication context: for the default profile, `(unset CLAUDE_CONFIG_DIR; command claude auth status --text)`; for the `.claude-wa` profile, `CLAUDE_CONFIG_DIR="$HOME/.claude-wa" command claude auth status --text`. Run these on the target, so `$HOME` resolves there. Compare the reported signed-in account with the intended source account, and record only match/mismatch plus the profile, not credentials or full authentication output. These examples apply only if the inspected launcher has no other authentication overrides; otherwise resolve and inspect its actual context before proceeding. If the installed CLI lacks this read-only command, reports no account, or the account/context cannot be matched, stop before publication and report the blocker. Do not invoke login/logout, copy credentials, or execute a wrapper with account-switching side effects merely to inspect it. Tier 3 receivers must perform the same check before execution.

### 3. Push the branch (make it visible to the Linux machine)

```bash
[ -n "$CONTEXT" ] || { echo "ERROR: CONTEXT is required" >&2; exit 75; }
CURRENT_SHA=$(git -C "$REPO_ROOT" rev-parse HEAD) || exit 75
[ "$CURRENT_SHA" = "$INTENDED_SHA" ] || {
  echo "ERROR: source changed since preflight; resolve the new candidate first" >&2
  exit 75
}
git -C "$REPO_ROOT" push origin "$INTENDED_SHA:refs/heads/$BRANCH" || exit 75
PUBLISHED_REF=$(git -C "$REPO_ROOT" ls-remote --exit-code origin "refs/heads/$BRANCH") || exit 75
[ "${PUBLISHED_REF%%[[:space:]]*}" = "$INTENDED_SHA" ] || {
  echo "ERROR: published branch does not match intended source; refusing dispatch" >&2
  exit 75
}
git -C "$REPO_ROOT" branch --set-upstream-to="origin/$BRANCH" "$BRANCH" || exit 75
```

Follow existing push authority and branch ownership; a successful push alone is not the readback above. If the target is empty (Tier 3), only now send the authorized gateway handoff with the verified remote URL, branch, exact published SHA, caller/profile, context and step 4's remote payload. Require the receiver to verify its own readiness/profile and exact fetched SHA before starting work; report unavailable checks rather than implying SSH readiness. A failed push or mismatched ref stops both transports. Do not run the SSH block below for Tier 3.

### 4. Remote checkout + tmux (Tier 1/2 only — skip if `$SSH_TARGET` is empty, that means Tier 3 applies instead)

Arguments are base64-encoded before crossing the wire. This isn't just a quoting nicety: `ssh host command args...` does not preserve argv separation — the remote login shell re-joins and re-tokenizes the command line, so an unencoded branch name containing a space silently shifts which value lands in `$1`/`$2`/`$3`, and one containing shell metacharacters (`;`, `` ` ``, `$()`, `&&`, `|` — all valid in a git branch name) executes arbitrary commands on the remote host. Base64 output contains none of those characters, so encoding closes both problems regardless of what the original value contains.

```bash
REL_PATH_B64=$(printf '%s' "$REL_PATH" | base64 | tr -d '\n')
BRANCH_B64=$(printf '%s' "$BRANCH" | base64 | tr -d '\n')
REMOTE_URL_B64=$(printf '%s' "$REMOTE_URL" | base64 | tr -d '\n')
CONTEXT_B64=$(printf 'x%s' "$CONTEXT" | base64 | tr -d '\n')
AGENT_CLI_B64=$(printf '%s' "$AGENT_CLI" | base64 | tr -d '\n')
# Keep the launcher argv nonempty; SSH reconstructs its remote command as shell text.
CLAUDE_LAUNCHER_ARG=${CLAUDE_LAUNCHER:-not-applicable}
CLAUDE_LAUNCHER_B64=$(printf '%s' "$CLAUDE_LAUNCHER_ARG" | base64 | tr -d '\n')
INTENDED_SHA_B64=$(printf '%s' "$INTENDED_SHA" | base64 | tr -d '\n')

ssh "${SSH_ARGS[@]}" "$SSH_TARGET" bash -s -- "$REL_PATH_B64" "$BRANCH_B64" "$REMOTE_URL_B64" "$CONTEXT_B64" "$AGENT_CLI_B64" "$CLAUDE_LAUNCHER_B64" "$INTENDED_SHA_B64" << 'EOF'
set -e
REL_PATH=$(printf '%s' "$1" | base64 -d)
BRANCH=$(printf '%s' "$2" | base64 -d)
REMOTE_URL=$(printf '%s' "$3" | base64 -d)
TARGET=""
CONTEXT_PAYLOAD=$(printf '%s' "$4" | base64 -d)
case "$CONTEXT_PAYLOAD" in
  x*) CONTEXT=${CONTEXT_PAYLOAD#x} ;;
  *) echo "FAILED:$TARGET — invalid CONTEXT payload" >&2; exit 1 ;;
esac
AGENT_CLI=$(printf '%s' "$5" | base64 -d)
CLAUDE_LAUNCHER=$(printf '%s' "$6" | base64 -d)
INTENDED_SHA=$(printf '%s' "$7" | base64 -d)
case "$AGENT_CLI:$CLAUDE_LAUNCHER" in
  claude:claude|claude:claudewa|pi:not-applicable|codex:not-applicable|agy:not-applicable) ;;
  *) echo "FAILED:$REL_PATH — invalid CLI/profile selection; refusing mirror reuse" >&2; exit 75 ;;
esac
if [[ ! "$INTENDED_SHA" =~ ^[0-9a-f]{40}$ ]]; then
  echo "FAILED:$REL_PATH — invalid intended source SHA" >&2
  exit 75
fi

if [ -z "$CONTEXT" ]; then
  echo "FAILED:$TARGET — CONTEXT is empty; refusing to start a bare shell" >&2
  exit 1
fi

# Contain every Git process used by this remote bootstrap. Resolve Git before
# defining the wrapper, and fail closed unless the user systemd manager and its
# aggregate agents.slice memory ceiling are available. The scope limits each
# Git command; agents.slice supplies the finite aggregate ceiling.
GIT_BIN=$(type -P git) || { echo "FAILED:$REL_PATH — git is unavailable" >&2; exit 75; }
case "$GIT_BIN" in /*) [ -x "$GIT_BIN" ] || { echo "FAILED:$REL_PATH — resolved git is not executable" >&2; exit 75; } ;; *) echo "FAILED:$REL_PATH — git did not resolve to an executable path" >&2; exit 75 ;; esac
SYSTEMD_RUN=$(command -v systemd-run) || { echo "FAILED:$REL_PATH — systemd-run is unavailable; refusing uncontained Git" >&2; exit 75; }
SYSTEMCTL=$(command -v systemctl) || { echo "FAILED:$REL_PATH — systemctl is unavailable; refusing uncontained Git" >&2; exit 75; }
export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
export DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-unix:path=$XDG_RUNTIME_DIR/bus}"
AGENTS_MEMORY_MAX=$("$SYSTEMCTL" --user show agents.slice -p MemoryMax --value 2>/dev/null) || {
  echo "FAILED:$REL_PATH — user systemd manager or agents.slice is unavailable; refusing uncontained Git" >&2
  exit 75
}
[[ "$AGENTS_MEMORY_MAX" =~ ^[0-9]+$ && ! "$AGENTS_MEMORY_MAX" =~ ^0+$ ]] || {
  echo "FAILED:$REL_PATH — agents.slice has no finite positive MemoryMax; refusing uncontained Git" >&2
  exit 75
}
git() {
  "$SYSTEMD_RUN" --user --scope --quiet --slice=agents.slice \
    -p MemoryHigh=3G -p MemoryMax=4G -p MemorySwapMax=512M \
    -p TasksMax=256 -p OOMPolicy=kill "$GIT_BIN" "$@" 9>&-
}

# Scratch is the only mirror destination. `diskm scratch-dir` performs the
# host-specific volume, availability, and admission checks. Keep the checkout
# and the agent's generated output in separate paths. A resolver failure is
# fatal; do not fall back to HOME or /tmp.
SCRATCH_ROOT="$(diskm scratch-dir 2>/dev/null)" || {
  echo "FAILED:$REL_PATH — canonical Scratch resolver failed; refusing HOME/tmp fallback" >&2
  exit 75
}
[ -n "$SCRATCH_ROOT" ] && [ -d "$SCRATCH_ROOT" ] || {
  echo "FAILED:$REL_PATH — canonical Scratch resolver returned no usable root" >&2
  exit 75
}
[ "$SCRATCH_ROOT" != "/tmp" ] || {
  echo "FAILED:$REL_PATH — Scratch is unconfigured; refusing the canonical /tmp fallback" >&2
  exit 75
}
MIRROR_KEY=$(printf '%s' "$REL_PATH" | cksum | cut -d' ' -f1)
BRANCH_KEY=$(printf '%s' "$BRANCH" | cksum | cut -d' ' -f1)
OUTPUT_SUBPATH="mirror-output/$MIRROR_KEY/$BRANCH_KEY"
OUTPUT_ROOT="$(diskm scratch-dir "$OUTPUT_SUBPATH" 2>/dev/null)" || {
  echo "FAILED:$REL_PATH — canonical Scratch output allocation failed" >&2
  exit 75
}
# Serialize cooperative bootstraps for this repository/branch without a new
# lock file. The existing Scratch output directory is the lock inode; fd 9 is
# held through session preflight, Git mutation, and tmux creation.
exec 9<"$OUTPUT_ROOT" || {
  echo "FAILED:$REL_PATH — cannot open Scratch coordination directory" >&2
  exit 75
}
flock -n 9 || {
  echo "FAILED:$REL_PATH — another mirror bootstrap holds the Scratch lock" >&2
  exit 75
}
TARGET_SUBPATH="mirrors/$MIRROR_KEY/$BRANCH_KEY/$REL_PATH"
TARGET="$(diskm scratch-dir "$TARGET_SUBPATH" 2>/dev/null)" || {
  echo "FAILED:$REL_PATH — canonical Scratch target allocation failed" >&2
  exit 75
}

BRANCH_SAFE=$(printf '%s' "$BRANCH" | tr -c 'a-zA-Z0-9_-' '-')
BRANCH_HASH=$(printf '%s' "$BRANCH" | cksum | cut -d' ' -f1)
SESSION="mirror-${MIRROR_KEY}-${BRANCH_SAFE}-${BRANCH_HASH}"
# Check an existing session before any clone, fetch, checkout, pull, or output
# mkdir. A matching branch in another repository cannot reuse this repo-keyed
# session name; a mismatched target is a hard failure, never a RESUMED claim.
if tmux has-session -t "=$SESSION" 2>/dev/null; then
  SESSION_CWD=$(tmux display-message -p -t "=$SESSION" '#{pane_current_path}' 2>/dev/null || true)
  [ -n "$SESSION_CWD" ] || { echo "FAILED:$SESSION — cannot inspect existing session cwd" >&2; exit 75; }
  SESSION_CWD_REAL=$(cd "$SESSION_CWD" 2>/dev/null && pwd -P) || {
    echo "FAILED:$SESSION — existing session cwd is unreadable" >&2
    exit 75
  }
  TARGET_REAL=$(cd "$TARGET" 2>/dev/null && pwd -P) || {
    echo "FAILED:$SESSION — existing session target is unreadable" >&2
    exit 75
  }
  [ "$SESSION_CWD_REAL" = "$TARGET_REAL" ] || {
    echo "FAILED:$SESSION — existing session target mismatch ($SESSION_CWD_REAL != $TARGET_REAL)" >&2
    exit 75
  }
  SESSION_ORIGIN=$(git -C "$TARGET" remote get-url origin 2>/dev/null || true)
  SESSION_BRANCH=$(git -C "$TARGET" branch --show-current 2>/dev/null || true)
  [ "$SESSION_ORIGIN" = "$REMOTE_URL" ] || {
    echo "FAILED:$SESSION — existing session origin mismatch" >&2
    exit 75
  }
  [ "$SESSION_BRANCH" = "$BRANCH" ] || {
    echo "FAILED:$SESSION — existing session branch mismatch" >&2
    exit 75
  }
  SESSION_AGENT_CLI=$(tmux show-option -qv -t "=$SESSION" @mirror-agent-cli 2>/dev/null || true)
  [ -n "$SESSION_AGENT_CLI" ] || {
    echo "FAILED:$SESSION — existing session has no recorded CLI; refusing RESUMED" >&2
    exit 75
  }
  [ "$SESSION_AGENT_CLI" = "$AGENT_CLI" ] || {
    echo "FAILED:$SESSION — existing session CLI mismatch ($SESSION_AGENT_CLI != $AGENT_CLI); refusing RESUMED" >&2
    exit 75
  }
  if [ "$AGENT_CLI" = "claude" ]; then
    SESSION_CLAUDE_LAUNCHER=$(tmux show-option -qv -t "=$SESSION" @mirror-claude-launcher 2>/dev/null || true)
    [ -n "$SESSION_CLAUDE_LAUNCHER" ] || {
      echo "FAILED:$SESSION — existing session has no recorded Claude profile; refusing RESUMED" >&2
      exit 75
    }
    [ "$SESSION_CLAUDE_LAUNCHER" = "$CLAUDE_LAUNCHER" ] || {
      echo "FAILED:$SESSION — existing session Claude profile mismatch ($SESSION_CLAUDE_LAUNCHER != $CLAUDE_LAUNCHER); refusing RESUMED" >&2
      exit 75
    }
  fi
  SESSION_HEAD=$(git -C "$TARGET" rev-parse HEAD 2>/dev/null || true)
  [ "$SESSION_HEAD" = "$INTENDED_SHA" ] || {
    echo "FAILED:$SESSION — active checkout SHA $SESSION_HEAD differs from intended source $INTENDED_SHA; preserving it" >&2
    exit 75
  }
  echo "RESUMED:$SESSION:$TARGET:$OUTPUT_ROOT:$SESSION_HEAD"
  exit 0
fi

# A child Bash reads BASH_ENV before its command. The host's BASH_ENV normally
# sources ~/.bashrc, which resets the two output variables to Scratch/tmp.
# Preserve that startup (including credentials), then restore this mirror's
# values. Re-export BASH_ENV so nested non-login Bash shells do the same.
SCOPED_BASH_ENV=$(mktemp "$OUTPUT_ROOT/.mirror-bash-env.XXXXXX") || {
  echo "FAILED:$OUTPUT_ROOT — cannot allocate scoped Bash startup" >&2
  exit 75
}
HOST_BASH_ENV=${BASH_ENV:-}
{
  if [ -n "$HOST_BASH_ENV" ]; then
    printf 'if [ -f %q ]; then . %q; fi\n' "$HOST_BASH_ENV" "$HOST_BASH_ENV"
  fi
  printf 'export CLAUDE_CODE_TMPDIR=%q\n' "$OUTPUT_ROOT"
  printf 'export PYTEST_DEBUG_TEMPROOT=%q\n' "$OUTPUT_ROOT"
  printf 'export BASH_ENV=%q\n' "$SCOPED_BASH_ENV"
} > "$SCOPED_BASH_ENV"
# Launch command for the caller's own CLI (see step 1: no hardcoded default).
# Keep the host's TMPDIR unchanged. Codex shell calls must use login:false:
# login Bash reads ~/.bash_profile after/instead of BASH_ENV and resets output.
LAUNCH_ENV=(env "DISKM_SCRATCH=$SCRATCH_ROOT" "CLAUDE_CODE_TMPDIR=$OUTPUT_ROOT" "PYTEST_DEBUG_TEMPROOT=$OUTPUT_ROOT" "BASH_ENV=$SCOPED_BASH_ENV")
# Claude launchers can be shell functions supplied by the target login profile.
# Keep the selected launcher and its arguments as argv; do not pass them through
# `env` (which cannot invoke functions) or reparse them as shell source.
# Clear an inherited alternate config only for the explicitly selected default
# launcher; claudewa remains responsible for its own verified profile selection.
CLAUDE_LOGIN=(bash -l -c
  'export DISKM_SCRATCH="$1" CLAUDE_CODE_TMPDIR="$2" PYTEST_DEBUG_TEMPROOT="$2" BASH_ENV="$3"; cd -- "$4" || exit 75; shift 4; if [ "$1" = claude ]; then unset CLAUDE_CONFIG_DIR; fi; "$@"'
  mirror-launch "$SCRATCH_ROOT" "$OUTPUT_ROOT" "$SCOPED_BASH_ENV" "$TARGET")
case "$AGENT_CLI" in
  pi)     LAUNCH=("${LAUNCH_ENV[@]}" pi -- "Caller handoff context: $CONTEXT") ;;
  claude)
    case "$CLAUDE_LAUNCHER" in
      claude) LAUNCH=("${CLAUDE_LOGIN[@]}" claude --dangerously-skip-permissions -- "$CONTEXT") ;;
      claudewa)
        if ! bash -lc 'command -v claudewa >/dev/null 2>&1'; then
          echo "FAILED:$TARGET — source selected .claude-wa, but matching target wrapper claudewa is unavailable in the login shell; refusing profile fallback" >&2
          exit 75
        fi
        LAUNCH=("${CLAUDE_LOGIN[@]}" claudewa --dangerously-skip-permissions -- "$CONTEXT") ;;
      *) echo "FAILED:$TARGET — unsupported Claude profile launcher '$CLAUDE_LAUNCHER'; refusing profile fallback" >&2; exit 75 ;;
    esac ;;
  codex)  LAUNCH=("${LAUNCH_ENV[@]}" codex
            -c "shell_environment_policy.set.DISKM_SCRATCH=$SCRATCH_ROOT"
            -c "shell_environment_policy.set.CLAUDE_CODE_TMPDIR=$OUTPUT_ROOT"
            -c "shell_environment_policy.set.PYTEST_DEBUG_TEMPROOT=$OUTPUT_ROOT"
            -c "shell_environment_policy.set.BASH_ENV=$SCOPED_BASH_ENV"
            --dangerously-bypass-approvals-and-sandbox -C "$TARGET" -- "$CONTEXT

Mirror shell contract: set login:false on every exec_command Bash call so BASH_ENV restores CLAUDE_CODE_TMPDIR and PYTEST_DEBUG_TEMPROOT to $OUTPUT_ROOT after host startup. Keep TMPDIR unchanged.") ;;
  agy)    LAUNCH=("${LAUNCH_ENV[@]}" agy --dangerously-skip-permissions --model gemini-3.8-flash-high --prompt-interactive="$CONTEXT") ;;
  *) echo "FAILED:$TARGET - unsupported AGENT_CLI '$AGENT_CLI' (pi|claude|codex|agy)" >&2; exit 1 ;;

esac


if [ ! -e "$TARGET/.git" ]; then
  mkdir -p "$(dirname "$TARGET")"
  git clone "$REMOTE_URL" "$TARGET"
fi

cd "$TARGET"

ORIGIN_URL=$(git remote get-url origin 2>/dev/null || echo "")
if [ -n "$ORIGIN_URL" ] && [ "$ORIGIN_URL" != "$REMOTE_URL" ]; then
  echo "ERROR:$TARGET already has a different origin ($ORIGIN_URL) — not touching it, resolve manually" >&2
  exit 1
fi

if [ -n "$(git status --porcelain --untracked-files=all --ignore-submodules=none)" ]; then
  echo "ERROR:$TARGET has uncommitted changes on the remote side — not overwriting them, resolve manually" >&2
  exit 1
fi

git fetch origin "$BRANCH"
REMOTE_BRANCH_SHA=$(git rev-parse "origin/$BRANCH")
if [ "$REMOTE_BRANCH_SHA" != "$INTENDED_SHA" ]; then
  echo "ERROR:$TARGET origin/$BRANCH moved to $REMOTE_BRANCH_SHA; intended source is $INTENDED_SHA — refusing checkout/launch" >&2
  exit 75
fi
if git show-ref --verify --quiet "refs/heads/$BRANCH"; then
  LOCAL_BRANCH_SHA=$(git rev-parse "$BRANCH")
  REMOTE_BRANCH_SHA=$(git rev-parse "origin/$BRANCH")
  if ! git merge-base --is-ancestor "$LOCAL_BRANCH_SHA" "$REMOTE_BRANCH_SHA"; then
    echo "ERROR:$TARGET branch is ahead of or diverged from origin/$BRANCH — not overwriting it, resolve manually" >&2
    exit 75
  fi
  git checkout "$BRANCH"
else
  git checkout -b "$BRANCH" "origin/$BRANCH"
fi

if ! git pull --ff-only origin "$BRANCH"; then
  echo "DIVERGED:$TARGET — local $BRANCH has diverged from origin/$BRANCH, resolve manually before continuing" >&2
  exit 1
fi
if [ "$(git rev-parse HEAD)" != "$INTENDED_SHA" ] || [ "$(git rev-parse "origin/$BRANCH")" != "$INTENDED_SHA" ]; then
  echo "ERROR:$TARGET did not converge exactly to origin/$BRANCH — refusing READY" >&2
  exit 75
fi

# tmux has-session prefix-matches by default (checking for "mirror-feat"
# would incorrectly succeed against an existing "mirror-feature-x") — the
# leading "=" forces an exact match.
if tmux has-session -t "=$SESSION" 2>/dev/null; then
  echo "FAILED:$SESSION — session appeared after preflight; refusing to attach or mutate its checkout" >&2
  exit 75
else
  # A bare shell in a checked-out repo is not "continuing the work session"
  # — launch the coding agent as the session's actual command, with
  # $CONTEXT as its argv, instead of `new-session` + a bare shell +
  # `send-keys` typed in after a fixed sleep. tmux execs trailing words
  # directly (no shell re-tokenization), so this also closes the injection
  # window a typed-and-Entered $CONTEXT would open if the CLI weren't at
  # its prompt yet: a `send-keys`-typed string lands in whatever the pane's
  # foreground process is at that moment, so a starting-vs-prompt-not-ready
  # race can dump $CONTEXT straight into an interactive shell and execute
  # it. Passing it as an argv element never touches a shell at all — this
  # only ever fires on a session that didn't already exist (the branch
  # above), so a resumed session never gets a replayed prompt injected on
  # top of work already in progress.
  #
  # `--dangerously-skip-permissions` and `--` are both required. `--`
  # stops `claude` from treating a `$CONTEXT` that happens to start with
  # `-`/`--` as a flag instead of the prompt. `--dangerously-skip-permissions`
  # skips tool-permission prompts, but — confirmed live, 2026-09-18 — it
  # does NOT suppress the first-run workspace-trust dialog for a git
  # repository specifically (it does for a plain non-git directory, which
  # is what made an earlier version of this fix look sufficient before
  # testing against an actual mirrored clone). That dialog's *default*
  # selection is "No, exit"; a bare `claude "$CONTEXT"` on a fresh mirror
  # clone sits there, and the session vanishes the instant anything —
  # including an unrelated Enter — accepts the default and exits `claude`.
  #
  # remain-on-exit is set in the same tmux invocation (not a separate
  # call) so a session that dies immediately — missing `claude` binary,
  # PATH not resolving it under a non-login tmux shell, a crash — leaves a
  # dead-but-inspectable pane instead of vanishing outright.
if [ "$AGENT_CLI" = "claude" ]; then
  tmux new-session -d -s "$SESSION" -c "$TARGET" "${LAUNCH[@]}" \; set-option -t "$SESSION" remain-on-exit on \; set-option -t "$SESSION" @mirror-agent-cli "$AGENT_CLI" \; set-option -t "$SESSION" @mirror-claude-launcher "$CLAUDE_LAUNCHER" 9>&-
else
  tmux new-session -d -s "$SESSION" -c "$TARGET" "${LAUNCH[@]}" \; set-option -t "$SESSION" remain-on-exit on \; set-option -t "$SESSION" @mirror-agent-cli "$AGENT_CLI" 9>&-
fi
  # Poll for the trust dialog and accept it with fixed navigation keys
  # (Down, Enter) — never $CONTEXT — so this carries none of the
  # injection risk the original send-keys-typed-$CONTEXT bug had. This
  # only fires the first time a given target directory is mirrored (the
  # dialog only appears once claude.json records the directory as
  # trusted); a no-op loop on an already-trusted directory is safe.
  # Only Claude Code uses this dialog-acceptance loop; other CLIs use the checks below.
  if [ "$AGENT_CLI" = "claude" ]; then
  for _ in $(seq 1 40); do
    if ! PANE_PROBE=$(tmux capture-pane -p -t "$SESSION" 2>/dev/null); then
      echo "FAILED:$SESSION - cannot capture the pane; refusing to infer a ready state" >&2
      exit 1
    fi
    if printf '%s' "$PANE_PROBE" | grep -qF "Yes, I trust this folder"; then
      # The dialog's text can be captured before its keyboard handler is
      # actually wired up — confirmed live under real load (this box
      # routinely runs 20+ concurrent mirror tmux sessions): a Down sent
      # the instant the text appeared was silently swallowed, and a
      # fixed-delay Enter afterward confirmed the still-focused default
      # "No, exit", killing the session (exit 1). Settle briefly, then
      # verify the cursor actually reached "Yes, I trust this folder"
      # before sending Enter — checking before each Down (not after)
      # means a Down that lands late is never followed by a second one
      # that would toggle the two-item list back to "No, exit".
      sleep 0.2
      for _ in $(seq 1 15); do
        tmux capture-pane -p -t "$SESSION" 2>/dev/null | grep -qE '❯[[:space:]]*Yes, I trust this folder' && break
        tmux send-keys -t "$SESSION" Down || true
        sleep 0.2
      done
      # || true on both send-keys calls: a session that died in the gap
      # since the last capture-pane check would make send-keys fail and,
      # under set -e, silently abort the whole remote script with no
      # FAILED: marker — the same class of gap 58d9db5 closed for
      # capture-pane. Falling through instead lets the existing
      # has-session/pane_dead check report FAILED correctly.
      tmux send-keys -t "$SESSION" Enter || true
      # send-keys returns before claude's render loop processes Enter —
      # confirmed live: the readiness check below ran ~8ms after Enter
      # and still saw the dialog text on screen, reporting a false
      # FAILED on a session that was actually fine one second later.
      # Poll (bounded) until the dialog text actually clears.
      for _ in $(seq 1 10); do
        tmux capture-pane -p -t "$SESSION" 2>/dev/null | grep -qF "Yes, I trust this folder" || break
        sleep 0.2
      done
      break
    fi
    # An already-trusted directory never shows the dialog, so without a
    # positive exit this loop always burns its full budget — confirmed
    # live: an already-trusted launch stalled the caller a flat 20s.
    # claude's status bar ("bypass permissions on") only ever appears
    # once past the dialog (confirmed live: never co-occurs with the
    # dialog text), so treat it as the "no dialog is coming" signal.
    printf '%s' "$PANE_PROBE" | grep -qF "bypass permissions on" && break
    sleep 0.5
  done
  # tmux new-session exits 0 even when the launched command can't be
  # exec'd, and with remain-on-exit set, has-session alone can't tell a
  # genuinely running session from a dead one either — remain-on-exit
  # keeps the session entry around specifically so it doesn't vanish, so
  # has-session still returns success. #{pane_dead} is the actual signal
  # (confirmed live: 1 immediately after an exec failure, 0 while running).
  # A still-showing trust dialog is a third failure mode #{pane_dead} can't
  # catch: claude is alive, just parked on the modal, if the poll above
  # exhausted its window before the dialog rendered (a real risk on a
  # loaded box — /advice round 3 caught this) — re-check for it explicitly
  # rather than trusting silence from the poll loop as acceptance.
  fi
  if [ "$AGENT_CLI" != "claude" ]; then
    if ! tmux has-session -t "=$SESSION" 2>/dev/null \
       || [ "$(tmux display-message -p -t "$SESSION" '#{pane_dead}')" != "0" ]; then
      echo "FAILED:$SESSION:$TARGET — agent exited before the settle check" >&2
      exit 1
    fi
    sleep 0.5
  fi
  if tmux has-session -t "=$SESSION" 2>/dev/null \
     && [ "$(tmux display-message -p -t "$SESSION" '#{pane_dead}')" = "0" ] \
     && { FINAL_PROBE=$(tmux capture-pane -p -t "$SESSION") || {
            echo "FAILED:$SESSION - cannot capture the pane; refusing to report READY" >&2; exit 1; }; } \
     && { [ "$AGENT_CLI" != "claude" ] || ! printf '%s' "$FINAL_PROBE" | grep -qF "Yes, I trust this folder"; }; then
    if [ "$AGENT_CLI" = "pi" ] \
       && printf '%s' "$FINAL_PROBE" | grep -qF "Trust project folder?"; then
      echo "FAILED:$SESSION:$TARGET — pi is waiting at its project-trust prompt; inspect it before reporting READY" >&2
      exit 1
    fi
    echo "READY:$SESSION:$TARGET:$OUTPUT_ROOT:$(git rev-parse HEAD)"
  else
    echo "FAILED:$SESSION:$TARGET — session did not survive launch (check that \`$AGENT_CLI\` is on the remote PATH); pane retained by remain-on-exit for inspection: tmux capture-pane -p -t $SESSION" >&2
    exit 1
  fi
fi
EOF
```

Pi treats each positional argument beginning with `@` as a file attachment, even after `--`. The fixed `Caller handoff context:` prefix keeps caller text as message content. If Pi's `Trust project folder?` prompt is visible after the settle check, leave the pane open and report `FAILED`; do not approve project resources automatically.

Note: `printf` (not `echo`) for the session-name sanitizing is deliberate — piping `echo`'s output through `tr -c '...' '-'` turns the trailing newline into a literal `-`, corrupting the session name.

### 5. Verify execution and print the Linux coder’s receipt

Follow the mandatory [Agent submission and response proof contract](../linux-remote/SKILL.md#agent-submission-and-response-proof--mandatory) for every initial launch and follow-up. `READY` and `RESUMED` establish transport only. An acknowledgment establishes delivery only.

Before reporting `MIRRORED` or that Linux work started, require both:

1. A fresh, attributable **2–3 sentence response written by the Linux CLI coder** for this dispatch. Verify it in the coder's actual pane or transcript. A gateway can relay the coder's response with its source reference.
2. Independent readback of the coder's **first task-specific action** on Linux. Match the dispatch and intended commit to a tool invocation and result in the transcript, a live job started by the coder for the task, or a fresh task artifact produced by the coder. A checkout, handoff file, Git head check performed by the caller, live pane, or queue entry cannot satisfy this gate.

Print the coder's **2–3 sentences verbatim**, with secrets redacted, in the calling terminal and the user-facing response. Label the excerpt with Linux host, coder CLI, session or transcript reference, observation time, and dispatch marker. Include the verified action and its evidence reference alongside it. If the operator requests a one-line report, include the receipt on that same line.

If either proof is missing, report `QUEUED`, `UNCONFIRMED`, or `BLOCKED` with the observed reason. Quote any fresh coder response that exists and explicitly say when no receipt is available. Preserve the session and use bounded monitoring or scoped recovery. Never substitute caller prose for the coder's receipt.

Report the session name, target path, and commit SHA from the `READY:`/`RESUMED:` line — cross-check that SHA against your local `git rev-parse HEAD` before trusting the mirror is on the commit you think it is. `READY` proves the pane passed the launch and liveness checks; it does not prove the agent received or acted on `$CONTEXT`. `RESUMED` means an existing session was found as-is and nothing was typed into it — inspect that work directly rather than assuming it is idle. The preflight rejects local branches that are ahead of or diverged from the fetched remote branch, and the final HEAD is checked for exact equality before READY. Then give the user (or continue as) the attach command:

```bash
ssh -t "${SSH_ARGS[@]}" "$SSH_TARGET" "tmux attach -t <SESSION>"
```

Continue driving the Linux session until the requested outcome or a verified blocker. Execution-start proof covers the first action. Verify completion separately at its source.

### 6. Push discipline while mirrored

The whole point is that the remote copy is a live working branch, not a snapshot — so push from there as work lands, same as any other machine:

```bash
git add -A && git commit -m "..." && git push
```

If a PR is already open for `$BRANCH`, pushes update that PR's head automatically — no extra step. If no PR exists yet, plain `git push` keeps the remote branch current so work isn't stranded on the Linux machine alone.

## Caveats

- Committed-state-only mirror (see "What this carries over" above) — this is the chosen tradeoff over rsyncing the dirty working tree.
- Source repo must live under `$HOME` (see Setup) — step 1 fails loudly rather than silently mirroring to the wrong place. The target-side checkout and agent output land under the target's configured Scratch root; existing `$HOME/mirror` paths are not reused or modified.
- Tool-owned auth, transcripts, and tmux state remain in their normal HOME locations; generated agent output and disposable test files use the Scratch output path reported by `READY`/`RESUMED`.
- Remote Git commands in the step 4 bootstrap run in transient user-systemd scopes under `agents.slice`, with per-command memory, swap, and task limits. The existing finite `agents.slice` `MemoryMax` bounds their aggregate use; bootstrap shell, SSH, tmux, and the launched agent remain outside this Git-only boundary.
- Step 4 launches the calling CLI (`$AGENT_CLI`, resolved in step 1 — `pi`/`claude`/`codex`/`agy`) as the session's command with `$CONTEXT` passed as its argv (not typed via `send-keys`), but only on a freshly created session. Never assume a `RESUMED` session is idle just because this skill didn't launch anything into it.
- A bare host alias is typically LAN-only; off-LAN (traveling), target the Tailscale IP + explicit `-i` per Tier 2 — and make sure step 4 actually uses the resolved `$SSH_ARGS`/`$SSH_TARGET` from step 2, not a re-hardcoded alias, or the whole point of the fallback is lost.
- Never pass unencoded user-controlled values (repo path, branch name, remote URL) as literal SSH command arguments — a branch name is attacker-controllable shell input the moment someone else can push to your fork, and SSH doesn't preserve argv separation across the wire. Base64-encode first (see step 4).
- Tier 3 (messaging-gateway handoff) hands off to a *different* agent/process with no shared context — give it complete, explicit instructions, don't assume it can infer intent from this conversation. Also verify it's genuinely reactive before relying on it (see Tier 3 caveats above) — a live-looking connection isn't proof it's actually processing events, and a missing permission grant is a much likelier culprit than the connection itself.
- If your remote origin URL embeds a credential (HTTPS + PAT), that credential gets written to the target machine's `.git/config` in cleartext the first time this clones there — prefer an SSH remote or an external credential helper.

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in tools →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.