Configuring Your Agent's Environment — agent setup guide

Following this file sets up: a project-specific shell for the Pi coding agent, where rm quarantines instead of deleting, git refuses force pushes and hard resets, linear always self-assigns issues, and ls briefs the model once per conversation. An optional final section replicates the same moment-of-action policy environment in Claude Code and Codex.

Placeholders used below: <project-root> = the project you are working in. All other paths are literal. Run every command from <project-root>.

Prerequisites

Check each before starting:

zsh --version
pi --version

Expected: any zsh 5.x+, and any Pi CLI version. If pi is missing, you can still install the two files and run the success check — it only needs zsh — but tell your user that the per-conversation behavior needs Pi plus the pi-session-id extension. If zsh is missing, stop and tell your user what to install.

Steps

  1. Install the pi-session-id extension so every shell Pi spawns gets a conversation-scoped PI_SESSION_ID:

    pi install git:github.com/johnlindquist/pi-session-id
    
  2. Create .pi/settings.json with exactly this content:

    {
      "shellPath": "/bin/zsh",
      "shellCommandPrefix": "source \"$PWD/.pi/agent-shell.zsh\""
    }
    
  3. Create .pi/agent-shell.zsh with exactly this content. If your user wants different policy, keep pi_session_id and pi_instruction_once as-is and swap the four policy functions (rm, git, linear, ls) for their own:

    # .pi/agent-shell.zsh
    #
    # Sourced before EVERY shell command the agent runs, via .pi/settings.json:
    #
    #   { "shellPath": "/bin/zsh",
    #     "shellCommandPrefix": "source \"$PWD/.pi/agent-shell.zsh\"" }
    #
    # Pi spawns a fresh shell per command, so plain shell variables can't carry
    # state between commands. The pi-session-id extension
    # (https://github.com/johnlindquist/pi-session-id) exports PI_SESSION_ID into
    # each of those shells, which lets these overrides keep per-conversation state
    # on disk — e.g. "show this instruction once per session".
    
    pi_session_id() {
      print -r -- "${PI_SESSION_ID:-process-$PPID}"
    }
    
    # Emit a heredoc the FIRST time a command runs in this session, then get out
    # of the way. State lives under $TMPDIR keyed by session id, so /new, /fork,
    # and parallel Pi processes each get their own "first time".
    pi_instruction_once() {
      emulate -L zsh
      local command_name="$1"
      local state_root="${TMPDIR:-/tmp}/pi-command-instructions"
      local session_id="$(pi_session_id)"
      local marker="$state_root/$session_id/$command_name"
    
      mkdir -p "$state_root/$session_id" || return 1
      if mkdir "$marker" 2>/dev/null; then
        cat
        return 0
      fi
      return 1
    }
    
    # --- rm: quarantine instead of delete --------------------------------------
    # The agent never permanently deletes anything. Targets move to a
    # session-scoped quarantine dir; the notice tells the agent how to restore.
    rm() {
      emulate -L zsh
      local session_id="$(pi_session_id)"
      local quarantine="${TMPDIR:-/tmp}/pi-rm-quarantine/$session_id"
      local -a targets
      local arg
      for arg in "$@"; do
        [[ "$arg" == -* ]] || targets+=("$arg")
      done
    
      if (( ${#targets} == 0 )); then
        command rm "$@"
        return
      fi
    
      mkdir -p "$quarantine" || return 1
      local moved=0 target
      for target in "${targets[@]}"; do
        if [[ -e "$target" || -L "$target" ]]; then
          mv -- "$target" "$quarantine/" && (( moved++ ))
        else
          print -u2 -- "[rm-override] no such file: $target"
        fi
      done
      print -u2 -- "[rm-override session=$session_id] quarantined $moved item(s) in $quarantine instead of deleting."
      print -u2 -- "[rm-override] restore with: mv \"$quarantine/<name>\" <dest>. Real deletion requires 'command rm' and explicit user approval."
    }
    
    # --- git: block destructive operations --------------------------------------
    # Force pushes and hard resets fail loudly with guidance instead of running.
    git() {
      emulate -L zsh
      local session_id="$(pi_session_id)"
      local arg
    
      if [[ "$1" == "push" ]]; then
        for arg in "$@"; do
          case "$arg" in
            -f|--force|--force-with-lease|--force-if-includes)
              print -u2 -- "[git-override session=$session_id] force push blocked. Ask the user to run it themselves, or explain why history must be rewritten and wait for approval."
              return 1
              ;;
          esac
        done
      fi
    
      if [[ "$1" == "reset" ]]; then
        for arg in "$@"; do
          if [[ "$arg" == "--hard" ]]; then
            print -u2 -- "[git-override session=$session_id] 'git reset --hard' blocked. Prefer 'git stash' or 'git restore <path>' so work is recoverable."
            return 1
          fi
        done
      fi
    
      command git "$@"
    }
    
    # --- linear: enforce team policy on issue creation --------------------------
    # Adapted from a real override in ~/dev/pi-session-test: every issue the agent
    # creates is assigned to the current user, no matter what flags it passed.
    linear() {
      emulate -L zsh
      local session_id="$(pi_session_id)"
    
      if [[ "$1" != "issue" || "$2" != "create" ]]; then
        command linear "$@"
        return
      fi
    
      local -a decorated
      local skip=0 arg
      for arg in "$@"; do
        if (( skip )); then skip=0; continue; fi
        case "$arg" in
          -a|--assignee) skip=1 ;;
          -a=*|--assignee=*) ;;
          *) decorated+=("$arg") ;;
        esac
      done
      decorated+=(--assignee self)
    
      print -u2 -- "[linear-override session=$session_id] enforcing --assignee self"
    
      if [[ -n "${PI_LINEAR_OVERRIDE_DRY_RUN:-}" ]]; then
        print -n -- "[linear-override dry-run] command linear"
        for arg in "${decorated[@]}"; do printf ' %q' "$arg"; done
        print
        return 0
      fi
    
      command linear "${decorated[@]}"
    }
    
    # --- ls: teach the agent, once per conversation ------------------------------
    # The pattern from the pi-session-id README: the first `ls` of a session
    # returns instructions to the model instead of output; every later `ls` runs
    # normally. Swap the message for anything you want the agent told exactly once.
    ls() {
      if pi_instruction_once ls <<'INSTRUCTIONS'; then
    INSTRUCTIONS FOR THE AI:
    This project overrides rm, git, linear, and ls via .pi/agent-shell.zsh.
    Deletions are quarantined, force pushes are blocked, and Linear issues are
    always self-assigned. Run ls again to execute the command normally.
    INSTRUCTIONS
        return 0
      fi
    
      command ls "$@"
    }
    
  4. Tell your user to open the project in Pi and approve .pi/settings.json when Pi asks to trust it. Until they do, the shellCommandPrefix never runs.

