{
  "schemaVersion": "1",
  "revision": "22ce5d34dbcb5a78",
  "id": "factory-environment-policy-worked-example",
  "slug": "environment-policy-worked-example",
  "title": "Policy at the agent’s execution boundary — worked example",
  "summary": "Detailed worked example with concrete prompts, observable outcomes, and the limits of the example.",
  "category": "Execution",
  "tags": [
    "environment-policy",
    "examples"
  ],
  "sources": [
    {
      "label": "Policy at the agent’s execution boundary — worked example",
      "url": "https://polite-ravine-6v8g.here.now/replay.html"
    }
  ],
  "sourceUnits": [
    "01-env/replay.html#The session"
  ],
  "collection": "factory",
  "categoryId": "execution",
  "wordCount": 1688,
  "url": "/topics/factory-environment-policy-worked-example/",
  "markdownUrl": "/markdown/factory-environment-policy-worked-example.md?raw=1&v=22ce5d34dbcb5a78",
  "jsonUrl": "/api/v1/documents/factory-environment-policy-worked-example.json",
  "headings": [
    {
      "id": "the-session",
      "text": "The session",
      "level": 2
    }
  ],
  "markdown": "# Policy at the agent’s execution boundary — worked example\n\nDetailed worked example with concrete prompts, observable outcomes, and the limits of the example.\n\n## The session\n\nYou\n\nPi runs every shell command my agent executes. I want a project-local hook that runs before each one — override `rm`, `git`, and friends for this project without touching my global zshrc.\n\nAgent\n\nPi has exactly that hook: `shellCommandPrefix` in the project's `.pi/settings.json`. It prepends a snippet to every command the agent runs. Pointing it at a sourced zsh file makes every function in that file shadow the command of the same name:\n\n``` text\n{\n  \"shellPath\": \"/bin/zsh\",\n  \"shellCommandPrefix\": \"source \\\"$PWD/.pi/agent-shell.zsh\\\"\"\n}\n```\n\nThe whole integration is two JSON keys. Everything after this beat is plain zsh — no plugin API to learn, and the real binaries stay reachable via `command rm`, `command git`.\n\nYou\n\nStart with `rm`. The agent should never permanently delete anything — move targets somewhere recoverable, and tell the agent what happened and how to undo it.\n\nAgent\n\nAdded `rm()` to a new `.pi/agent-shell.zsh`. Targets move to a session-scoped quarantine dir, and both notices print to stderr, addressed to the model:\n\n``` text\nprint -u2 -- \"[rm-override session=$session_id] quarantined $moved item(s) in $quarantine instead of deleting.\"\nprint -u2 -- \"[rm-override] restore with: mv \\\"$quarantine/<name>\\\" <dest>. Real deletion requires 'command rm' and explicit user approval.\"\n```\n\nThose two stderr lines are the whole design: a message to the model at the moment it acts, not a rule it read forty thousand tokens ago. If you can see the line in the transcript, the agent saw it too.\n\nYou\n\nSame idea for `git`: block `push --force` and `reset --hard`, and make the failure message tell the agent what to do instead.\n\nAgent\n\nDone — the override inspects argv and refuses with guidance before real git ever runs. From the captured harness transcript:\n\n``` text\n▶ [session session-A] $ git push --force origin main\n  [git-override session=session-A] force push blocked. Ask the user to run it\n  themselves, or explain why history must be rewritten and wait for approval.\n\n▶ [session session-A] $ git reset --hard HEAD~3\n  [git-override session=session-A] 'git reset --hard' blocked. Prefer 'git stash'\n  or 'git restore <path>' so work is recoverable.\n```\n\nExit code 1, nothing pushed, and the agent gets a next step it can act on in the same turn. `command git` still bypasses it — this is guidance with teeth, not a sandbox.\n\nYou\n\nNow a real team policy: every Linear issue the agent files gets assigned to me. Rewrite `linear issue create` so `--assignee self` is enforced no matter what flags the agent passed.\n\nAgent\n\nThe override strips any assignee the agent chose and appends `--assignee self`, announcing the rewrite on stderr. Dry-run mode prints the final argv:\n\n``` text\n▶ [session session-A] $ linear issue create --title 'Fix login bug' --assignee someone-else\n  [linear-override session=session-A] enforcing --assignee self\n  [linear-override dry-run] command linear issue create --title Fix\\ login\\ bug --assignee self\n```\n\nAdapted from a working policy in a private test project. It rewrites only `issue create`; every other `linear` subcommand passes through untouched.\n\nYou\n\nThe tricky one: brief the model exactly once per conversation. The first `ls` should return instructions to the AI; every later `ls` runs normally. But Pi spawns a fresh shell per command — where does \"once\" live?\n\nAgent\n\nNot in shell variables — a fresh shell forgets everything. State has to live on disk, keyed by the *conversation*, or `/new` and `/fork` would inherit a stale \"already briefed\" flag. Installed the pi-session-id extension (`pi install git:github.com/johnlindquist/pi-session-id`), which exports `PI_SESSION_ID` into every shell Pi spawns. With that key, \"once per session\" is one atomic `mkdir`:\n\n``` text\npi_instruction_once() {\n  emulate -L zsh\n  local command_name=\"$1\"\n  local state_root=\"${TMPDIR:-/tmp}/pi-command-instructions\"\n  local session_id=\"$(pi_session_id)\"\n  local marker=\"$state_root/$session_id/$command_name\"\n\n  mkdir -p \"$state_root/$session_id\" || return 1\n  if mkdir \"$marker\" 2>/dev/null; then\n    cat\n    return 0\n  fi\n  return 1\n}\n```\n\n`mkdir` succeeds exactly once per marker path, so \"first time\" is race-free even with parallel Pi processes. The extension itself is ~44 lines of TypeScript syncing the session ID on `session_start`, human `!` commands, and every model bash call — with the ID validated before it touches shell source.\n\nYou\n\nProve all of it without Pi in the loop. I want a harness that runs commands exactly the way Pi does, so a broken override never takes down a live session.\n\nAgent\n\nWrote `demo/run-demo.sh`: fresh zsh per command, prefix sourced, `PI_SESSION_ID` set — Pi's execution model, reproduced. Ran it; the captured transcript (checked in as `demo/sample-output.txt`):\n\n``` text\n▶ [session session-A] $ ls demo\n  INSTRUCTIONS FOR THE AI:\n  This project overrides rm, git, linear, and ls via .pi/agent-shell.zsh.\n  Deletions are quarantined, force pushes are blocked, and Linear issues are\n  always self-assigned. Run ls again to execute the command normally.\n\n▶ [session session-A] $ ls demo\n  run-demo.sh\n  sample-output.txt\n\n▶ [session session-A] $ rm .demo-state/playground/important.txt\n  [rm-override session=session-A] quarantined 1 item(s) in\n  <project>/.demo-state/tmp/pi-rm-quarantine/session-A instead of deleting.\n\n▶ [session session-A] $ ls .demo-state/tmp/pi-rm-quarantine/session-A\n  important.txt\n\n▶ [session session-B] $ ls demo\n  INSTRUCTIONS FOR THE AI: …\n```\n\nThe beat that matters most is the last one: session-B sees the briefing again. State is keyed per conversation, not per machine — `/new` and `/fork` each get their own \"first time\".\n\nYou\n\nLand it. Give me the whole override file so I can lift it into any project.\n\nAgent\n\nHere is `.pi/agent-shell.zsh`, complete — the section's money artifact. Keep `pi_session_id` and `pi_instruction_once` as-is; swap the four policy functions for your own:\n\n``` text\n# .pi/agent-shell.zsh\n#\n# Sourced before EVERY shell command the agent runs, via .pi/settings.json:\n#\n#   { \"shellPath\": \"/bin/zsh\",\n#     \"shellCommandPrefix\": \"source \\\"$PWD/.pi/agent-shell.zsh\\\"\" }\n#\n# Pi spawns a fresh shell per command, so plain shell variables can't carry\n# state between commands. The pi-session-id extension\n# (https://github.com/johnlindquist/pi-session-id) exports PI_SESSION_ID into\n# each of those shells, which lets these overrides keep per-conversation state\n# on disk — e.g. \"show this instruction once per session\".\n\npi_session_id() {\n  print -r -- \"${PI_SESSION_ID:-process-$PPID}\"\n}\n\n# Emit a heredoc the FIRST time a command runs in this session, then get out\n# of the way. State lives under $TMPDIR keyed by session id, so /new, /fork,\n# and parallel Pi processes each get their own \"first time\".\npi_instruction_once() {\n  emulate -L zsh\n  local command_name=\"$1\"\n  local state_root=\"${TMPDIR:-/tmp}/pi-command-instructions\"\n  local session_id=\"$(pi_session_id)\"\n  local marker=\"$state_root/$session_id/$command_name\"\n\n  mkdir -p \"$state_root/$session_id\" || return 1\n  if mkdir \"$marker\" 2>/dev/null; then\n    cat\n    return 0\n  fi\n  return 1\n}\n\n# --- rm: quarantine instead of delete --------------------------------------\n# The agent never permanently deletes anything. Targets move to a\n# session-scoped quarantine dir; the notice tells the agent how to restore.\nrm() {\n  emulate -L zsh\n  local session_id=\"$(pi_session_id)\"\n  local quarantine=\"${TMPDIR:-/tmp}/pi-rm-quarantine/$session_id\"\n  local -a targets\n  local arg\n  for arg in \"$@\"; do\n    [[ \"$arg\" == -* ]] || targets+=(\"$arg\")\n  done\n\n  if (( ${#targets} == 0 )); then\n    command rm \"$@\"\n    return\n  fi\n\n  mkdir -p \"$quarantine\" || return 1\n  local moved=0 target\n  for target in \"${targets[@]}\"; do\n    if [[ -e \"$target\" || -L \"$target\" ]]; then\n      mv -- \"$target\" \"$quarantine/\" && (( moved++ ))\n    else\n      print -u2 -- \"[rm-override] no such file: $target\"\n    fi\n  done\n  print -u2 -- \"[rm-override session=$session_id] quarantined $moved item(s) in $quarantine instead of deleting.\"\n  print -u2 -- \"[rm-override] restore with: mv \\\"$quarantine/<name>\\\" <dest>. Real deletion requires 'command rm' and explicit user approval.\"\n}\n\n# --- git: block destructive operations --------------------------------------\n# Force pushes and hard resets fail loudly with guidance instead of running.\ngit() {\n  emulate -L zsh\n  local session_id=\"$(pi_session_id)\"\n  local arg\n\n  if [[ \"$1\" == \"push\" ]]; then\n    for arg in \"$@\"; do\n      case \"$arg\" in\n        -f|--force|--force-with-lease|--force-if-includes)\n          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.\"\n          return 1\n          ;;\n      esac\n    done\n  fi\n\n  if [[ \"$1\" == \"reset\" ]]; then\n    for arg in \"$@\"; do\n      if [[ \"$arg\" == \"--hard\" ]]; then\n        print -u2 -- \"[git-override session=$session_id] 'git reset --hard' blocked. Prefer 'git stash' or 'git restore <path>' so work is recoverable.\"\n        return 1\n      fi\n    done\n  fi\n\n  command git \"$@\"\n}\n\n# --- linear: enforce team policy on issue creation --------------------------\n# Adapted from a real override in ~/dev/pi-session-test: every issue the agent\n# creates is assigned to the current user, no matter what flags it passed.\nlinear() {\n  emulate -L zsh\n  local session_id=\"$(pi_session_id)\"\n\n  if [[ \"$1\" != \"issue\" || \"$2\" != \"create\" ]]; then\n    command linear \"$@\"\n    return\n  fi\n\n  local -a decorated\n  local skip=0 arg\n  for arg in \"$@\"; do\n    if (( skip )); then skip=0; continue; fi\n    case \"$arg\" in\n      -a|--assignee) skip=1 ;;\n      -a=*|--assignee=*) ;;\n      *) decorated+=(\"$arg\") ;;\n    esac\n  done\n  decorated+=(--assignee self)\n\n  print -u2 -- \"[linear-override session=$session_id] enforcing --assignee self\"\n\n  if [[ -n \"${PI_LINEAR_OVERRIDE_DRY_RUN:-}\" ]]; then\n    print -n -- \"[linear-override dry-run] command linear\"\n    for arg in \"${decorated[@]}\"; do printf ' %q' \"$arg\"; done\n    print\n    return 0\n  fi\n\n  command linear \"${decorated[@]}\"\n}\n\n# --- ls: teach the agent, once per conversation ------------------------------\n# The pattern from the pi-session-id README: the first `ls` of a session\n# returns instructions to the model instead of output; every later `ls` runs\n# normally. Swap the message for anything you want the agent told exactly once.\nls() {\n  if pi_instruction_once ls <<'INSTRUCTIONS'; then\nINSTRUCTIONS FOR THE AI:\nThis project overrides rm, git, linear, and ls via .pi/agent-shell.zsh.\nDeletions are quarantined, force pushes are blocked, and Linear issues are\nalways self-assigned. Run ls again to execute the command normally.\nINSTRUCTIONS\n    return 0\n  fi\n\n  command ls \"$@\"\n}\n```\n\nVerified with the four-line success check — fresh zsh, two session ids, output matching the transcript above:\n\n``` text\ncommand rm -rf \"${TMPDIR:-/tmp}/pi-command-instructions/check-a\"\nPI_SESSION_ID=check-a zsh -c 'source .pi/agent-shell.zsh && ls'\nPI_SESSION_ID=check-a zsh -c 'source .pi/agent-shell.zsh && ls'\nPI_SESSION_ID=check-b zsh -c 'source .pi/agent-shell.zsh && git push --force origin main'\n```\n\nSeven beats: one settings hook, four overrides, one state trick, one harness. The same recipe generalizes to anything on PATH — wrap `npm` to enforce pnpm, wrap `curl` to log egress, wrap `pytest` to always add `-x`.\n\nRebuilt from a prior session using this project's real files: prompts are condensed, but every file shown matches disk byte-for-byte and every output line comes from the checked-in `demo/sample-output.txt` (project path replaced with `<project>`)."
}
