See the once-per-conversation briefing
List the files in this project. If the shell tells you anything unusual, quote it back to me before doing anything else.
Agentic Software Factory · 2026-07-17
Give your coding agent a project-specific shell: quarantine rm, block force pushes, enforce issue policy, and brief the model exactly once per conversation.
.pi/ rewire every shell command your agent runs: 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.🤖 Have your agent set this up — paste this into it:
Fetch https://polite-ravine-6v8g.here.now/agent.md?raw and follow it to set this up in my current project. Run the success check at the end and show me the result.
From your project root:
pi install git:github.com/johnlindquist/pi-session-id
mkdir -p .pi
# paste the two files from the agent guide below into .pi/, then prove it:
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'
First ls prints instructions addressed to the AI; the second runs normally. That's the whole mechanism working.
Paste these into Pi inside a project that has the setup below (with .pi/settings.json trusted) and watch the agent read the override output and self-correct.
List the files in this project. If the shell tells you anything unusual, quote it back to me before doing anything else.
Create a file named scratch-note.txt containing the word "disposable", then delete it. Afterward, tell me exactly what the shell printed when you deleted it and where the file actually went.
Force-push the current branch to origin right now. If anything stops you, do not work around it — stop and report exactly what it said.
Create a Linear issue titled "Fix login bug" and assign it to someone-else. Show me the exact command you ran and everything it printed.
These steps mirror agent.md — the machine copy your agent fetches.
PI_SESSION_ID:
pi install git:github.com/johnlindquist/pi-session-id
.pi/settings.json in your project. It tells Pi which shell to use and sources the override file before every command:
{
"shellPath": "/bin/zsh",
"shellCommandPrefix": "source \"$PWD/.pi/agent-shell.zsh\""
}
.pi/agent-shell.zsh — the override file itself, complete. Keep pi_session_id and pi_instruction_once as-is; swap the four policy functions for your 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 "$@"
}
.pi/settings.json when Pi asks you to trust it. Until you do, the prefix never runs.Success check: run each override in a fresh zsh -c with PI_SESSION_ID set — the same way Pi runs commands — from your project root:
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'
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.
CLAUDE.md
demo
folio
notes
README.md
site
[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.
Line by line: the first ls returns the briefing, the second returns your project's normal listing (this transcript shows this project's files), and the force push is refused with exit code 1.
The .pi/ setup above is one instance of a portable idea: put your policy at the seam where the agent's actions pass through, and make its output land in the model's context at the moment it acts. All three agents give you a first-class version of that seam:
| Agent | Where the override lives | How it's scoped | Session key | How the message reaches the model |
|---|---|---|---|---|
| Pi | .pi/settings.json → shellCommandPrefix sources .pi/agent-shell.zsh | Per project, once trusted | PI_SESSION_ID (extension) | Override's stderr, same turn as the action |
| Codex | .zshenv guard sources your function files into opted-in agent shells | Per launch (codex -c …) or per machine (config.toml) | — | Shadowing function's stderr, same turn |
| Claude Code | PreToolUse hooks + the env map in settings.json | Per project (.claude/settings.json) or global (~/.claude/settings.json) | session_id in every hook's stdin JSON | Hook decision + reason, delivered before the tool runs |
The failure-mode demo takes ten seconds: ask plain codex to run one of your zsh helper functions and it comes back not found; ask the x wrapper from the custom zsh functions section and the same function resolves. In this setup, plain Codex does not automatically receive your zsh helper/function surface — and the wrapper doesn't fix that by sourcing zsh files. It starts Codex with one environment variable, and your zsh config decides what that variable means:
codex -c 'shell_environment_policy.set.CODEX_LOAD_ZSH_DSL="1"'
Codex's shell_environment_policy is the real, documented piece here — it injects env vars into the shells Codex spawns. CODEX_LOAD_ZSH_DSL is not a Codex built-in: it's a local marker this setup invented, and zsh startup rules — not Codex — decide which files load when they see it. Prefer the wrapper-local -c flag, which keeps the opt-in explicit and reversible per launch. Reach for global config only if every Codex launch on the machine should load the helper surface (it's also the place for per-machine values your functions need; the real config carries a key-helper path here, generalized below):
# Append to ~/.codex/config.toml to make the opt-in permanent for every
# launch — no wrapper function needed.
[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"
What the marker opens is best pictured as an airlock. On one side sits your interactive .zshrc — prompt, completions, keybindings, fuzzy finders, terminal UI — and it stays sealed: agent shells never source it, because in a non-interactive shell that machinery can slow, hang, or spam every command the agent runs. In the middle is a narrow agent-safe bridge that assembles PATH and non-secret env for agent shells. And the marker is the opt-in valve: only when a launch sets it do your chosen helper and override files cross into the agent shell. When something's missing on the Codex side, the temptation is to open the whole hatch. The field rule: missing PATH is not permission to pour .zshrc into Codex.
Here's the airlock as John runs it today — a guard at the end of his real ~/.config/zsh/.zshenv. zsh sources .zshenv for every shell it starts, so the guard sees every agent shell, and it opens only when the launch opted in and no human is at the prompt (the sourced list here is trimmed to representative entries). Append it to your own .zshenv:
# 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
Because these are real zsh shells, overrides are plain function shadowing — an rm() function beats /bin/rm — and stderr reaches the model naturally. Every policy function in .pi/agent-shell.zsh above works verbatim in a file the guard sources. The base file the guard loads first looks like this:
# codex-env.zsh (excerpt) — the base file the guard loads first.
# Functions are not inherited by child shells, so the source guard is
# deliberately shell-local (typeset -g, not exported):
[[ -n "${__CODEX_AGENT_ENV_SOURCED:-}" ]] && return 0
typeset -g __CODEX_AGENT_ENV_SOURCED=1
export CODEX_AGENT_ENV_READY=1
# ...PATH and env setup for agent shells, then plain function shadowing:
if (( $+commands[mdflow] )); then
md() {
command mdflow "$@"
}
fi
That shell-local guard is a hard-won detail: a prior session that refactored this zsh config had to preserve it, because child shells inherit the exported env markers but not the functions — every nested zsh must re-create them.
There's also a cleaner cut of the same airlock — the version refined for a prior Codex workshop. It moves the bridge out of .zshenv entirely: ~/.zshenv shrinks to one line that sets ZDOTDIR, and $ZDOTDIR/.zprofile becomes the login-shell bridge. The proof shell for this setup, zsh -lc, is a login shell but not interactive — so .zprofile runs for it while .zshrc never does. In that layout the agent-safe base always crosses the bridge — codex-env.zsh marks itself with CODEX_AGENT_ENV_SOURCED=1, conf.d/00-path.zsh does deterministic PATH assembly, local.zsh holds reviewed machine-local overrides — and CODEX_LOAD_ZSH_DSL gates only the extra helper DSL. That's the honest difference from the guard above: in the live .zshenv version everything, base env included, waits behind the valve; in the clean version the base env rides the bridge on every login shell and only the function surface is opt-in. Same airlock, cleaner plumbing. This setup prompt builds the clean version end to end — hand it to your agent verbatim:
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`.
However you get there, the proof should be boring: confirm the marker is off by default, confirm the env marker and tools appear when it's on, and re-check from a clean shell so an inherited marker can't fool you. Never dump full env output — confirm tools without printing secret values:
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'
Claude Code's seam is not the shell but the tool call. A PreToolUse hook sees every Bash command before it runs and can allow it, deny it, or attach an instruction — and whatever it says is delivered to the model at the moment of action. Check this into any repo as project scope (the same shape John runs globally in ~/.claude/settings.json):
{
"env": {
"PROJECT_ISSUE_ASSIGNEE": "self"
},
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/git-guard.sh"
}
]
}
]
}
}
The env map sets per-project env vars for every session in that project. The hook script receives the pending call as JSON on stdin — including session_id, Claude Code's PI_SESSION_ID: key per-session state (and the tag in your messages) by it, and use SessionStart hooks to seed that state once per conversation. This validator mirrors the page's git override; it's distilled from a hook that runs on every Bash call on John's machine:
#!/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
Make it executable (chmod +x .claude/hooks/git-guard.sh) and test it exactly like the pi overrides — no agent in the loop, just the hook's stdin contract:
echo '{"session_id":"check-a","tool_input":{"command":"git push --force origin main"}}' \
| .claude/hooks/git-guard.sh
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": "[git-guard session=check-a] force push blocked. Ask the user to run it themselves, or explain why history must be rewritten and wait for approval."
}
}
Same message as the pi override, delivered even harder: the push never runs, and the reason becomes the model's next input. The difference in kind is worth naming — a zsh function is guidance (command git bypasses it), while a deny from a hook is enforcement. In all three agents, though, the core move is identical: the override's output at the moment of action is the message to the model.
You've written rules for your agent in CLAUDE.md or AGENTS.md: never force push, never hard-delete, always self-assign issues. Then, deep into a session, the agent runs rm -rf anyway. The mistake is treating instructions the model read once as if they control actions it takes much later.
Every deletion, push, and issue the agent creates passes through one place: the shell. A tagged stderr line like [git-override session=…] lands in the agent's tool output in the same turn as the blocked action — it can read the message and change course immediately. If you can see that line in the transcript, the agent saw it too.
The decision rule: use overrides to steer — redirect destructive commands, inject policy, brief the model — and use Pi's hooks and permission system to enforce anything you can't afford to have bypassed. If violating a rule merely wastes a turn, an override is enough. If it loses data or pushes broken history, put a real control behind the friendly message.
Pi runs every agent command in a fresh shell and, once you trust a project's .pi/settings.json, prepends its shellCommandPrefix. Here that prefix sources .pi/agent-shell.zsh, so every zsh function in it shadows the command of the same name. The real binaries stay reachable: command rm, command git. This project ships four overrides — quarantining rm, guarded git, a linear rewrite adapted from a real team policy, and the instruction-once ls.
A fresh shell per command means plain variables can't carry state between commands. Blocking a force push needs no memory — the evidence is in the argv. But "tell the agent this once, then get out of the way" needs state that survives across throwaway shells, and storing it under a fixed path fails in a specific way: /new, /resume, and /fork would all share one "first time".
The pi-session-id extension (~44 lines of TypeScript) exports the active conversation ID as PI_SESSION_ID into each shell, syncing it on session_start, on human ! commands, and on every model bash call. The ID is validated against Pi's session-ID syntax before it touches shell source — an invalid value blocks the call rather than permitting injection. With that key, per-conversation state is just a directory name, which is all pi_instruction_once is: a mkdir that succeeds exactly once per session. Keep overrides stateless unless the first occurrence in a conversation must behave differently from every later one.
An override you've never executed is a guess, and a broken one makes every agent command fail mid-session. This project's demo/run-demo.sh reproduces Pi's execution model — fresh zsh, prefix sourced, PI_SESSION_ID set — so you can watch all five acts fire without Pi in the loop:
▶ [session session-A] $ ls demo
INSTRUCTIONS FOR THE AI:
This project overrides rm, git, linear, and ls via .pi/agent-shell.zsh. …
▶ [session session-A] $ rm .demo-state/playground/important.txt
[rm-override session=session-A] quarantined 1 item(s) in
<project>/.demo-state/tmp/pi-rm-quarantine/session-A instead of deleting.
▶ [session session-A] $ ls .demo-state/tmp/pi-rm-quarantine/session-A
important.txt
▶ [session session-A] $ git push --force origin main
[git-override session=session-A] force push blocked. Ask the user to run it
themselves, or explain why history must be rewritten and wait for approval.
▶ [session session-A] $ linear issue create --title 'Fix login bug' --assignee someone-else
[linear-override session=session-A] enforcing --assignee self
[linear-override dry-run] command linear issue create --title Fix\ login\ bug --assignee self
▶ [session session-B] $ ls demo
INSTRUCTIONS FOR THE AI: …
The quarantined file is listed, not gone. The force push never executed. The Linear issue lost --assignee someone-else and gained --assignee self. And session-B sees the briefing again, because state is keyed by conversation. The same recipe, boiled down to four lines, is the success check above.
command rm and command git bypass the functions by design — the overrides say so in their own stderr. Real enforcement belongs in Pi's hooks and permission system.pi.exec() calls, custom tools that spawn processes directly, custom user_bash handlers that build a sanitized environment, or commands that clear their environment with env -i / unset PI_SESSION_ID.linear call ran with PI_LINEAR_OVERRIDE_DRY_RUN=1, printing the rewritten argv instead of hitting the Linear API.pi_session_id falls back to process-$PPID — stable per shell process, not per conversation.shellCommandPrefix executes with your full permissions on every command. Review agent-shell.zsh the way you'd review any shell script from the internet — because it is one.zsh -n / bash -n on the shell blocks, JSON/TOML parses, and the Claude Code validator exercised by piping mock hook JSON to it (deny, allow, and passthrough cases). They were not captured from live Claude Code or Codex sessions; field names follow the current Claude Code hooks contract, which can change..zshenv guard edits a home-directory file, not a project file — it applies to every Codex launch that opts in on that machine, so keep what it sources small and agent-safe.The two files in the agent guide are this workshop project's .pi/settings.json and .pi/agent-shell.zsh, re-read from disk and injected byte-identically at build time. The harness transcript is excerpted from a captured run of demo/run-demo.sh on 2026-07-16 that matched the checked-in demo/sample-output.txt — acts elided with …, long lines wrapped, and the project's absolute path replaced with <project>. The success-check output was captured the same day, verbatim, from the exact commands shown. Extension facts (lifecycle hooks, validation, scope) come from the public pi-session-id repository — its README and the 44-line extensions/session-id.ts at github.com/johnlindquist/pi-session-id. The linear override is adapted from a working policy in a private test project. The claim that moment-of-action messages outperform static instructions is editorial inference, tested against the transcript, not a measured result. The cross-agent section is grounded in the real config on the author's machine: the guard block quotes the actual ~/.config/zsh/.zshenv (sourced-file list trimmed to representative entries), the codex-env.zsh excerpt is curated from the real file, the config.toml snippet mirrors the real [shell_environment_policy] with the personal value generalized to a placeholder, and the Claude Code validator is distilled from a hook that runs globally via the real ~/.claude/settings.json — its deny output was captured verbatim from feeding the script mock hook JSON on 2026-07-17. That the .zshenv guard is load-bearing is evidenced by a prior session's zsh-config refactor, which had to preserve the opt-in behavior and the shell-local source guard; it is referred to generically. No secrets, tokens, or real session IDs appear. This page supersedes the Scholarly Folio previously published at this URL (2026-07-16); its argument and caveats were carried into this appendix.