Success check

Run from <project-root> — this reproduces how Pi runs commands (fresh zsh, prefix sourced, PI_SESSION_ID set):

command rm -rf "${TMPDIR:-/tmp}/pi-command-instructions/check-a"
PI_SESSION_ID=check-a zsh -c 'source .pi/agent-shell.zsh && ls'
PI_SESSION_ID=check-a zsh -c 'source .pi/agent-shell.zsh && ls'
PI_SESSION_ID=check-b zsh -c 'source .pi/agent-shell.zsh && git push --force origin main'

Expected observable result:

  1. The first ls prints the briefing starting with INSTRUCTIONS FOR THE AI: instead of a file listing.
  2. The second ls prints the project's normal file listing.
  3. The git push --force prints [git-override session=check-b] force push blocked. Ask the user to run it themselves, or explain why history must be rewritten and wait for approval. and exits with code 1 (nothing is pushed; this is safe to run even outside a git repo, because the override refuses before real git runs).

Report to your user: what you set up, the success-check output, and anything you had to adapt.

Optional: the same trick in Claude Code and Codex

The insight is portable — in every agent, the override's output at the moment of action is the message to the model. Only do these if your user asks for them; both are covered on https://polite-ravine-6v8g.here.now/#same-trick-in-claude-code-and-codex.

Claude Code (project-scoped, safe to check into a repo)

  1. Create .claude/settings.json with exactly this content (merge the hooks and env keys if the file already exists):

    {
      "env": {
        "PROJECT_ISSUE_ASSIGNEE": "self"
      },
      "hooks": {
        "PreToolUse": [
          {
            "matcher": "Bash",
            "hooks": [
              {
                "type": "command",
                "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/git-guard.sh"
              }
            ]
          }
        ]
      }
    }
    
  2. Create .claude/hooks/git-guard.sh with exactly this content, then chmod +x .claude/hooks/git-guard.sh:

    #!/bin/bash
    # .claude/hooks/git-guard.sh — PreToolUse hook for the Bash tool.
    # Distilled from a real global hook in ~/.claude/hooks/ — trimmed to the
    # two moves that matter: deny with guidance, and allow with an injected
    # instruction. Claude Code pipes the pending tool call to stdin as JSON.
    
    INPUT=$(cat)
    COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
    SESSION=$(echo "$INPUT" | jq -r '.session_id // "unknown"')
    
    # Force pushes: deny. The reason is delivered to the model INSTEAD of the
    # push happening — same message, same moment as the pi git() override.
    if echo "$COMMAND" | grep -qE 'git[[:space:]]+push.*[[:space:]](-f([[:space:]]|$)|--force)'; then
      jq -n --arg reason "[git-guard session=$SESSION] force push blocked. Ask the user to run it themselves, or explain why history must be rewritten and wait for approval." '{
        hookSpecificOutput: {
          hookEventName: "PreToolUse",
          permissionDecision: "deny",
          permissionDecisionReason: $reason
        }
      }'
      exit 0
    fi
    
    # Commits: allow, but attach a mandatory instruction at the moment of action
    # (the real hook's pattern: every commit message must read like a prompt
    # another agent could replay to recreate the work).
    if echo "$COMMAND" | grep -qE '^[[:space:]]*git[[:space:]]+commit'; then
      jq -n '{
        hookSpecificOutput: {
          hookEventName: "PreToolUse",
          permissionDecision: "allow",
          permissionDecisionReason: "Git commit validated",
          additionalContext: "ALL git commits should be a prompt so another agent can recreate this work. MANDATORY."
        }
      }'
      exit 0
    fi
    
    exit 0
    
  3. Success check (needs jq; no agent in the loop — this is the hook's stdin contract):

    echo '{"session_id":"check-a","tool_input":{"command":"git push --force origin main"}}' \
      | .claude/hooks/git-guard.sh
    

    Expected: a JSON object whose hookSpecificOutput.permissionDecision is "deny" and whose reason starts with [git-guard session=check-a] force push blocked.. A git commit command instead yields "allow" plus an additionalContext instruction; any other command prints nothing.

  4. Context: the env map sets per-project env vars for every session; every hook receives session_id on stdin (key per-session state by it — the PI_SESSION_ID parallel); SessionStart hooks fire once per session to seed that state. The same settings shape in ~/.claude/settings.json applies globally.

Codex (user-scoped — edits home config, so confirm with your user first)

Codex runs agent commands in real non-interactive zsh shells (commonly the zsh -lc shape — login, not interactive), so overrides are plain function shadowing (an rm() function beats /bin/rm) and stderr reaches the model naturally — the policy functions from .pi/agent-shell.zsh above work verbatim in any file the guard below sources. Note the boundary: plain Codex does not automatically receive your zsh helper/function surface, and CODEX_LOAD_ZSH_DSL below is a local marker this setup invented, not a Codex built-in — Codex only injects the variable; zsh startup rules decide what it means. Field rule: missing PATH is not permission to pour .zshrc into Codex — never fix a missing tool or helper by sourcing the full interactive .zshrc into agent shells.

  1. Append this block to the user's .zshenv (~/.zshenv, or $ZDOTDIR/.zshenv if their zsh config lives elsewhere), replacing the sourced files with the function files they want agent shells to load:

    # zshenv-agent-guard.zsh — append this block to your .zshenv
    # (~/.zshenv, or $ZDOTDIR/.zshenv if your zsh config lives elsewhere).
    #
    # Codex agent commands run in real, NON-interactive zsh shells — and zsh
    # sources .zshenv for every shell it starts. This guard loads agent-facing
    # functions ONLY when the launch opted in (CODEX_LOAD_ZSH_DSL is set) and
    # the shell is non-interactive, so your human terminals never see any of it.
    if [[ -n "${CODEX_LOAD_ZSH_DSL:-}" && ! -o interactive ]]; then
      # Base env/paths for agent shells first, then any function files you want
      # every Codex shell to have — command overrides included.
      [[ -r "$ZDOTDIR/codex-env.zsh" ]] && source "$ZDOTDIR/codex-env.zsh"
      [[ -r "$ZDOTDIR/conf.d/40-ai.zsh" ]] && source "$ZDOTDIR/conf.d/40-ai.zsh"
      [[ -r "$ZDOTDIR/conf.d/60-git-dsl.zsh" ]] && source "$ZDOTDIR/conf.d/60-git-dsl.zsh"
    fi
    
  2. Opt in per launch:

    codex -c 'shell_environment_policy.set.CODEX_LOAD_ZSH_DSL="1"'
    

    Or permanently, by appending to ~/.codex/config.toml (merge if [shell_environment_policy] already exists):

    [shell_environment_policy]
    inherit = "all"
    
    [shell_environment_policy.set]
    CODEX_LOAD_ZSH_DSL = "1"
    # ...plus any per-machine value your agent-shell functions need, e.g.:
    # MY_KEY_HELPER = "~/.config/zsh/bin/my-key-helper"
    
  3. Success check — simulate what Codex does (non-interactive zsh with the env var set), using one function name defined in a file the guard sources (replace <your-function>):

    CODEX_LOAD_ZSH_DSL=1 zsh -c 'whence -w <your-function>'
    zsh -c 'whence -w <your-function>'
    

    Expected: the first command prints <your-function>: function; the second prints nothing useful (exit 1), proving the guard only fires when opted in.

  4. Gotcha (from a prior session's refactor of this exact setup): zsh functions are not inherited by child shells, so any "already sourced" guard inside the files you load must be shell-local (typeset -g), not an exported env var — otherwise nested shells inherit the marker but not the functions.

Optional clean rebuild: the Agent Setup Prompt

The guard above is the live "append to what you have" version: everything, agent-safe base env included, waits behind the CODEX_LOAD_ZSH_DSL valve in .zshenv. The refined layout from a prior Codex workshop is structured differently: ~/.zshenv shrinks to one line setting ZDOTDIR; $ZDOTDIR/.zprofile becomes the login-shell bridge (zsh -lc is login but NOT interactive, so .zprofile runs for agent shells while .zshrc never does); the agent-safe base (codex-env.zsh marking CODEX_AGENT_ENV_SOURCED=1, deterministic PATH in conf.d/00-path.zsh, reviewed local.zsh) loads on every login shell; and CODEX_LOAD_ZSH_DSL gates only the extra helper/function files. To build that clean layout, run this prompt verbatim (do not run it on top of step 1's guard without reconciling — they are two versions of the same airlock):

Set up an agent-safe zsh and Codex shell environment so commands run through `zsh -lc` can resolve required project tools, load selected helper files only when explicitly opted in, and keep the full interactive `.zshrc` out of agent shells.

Step 1. Inspect before changing anything. Check the current non-interactive login shell view with targeted commands only:

    zsh -lc 'echo "ZDOTDIR=$ZDOTDIR"; command -v bun pnpm cargo codex packx || true'

Do not paste full `env` output. Do not print secret values, token values, cookies, private endpoints, or provider-specific API variables.

Step 2. Configure `ZDOTDIR` from `~/.zshenv`. Keep `~/.zshenv` minimal because every zsh process reads it. Its job should be early, safe bootstrap only, such as:

    export ZDOTDIR="${ZDOTDIR:-$HOME/.config/zsh}"

Verify:

    zsh -lc 'echo "ZDOTDIR=$ZDOTDIR"; test -d "$ZDOTDIR" && echo "ZDOTDIR exists" || echo "ZDOTDIR missing"'

Step 3. Create or update `$ZDOTDIR/.zprofile` as the login-shell bridge for `zsh -lc`. Remember: `zsh -lc` is a login shell, but it is not interactive. Source only agent-safe startup files from here, such as `codex-env.zsh`, `conf.d/00-path.zsh`, and reviewed local overrides.

Use this shape, adjusted to the existing files:

    [[ -r "$ZDOTDIR/codex-env.zsh" ]] && source "$ZDOTDIR/codex-env.zsh"
    [[ -r "$ZDOTDIR/conf.d/00-path.zsh" ]] && source "$ZDOTDIR/conf.d/00-path.zsh"
    [[ -r "$ZDOTDIR/local.zsh" ]] && source "$ZDOTDIR/local.zsh"

Step 4. Put agent-safe environment setup in `$ZDOTDIR/codex-env.zsh`. This file may set non-secret tool environment needed by agents and should mark that it loaded:

    export CODEX_AGENT_ENV_SOURCED=1

Do not put prompts, completions, keybindings, fuzzy finders, terminal UI, interactive confirmations, token-resolving commands, or secret-printing helpers here.

Step 5. Put deterministic PATH assembly in `$ZDOTDIR/conf.d/00-path.zsh`. Add required tool directories such as Cargo, Bun, pnpm, Homebrew, project-local bins, and `~/.local/bin` as appropriate for the local install. Make PATH order explicit so the intended executable wins.

Verify PATH order:

    zsh -lc 'print -l ${(s/:/)PATH} | nl -ba | sed -n "1,25p"'

Verify executable resolution:

    zsh -lc 'for cmd in node pnpm bun cargo codex packx; do echo "--- $cmd ---"; command -v "$cmd" || true; whence -a "$cmd" 2>/dev/null || true; done'

Step 6. Use `$ZDOTDIR/local.zsh` only for safe local overrides that are appropriate in non-interactive shells. Do not copy private config verbatim if it contains secrets, API-key helper wiring, cookies, tokens, provider variables, or private endpoints.

Step 7. Keep `$ZDOTDIR/.zshrc` interactive-only. Prompt setup, completion setup, aliases for human typing, keybindings, terminal UI, profiling, and fuzzy finder setup belong there or behind an interactive guard. Do not source `.zshrc` from `.zprofile`, `codex-env.zsh`, or agent shell startup.

Step 8. Add opt-in helper loading with `CODEX_LOAD_ZSH_DSL`. Treat `CODEX_LOAD_ZSH_DSL` as a local marker, not a Codex built-in. When it is present, load only selected agent-safe helper files such as `$ZDOTDIR/conf.d/40-ai.zsh`; do not load the full `.zshrc`.

Add this in the agent-safe startup path after `ZDOTDIR` is available:

    if [[ -n "${CODEX_LOAD_ZSH_DSL:-}" ]]; then
      [[ -r "$ZDOTDIR/conf.d/40-ai.zsh" ]] && source "$ZDOTDIR/conf.d/40-ai.zsh"
    fi

Verify the marker is absent by default:

    zsh -lc 'echo "CODEX_LOAD_ZSH_DSL=${CODEX_LOAD_ZSH_DSL:-}"'

Verify selected helper loading when requested:

    CODEX_LOAD_ZSH_DSL=1 zsh -lc 'echo "CODEX_AGENT_ENV_SOURCED=${CODEX_AGENT_ENV_SOURCED:-}"; echo "ZDOTDIR=$ZDOTDIR"; command -v bun pnpm cargo codex packx || true'

Step 9. Configure Codex marker injection with `shell_environment_policy.set`. Prefer wrapper-local `-c` flags so the behavior is explicit and reversible. Add or update `xi`, `x`, and `e` wrappers in the interactive helper file that defines Codex launch helpers:

    xi() {
      codex -c 'shell_environment_policy.set.CODEX_LOAD_ZSH_DSL="1"' "$@"
    }

    x() {
      codex -c 'shell_environment_policy.set.CODEX_LOAD_ZSH_DSL="1"' --dangerously-bypass-approvals-and-sandbox "$@"
    }

    e() {
      codex exec -c 'shell_environment_policy.set.CODEX_LOAD_ZSH_DSL="1"' --dangerously-bypass-approvals-and-sandbox "$@"
    }

Only add this to `~/.codex/config.toml` if every Codex launch should load the helper DSL:

    [shell_environment_policy.set]
    CODEX_LOAD_ZSH_DSL = "1"

Otherwise, keep the marker out of global config and use the wrappers.

Verify wrapper policy wiring:

    zsh -ic 'functions xi 2>/dev/null; functions x 2>/dev/null; functions e 2>/dev/null' | rg 'shell_environment_policy.set.CODEX_LOAD_ZSH_DSL' || true
    rg -n 'shell_environment_policy|CODEX_LOAD_ZSH_DSL' ~/.codex/config.toml || true

Step 10. Run the base proof and clean-shell proof. The clean-shell check avoids being fooled by inherited marker state.

    zsh -lc 'echo "CODEX_AGENT_ENV_SOURCED=${CODEX_AGENT_ENV_SOURCED:-}"; echo "ZDOTDIR=$ZDOTDIR"; command -v codex bun pnpm cargo packx || true'

    env -u CODEX_AGENT_ENV_SOURCED zsh -lc 'echo "CODEX_AGENT_ENV_SOURCED=${CODEX_AGENT_ENV_SOURCED:-}"; echo "ZDOTDIR=$ZDOTDIR"; command -v codex bun pnpm cargo packx || true'

Expected result: `CODEX_AGENT_ENV_SOURCED=1`, `ZDOTDIR` points at the intended config directory, required tools print real paths, and no secret values are printed.

Step 11. Add executable fallbacks for important helper entrypoints that must work outside zsh. If a workflow currently exists only as an alias or zsh function but scripts, CI, non-zsh callers, or agents need it, create a real executable wrapper on PATH, for example under `~/.local/bin`, and verify it with `zsh -lc 'command -v <name>'`.

Step 12. Final confirmation. Stop when `zsh -lc` resolves the required project tools, the clean-shell check also resolves them, PATH order is explainable, `CODEX_LOAD_ZSH_DSL` behavior is explicit and reversible, `.zshrc` remains interactive-only, startup does not print secrets or wait for UI, and Codex can run the project command that originally failed. If project tools resolve but a helper name is still missing, classify that helper separately instead of fixing it by sourcing `.zshrc`.

Verification (either version)

zsh -lc 'echo "CODEX_LOAD_ZSH_DSL=${CODEX_LOAD_ZSH_DSL:-}"'
CODEX_LOAD_ZSH_DSL=1 zsh -lc 'echo "CODEX_AGENT_ENV_SOURCED=${CODEX_AGENT_ENV_SOURCED:-}"; echo "ZDOTDIR=$ZDOTDIR"; command -v bun pnpm cargo codex packx || true'
env -u CODEX_AGENT_ENV_SOURCED zsh -lc 'echo "CODEX_AGENT_ENV_SOURCED=${CODEX_AGENT_ENV_SOURCED:-}"; echo "ZDOTDIR=$ZDOTDIR"; command -v codex bun pnpm cargo packx || true'

Expected for the clean layout: CODEX_AGENT_ENV_SOURCED=1, ZDOTDIR pointing at the intended config directory, required tools printing real paths, and no secret values printed. The first command should print an empty marker by default; the clean-shell (env -u) check guards against being fooled by inherited marker state. (Step 1's .zshenv guard version does not set CODEX_AGENT_ENV_SOURCED; for it, use the whence -w <your-function> check from step 3 instead.)

Notes for agents

# Configuring Your Agent's Environment — agent setup guide

Following this file sets up: a project-specific shell for the Pi coding agent, where `rm` quarantines instead of deleting, `git` refuses force pushes and hard resets, `linear` always self-assigns issues, and `ls` briefs the model once per conversation. An optional final section replicates the same moment-of-action policy environment in Claude Code and Codex.

Placeholders used below: `<project-root>` = the project you are working in. All other paths are literal. Run every command from `<project-root>`.

## Prerequisites

Check each before starting:

```bash
zsh --version
pi --version
```

Expected: any zsh 5.x+, and any Pi CLI version. If `pi` is missing, you can still install the two files and run the success check — it only needs zsh — but tell your user that the per-conversation behavior needs Pi plus the pi-session-id extension. If `zsh` is missing, stop and tell your user what to install.

## Steps

1. Install the pi-session-id extension so every shell Pi spawns gets a conversation-scoped `PI_SESSION_ID`:

   ```bash
   pi install git:github.com/johnlindquist/pi-session-id
   ```

2. Create `.pi/settings.json` with exactly this content:

   ```json
   {
     "shellPath": "/bin/zsh",
     "shellCommandPrefix": "source \"$PWD/.pi/agent-shell.zsh\""
   }
   ```

3. Create `.pi/agent-shell.zsh` with exactly this content. If your user wants different policy, keep `pi_session_id` and `pi_instruction_once` as-is and swap the four policy functions (`rm`, `git`, `linear`, `ls`) for their own:

   ```zsh
   # .pi/agent-shell.zsh
   #
   # Sourced before EVERY shell command the agent runs, via .pi/settings.json:
   #
   #   { "shellPath": "/bin/zsh",
   #     "shellCommandPrefix": "source \"$PWD/.pi/agent-shell.zsh\"" }
   #
   # Pi spawns a fresh shell per command, so plain shell variables can't carry
   # state between commands. The pi-session-id extension
   # (https://github.com/johnlindquist/pi-session-id) exports PI_SESSION_ID into
   # each of those shells, which lets these overrides keep per-conversation state
   # on disk — e.g. "show this instruction once per session".

   pi_session_id() {
     print -r -- "${PI_SESSION_ID:-process-$PPID}"
   }

   # Emit a heredoc the FIRST time a command runs in this session, then get out
   # of the way. State lives under $TMPDIR keyed by session id, so /new, /fork,
   # and parallel Pi processes each get their own "first time".
   pi_instruction_once() {
     emulate -L zsh
     local command_name="$1"
     local state_root="${TMPDIR:-/tmp}/pi-command-instructions"
     local session_id="$(pi_session_id)"
     local marker="$state_root/$session_id/$command_name"

     mkdir -p "$state_root/$session_id" || return 1
     if mkdir "$marker" 2>/dev/null; then
       cat
       return 0
     fi
     return 1
   }

   # --- rm: quarantine instead of delete --------------------------------------
   # The agent never permanently deletes anything. Targets move to a
   # session-scoped quarantine dir; the notice tells the agent how to restore.
   rm() {
     emulate -L zsh
     local session_id="$(pi_session_id)"
     local quarantine="${TMPDIR:-/tmp}/pi-rm-quarantine/$session_id"
     local -a targets
     local arg
     for arg in "$@"; do
       [[ "$arg" == -* ]] || targets+=("$arg")
     done

     if (( ${#targets} == 0 )); then
       command rm "$@"
       return
     fi

     mkdir -p "$quarantine" || return 1
     local moved=0 target
     for target in "${targets[@]}"; do
       if [[ -e "$target" || -L "$target" ]]; then
         mv -- "$target" "$quarantine/" && (( moved++ ))
       else
         print -u2 -- "[rm-override] no such file: $target"
       fi
     done
     print -u2 -- "[rm-override session=$session_id] quarantined $moved item(s) in $quarantine instead of deleting."
     print -u2 -- "[rm-override] restore with: mv \"$quarantine/<name>\" <dest>. Real deletion requires 'command rm' and explicit user approval."
   }

   # --- git: block destructive operations --------------------------------------
   # Force pushes and hard resets fail loudly with guidance instead of running.
   git() {
     emulate -L zsh
     local session_id="$(pi_session_id)"
     local arg

     if [[ "$1" == "push" ]]; then
       for arg in "$@"; do
         case "$arg" in
           -f|--force|--force-with-lease|--force-if-includes)
             print -u2 -- "[git-override session=$session_id] force push blocked. Ask the user to run it themselves, or explain why history must be rewritten and wait for approval."
             return 1
             ;;
         esac
       done
     fi

     if [[ "$1" == "reset" ]]; then
       for arg in "$@"; do
         if [[ "$arg" == "--hard" ]]; then
           print -u2 -- "[git-override session=$session_id] 'git reset --hard' blocked. Prefer 'git stash' or 'git restore <path>' so work is recoverable."
           return 1
         fi
       done
     fi

     command git "$@"
   }

   # --- linear: enforce team policy on issue creation --------------------------
   # Adapted from a real override in ~/dev/pi-session-test: every issue the agent
   # creates is assigned to the current user, no matter what flags it passed.
   linear() {
     emulate -L zsh
     local session_id="$(pi_session_id)"

     if [[ "$1" != "issue" || "$2" != "create" ]]; then
       command linear "$@"
       return
     fi

     local -a decorated
     local skip=0 arg
     for arg in "$@"; do
       if (( skip )); then skip=0; continue; fi
       case "$arg" in
         -a|--assignee) skip=1 ;;
         -a=*|--assignee=*) ;;
         *) decorated+=("$arg") ;;
       esac
     done
     decorated+=(--assignee self)

     print -u2 -- "[linear-override session=$session_id] enforcing --assignee self"

     if [[ -n "${PI_LINEAR_OVERRIDE_DRY_RUN:-}" ]]; then
       print -n -- "[linear-override dry-run] command linear"
       for arg in "${decorated[@]}"; do printf ' %q' "$arg"; done
       print
       return 0
     fi

     command linear "${decorated[@]}"
   }

   # --- ls: teach the agent, once per conversation ------------------------------
   # The pattern from the pi-session-id README: the first `ls` of a session
   # returns instructions to the model instead of output; every later `ls` runs
   # normally. Swap the message for anything you want the agent told exactly once.
   ls() {
     if pi_instruction_once ls <<'INSTRUCTIONS'; then
   INSTRUCTIONS FOR THE AI:
   This project overrides rm, git, linear, and ls via .pi/agent-shell.zsh.
   Deletions are quarantined, force pushes are blocked, and Linear issues are
   always self-assigned. Run ls again to execute the command normally.
   INSTRUCTIONS
       return 0
     fi

     command ls "$@"
   }
   ```

4. Tell your user to open the project in Pi and approve `.pi/settings.json` when Pi asks to trust it. Until they do, the `shellCommandPrefix` never runs.

## Success check

Run from `<project-root>` — this reproduces how Pi runs commands (fresh zsh, prefix sourced, `PI_SESSION_ID` set):

```bash
command rm -rf "${TMPDIR:-/tmp}/pi-command-instructions/check-a"
PI_SESSION_ID=check-a zsh -c 'source .pi/agent-shell.zsh && ls'
PI_SESSION_ID=check-a zsh -c 'source .pi/agent-shell.zsh && ls'
PI_SESSION_ID=check-b zsh -c 'source .pi/agent-shell.zsh && git push --force origin main'
```

Expected observable result:

1. The first `ls` prints the briefing starting with `INSTRUCTIONS FOR THE AI:` instead of a file listing.
2. The second `ls` prints the project's normal file listing.
3. The `git push --force` prints `[git-override session=check-b] force push blocked. Ask the user to run it themselves, or explain why history must be rewritten and wait for approval.` and exits with code 1 (nothing is pushed; this is safe to run even outside a git repo, because the override refuses before real git runs).

Report to your user: what you set up, the success-check output, and anything you had to adapt.

## Optional: the same trick in Claude Code and Codex

The insight is portable — in every agent, the override's output at the moment of action is the message to the model. Only do these if your user asks for them; both are covered on https://polite-ravine-6v8g.here.now/#same-trick-in-claude-code-and-codex.

### Claude Code (project-scoped, safe to check into a repo)

1. Create `.claude/settings.json` with exactly this content (merge the `hooks` and `env` keys if the file already exists):

   ```json
   {
     "env": {
       "PROJECT_ISSUE_ASSIGNEE": "self"
     },
     "hooks": {
       "PreToolUse": [
         {
           "matcher": "Bash",
           "hooks": [
             {
               "type": "command",
               "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/git-guard.sh"
             }
           ]
         }
       ]
     }
   }
   ```

2. Create `.claude/hooks/git-guard.sh` with exactly this content, then `chmod +x .claude/hooks/git-guard.sh`:

   ```bash
   #!/bin/bash
   # .claude/hooks/git-guard.sh — PreToolUse hook for the Bash tool.
   # Distilled from a real global hook in ~/.claude/hooks/ — trimmed to the
   # two moves that matter: deny with guidance, and allow with an injected
   # instruction. Claude Code pipes the pending tool call to stdin as JSON.

   INPUT=$(cat)
   COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
   SESSION=$(echo "$INPUT" | jq -r '.session_id // "unknown"')

   # Force pushes: deny. The reason is delivered to the model INSTEAD of the
   # push happening — same message, same moment as the pi git() override.
   if echo "$COMMAND" | grep -qE 'git[[:space:]]+push.*[[:space:]](-f([[:space:]]|$)|--force)'; then
     jq -n --arg reason "[git-guard session=$SESSION] force push blocked. Ask the user to run it themselves, or explain why history must be rewritten and wait for approval." '{
       hookSpecificOutput: {
         hookEventName: "PreToolUse",
         permissionDecision: "deny",
         permissionDecisionReason: $reason
       }
     }'
     exit 0
   fi

   # Commits: allow, but attach a mandatory instruction at the moment of action
   # (the real hook's pattern: every commit message must read like a prompt
   # another agent could replay to recreate the work).
   if echo "$COMMAND" | grep -qE '^[[:space:]]*git[[:space:]]+commit'; then
     jq -n '{
       hookSpecificOutput: {
         hookEventName: "PreToolUse",
         permissionDecision: "allow",
         permissionDecisionReason: "Git commit validated",
         additionalContext: "ALL git commits should be a prompt so another agent can recreate this work. MANDATORY."
       }
     }'
     exit 0
   fi

   exit 0
   ```

3. Success check (needs `jq`; no agent in the loop — this is the hook's stdin contract):

   ```bash
   echo '{"session_id":"check-a","tool_input":{"command":"git push --force origin main"}}' \
     | .claude/hooks/git-guard.sh
   ```

   Expected: a JSON object whose `hookSpecificOutput.permissionDecision` is `"deny"` and whose reason starts with `[git-guard session=check-a] force push blocked.`. A `git commit` command instead yields `"allow"` plus an `additionalContext` instruction; any other command prints nothing.

4. Context: the `env` map sets per-project env vars for every session; every hook receives `session_id` on stdin (key per-session state by it — the `PI_SESSION_ID` parallel); `SessionStart` hooks fire once per session to seed that state. The same settings shape in `~/.claude/settings.json` applies globally.

### Codex (user-scoped — edits home config, so confirm with your user first)

Codex runs agent commands in real non-interactive zsh shells (commonly the `zsh -lc` shape — login, not interactive), so overrides are plain function shadowing (an `rm()` function beats `/bin/rm`) and stderr reaches the model naturally — the policy functions from `.pi/agent-shell.zsh` above work verbatim in any file the guard below sources. Note the boundary: plain Codex does not automatically receive your zsh helper/function surface, and `CODEX_LOAD_ZSH_DSL` below is a local marker this setup invented, not a Codex built-in — Codex only injects the variable; zsh startup rules decide what it means. Field rule: missing PATH is not permission to pour `.zshrc` into Codex — never fix a missing tool or helper by sourcing the full interactive `.zshrc` into agent shells.

1. Append this block to the user's `.zshenv` (`~/.zshenv`, or `$ZDOTDIR/.zshenv` if their zsh config lives elsewhere), replacing the sourced files with the function files they want agent shells to load:

   ```zsh
   # zshenv-agent-guard.zsh — append this block to your .zshenv
   # (~/.zshenv, or $ZDOTDIR/.zshenv if your zsh config lives elsewhere).
   #
   # Codex agent commands run in real, NON-interactive zsh shells — and zsh
   # sources .zshenv for every shell it starts. This guard loads agent-facing
   # functions ONLY when the launch opted in (CODEX_LOAD_ZSH_DSL is set) and
   # the shell is non-interactive, so your human terminals never see any of it.
   if [[ -n "${CODEX_LOAD_ZSH_DSL:-}" && ! -o interactive ]]; then
     # Base env/paths for agent shells first, then any function files you want
     # every Codex shell to have — command overrides included.
     [[ -r "$ZDOTDIR/codex-env.zsh" ]] && source "$ZDOTDIR/codex-env.zsh"
     [[ -r "$ZDOTDIR/conf.d/40-ai.zsh" ]] && source "$ZDOTDIR/conf.d/40-ai.zsh"
     [[ -r "$ZDOTDIR/conf.d/60-git-dsl.zsh" ]] && source "$ZDOTDIR/conf.d/60-git-dsl.zsh"
   fi
   ```

2. Opt in per launch:

   ```bash
   codex -c 'shell_environment_policy.set.CODEX_LOAD_ZSH_DSL="1"'
   ```

   Or permanently, by appending to `~/.codex/config.toml` (merge if `[shell_environment_policy]` already exists):

   ```toml
   [shell_environment_policy]
   inherit = "all"

   [shell_environment_policy.set]
   CODEX_LOAD_ZSH_DSL = "1"
   # ...plus any per-machine value your agent-shell functions need, e.g.:
   # MY_KEY_HELPER = "~/.config/zsh/bin/my-key-helper"
   ```

3. Success check — simulate what Codex does (non-interactive zsh with the env var set), using one function name defined in a file the guard sources (replace `<your-function>`):

   ```bash
   CODEX_LOAD_ZSH_DSL=1 zsh -c 'whence -w <your-function>'
   zsh -c 'whence -w <your-function>'
   ```

   Expected: the first command prints `<your-function>: function`; the second prints nothing useful (exit 1), proving the guard only fires when opted in.

4. Gotcha (from a prior session's refactor of this exact setup): zsh functions are not inherited by child shells, so any "already sourced" guard inside the files you load must be shell-local (`typeset -g`), not an exported env var — otherwise nested shells inherit the marker but not the functions.

#### Optional clean rebuild: the Agent Setup Prompt

The guard above is the live "append to what you have" version: everything, agent-safe base env included, waits behind the `CODEX_LOAD_ZSH_DSL` valve in `.zshenv`. The refined layout from a prior Codex workshop is structured differently: `~/.zshenv` shrinks to one line setting `ZDOTDIR`; `$ZDOTDIR/.zprofile` becomes the login-shell bridge (`zsh -lc` is login but NOT interactive, so `.zprofile` runs for agent shells while `.zshrc` never does); the agent-safe base (`codex-env.zsh` marking `CODEX_AGENT_ENV_SOURCED=1`, deterministic PATH in `conf.d/00-path.zsh`, reviewed `local.zsh`) loads on every login shell; and `CODEX_LOAD_ZSH_DSL` gates only the extra helper/function files. To build that clean layout, run this prompt verbatim (do not run it on top of step 1's guard without reconciling — they are two versions of the same airlock):

```text
Set up an agent-safe zsh and Codex shell environment so commands run through `zsh -lc` can resolve required project tools, load selected helper files only when explicitly opted in, and keep the full interactive `.zshrc` out of agent shells.

Step 1. Inspect before changing anything. Check the current non-interactive login shell view with targeted commands only:

    zsh -lc 'echo "ZDOTDIR=$ZDOTDIR"; command -v bun pnpm cargo codex packx || true'

Do not paste full `env` output. Do not print secret values, token values, cookies, private endpoints, or provider-specific API variables.

Step 2. Configure `ZDOTDIR` from `~/.zshenv`. Keep `~/.zshenv` minimal because every zsh process reads it. Its job should be early, safe bootstrap only, such as:

    export ZDOTDIR="${ZDOTDIR:-$HOME/.config/zsh}"

Verify:

    zsh -lc 'echo "ZDOTDIR=$ZDOTDIR"; test -d "$ZDOTDIR" && echo "ZDOTDIR exists" || echo "ZDOTDIR missing"'

Step 3. Create or update `$ZDOTDIR/.zprofile` as the login-shell bridge for `zsh -lc`. Remember: `zsh -lc` is a login shell, but it is not interactive. Source only agent-safe startup files from here, such as `codex-env.zsh`, `conf.d/00-path.zsh`, and reviewed local overrides.

Use this shape, adjusted to the existing files:

    [[ -r "$ZDOTDIR/codex-env.zsh" ]] && source "$ZDOTDIR/codex-env.zsh"
    [[ -r "$ZDOTDIR/conf.d/00-path.zsh" ]] && source "$ZDOTDIR/conf.d/00-path.zsh"
    [[ -r "$ZDOTDIR/local.zsh" ]] && source "$ZDOTDIR/local.zsh"

Step 4. Put agent-safe environment setup in `$ZDOTDIR/codex-env.zsh`. This file may set non-secret tool environment needed by agents and should mark that it loaded:

    export CODEX_AGENT_ENV_SOURCED=1

Do not put prompts, completions, keybindings, fuzzy finders, terminal UI, interactive confirmations, token-resolving commands, or secret-printing helpers here.

Step 5. Put deterministic PATH assembly in `$ZDOTDIR/conf.d/00-path.zsh`. Add required tool directories such as Cargo, Bun, pnpm, Homebrew, project-local bins, and `~/.local/bin` as appropriate for the local install. Make PATH order explicit so the intended executable wins.

Verify PATH order:

    zsh -lc 'print -l ${(s/:/)PATH} | nl -ba | sed -n "1,25p"'

Verify executable resolution:

    zsh -lc 'for cmd in node pnpm bun cargo codex packx; do echo "--- $cmd ---"; command -v "$cmd" || true; whence -a "$cmd" 2>/dev/null || true; done'

Step 6. Use `$ZDOTDIR/local.zsh` only for safe local overrides that are appropriate in non-interactive shells. Do not copy private config verbatim if it contains secrets, API-key helper wiring, cookies, tokens, provider variables, or private endpoints.

Step 7. Keep `$ZDOTDIR/.zshrc` interactive-only. Prompt setup, completion setup, aliases for human typing, keybindings, terminal UI, profiling, and fuzzy finder setup belong there or behind an interactive guard. Do not source `.zshrc` from `.zprofile`, `codex-env.zsh`, or agent shell startup.

Step 8. Add opt-in helper loading with `CODEX_LOAD_ZSH_DSL`. Treat `CODEX_LOAD_ZSH_DSL` as a local marker, not a Codex built-in. When it is present, load only selected agent-safe helper files such as `$ZDOTDIR/conf.d/40-ai.zsh`; do not load the full `.zshrc`.

Add this in the agent-safe startup path after `ZDOTDIR` is available:

    if [[ -n "${CODEX_LOAD_ZSH_DSL:-}" ]]; then
      [[ -r "$ZDOTDIR/conf.d/40-ai.zsh" ]] && source "$ZDOTDIR/conf.d/40-ai.zsh"
    fi

Verify the marker is absent by default:

    zsh -lc 'echo "CODEX_LOAD_ZSH_DSL=${CODEX_LOAD_ZSH_DSL:-}"'

Verify selected helper loading when requested:

    CODEX_LOAD_ZSH_DSL=1 zsh -lc 'echo "CODEX_AGENT_ENV_SOURCED=${CODEX_AGENT_ENV_SOURCED:-}"; echo "ZDOTDIR=$ZDOTDIR"; command -v bun pnpm cargo codex packx || true'

Step 9. Configure Codex marker injection with `shell_environment_policy.set`. Prefer wrapper-local `-c` flags so the behavior is explicit and reversible. Add or update `xi`, `x`, and `e` wrappers in the interactive helper file that defines Codex launch helpers:

    xi() {
      codex -c 'shell_environment_policy.set.CODEX_LOAD_ZSH_DSL="1"' "$@"
    }

    x() {
      codex -c 'shell_environment_policy.set.CODEX_LOAD_ZSH_DSL="1"' --dangerously-bypass-approvals-and-sandbox "$@"
    }

    e() {
      codex exec -c 'shell_environment_policy.set.CODEX_LOAD_ZSH_DSL="1"' --dangerously-bypass-approvals-and-sandbox "$@"
    }

Only add this to `~/.codex/config.toml` if every Codex launch should load the helper DSL:

    [shell_environment_policy.set]
    CODEX_LOAD_ZSH_DSL = "1"

Otherwise, keep the marker out of global config and use the wrappers.

Verify wrapper policy wiring:

    zsh -ic 'functions xi 2>/dev/null; functions x 2>/dev/null; functions e 2>/dev/null' | rg 'shell_environment_policy.set.CODEX_LOAD_ZSH_DSL' || true
    rg -n 'shell_environment_policy|CODEX_LOAD_ZSH_DSL' ~/.codex/config.toml || true

Step 10. Run the base proof and clean-shell proof. The clean-shell check avoids being fooled by inherited marker state.

    zsh -lc 'echo "CODEX_AGENT_ENV_SOURCED=${CODEX_AGENT_ENV_SOURCED:-}"; echo "ZDOTDIR=$ZDOTDIR"; command -v codex bun pnpm cargo packx || true'

    env -u CODEX_AGENT_ENV_SOURCED zsh -lc 'echo "CODEX_AGENT_ENV_SOURCED=${CODEX_AGENT_ENV_SOURCED:-}"; echo "ZDOTDIR=$ZDOTDIR"; command -v codex bun pnpm cargo packx || true'

Expected result: `CODEX_AGENT_ENV_SOURCED=1`, `ZDOTDIR` points at the intended config directory, required tools print real paths, and no secret values are printed.

Step 11. Add executable fallbacks for important helper entrypoints that must work outside zsh. If a workflow currently exists only as an alias or zsh function but scripts, CI, non-zsh callers, or agents need it, create a real executable wrapper on PATH, for example under `~/.local/bin`, and verify it with `zsh -lc 'command -v <name>'`.

Step 12. Final confirmation. Stop when `zsh -lc` resolves the required project tools, the clean-shell check also resolves them, PATH order is explainable, `CODEX_LOAD_ZSH_DSL` behavior is explicit and reversible, `.zshrc` remains interactive-only, startup does not print secrets or wait for UI, and Codex can run the project command that originally failed. If project tools resolve but a helper name is still missing, classify that helper separately instead of fixing it by sourcing `.zshrc`.
```

#### Verification (either version)

```bash
zsh -lc 'echo "CODEX_LOAD_ZSH_DSL=${CODEX_LOAD_ZSH_DSL:-}"'
CODEX_LOAD_ZSH_DSL=1 zsh -lc 'echo "CODEX_AGENT_ENV_SOURCED=${CODEX_AGENT_ENV_SOURCED:-}"; echo "ZDOTDIR=$ZDOTDIR"; command -v bun pnpm cargo codex packx || true'
env -u CODEX_AGENT_ENV_SOURCED zsh -lc 'echo "CODEX_AGENT_ENV_SOURCED=${CODEX_AGENT_ENV_SOURCED:-}"; echo "ZDOTDIR=$ZDOTDIR"; command -v codex bun pnpm cargo packx || true'
```

Expected for the clean layout: `CODEX_AGENT_ENV_SOURCED=1`, `ZDOTDIR` pointing at the intended config directory, required tools printing real paths, and no secret values printed. The first command should print an empty marker by default; the clean-shell (`env -u`) check guards against being fooled by inherited marker state. (Step 1's `.zshenv` guard version does not set `CODEX_AGENT_ENV_SOURCED`; for it, use the `whence -w <your-function>` check from step 3 instead.)

## Notes for agents

- Instruction-once state persists in `${TMPDIR:-/tmp}/pi-command-instructions/<session-id>/` across runs. If the first `ls` does NOT print the briefing, a marker from an earlier run exists — remove it with the `command rm -rf` line above (change `check-a` to the session id you used) and retry.
- `command rm`, `command git`, etc. bypass the overrides by design. This setup is guidance the agent reads at the moment it acts, not a security boundary. Anything that must never happen belongs in Pi's hooks/permissions, not here.
- Without the extension, `pi_session_id` falls back to `process-$PPID`, which is stable per shell process rather than per conversation — the overrides still work, but "once per session" becomes "once per shell parent".
- If overrides don't fire inside Pi, the usual cause is that the user has not trusted `.pi/settings.json` yet, so the prefix is never prepended.
- The `linear` override rewrites only `linear issue create`; every other `linear` subcommand passes through untouched. Set `PI_LINEAR_OVERRIDE_DRY_RUN=1` to print the rewritten argv instead of calling the real CLI.
- Full explanation, prompt library, and caveats: https://polite-ravine-6v8g.here.now/
- For your user (human-readable presentation pages): an annotated replay of the session that built this setup at https://polite-ravine-6v8g.here.now/replay.html, and a Q&A walkthrough at https://polite-ravine-6v8g.here.now/dialogue.html. Both carry the complete `.pi/agent-shell.zsh`.