{
  "schemaVersion": "1",
  "revision": "22ce5d34dbcb5a78",
  "id": "factory-zsh-launchers-reference-patterns",
  "slug": "zsh-launchers-reference-patterns",
  "title": "Thin zsh launchers and composable command families — reference patterns",
  "summary": "Extended explanations, comparisons, experiments, and practical actions for the same operating pattern.",
  "category": "Tools",
  "tags": [
    "zsh-launchers",
    "reference",
    "examples"
  ],
  "sources": [
    {
      "label": "Prepared module reference",
      "url": "https://sacred-ritual-w7as.here.now/"
    }
  ],
  "sourceUnits": [
    "02-zsh/folio/index.html#Abstract",
    "02-zsh/folio/index.html#Notice what launching an agent really costs",
    "02-zsh/folio/index.html#Compare an alias with a defended function",
    "02-zsh/folio/index.html#Explain why composed families beat one-off wrappers",
    "02-zsh/folio/index.html#Choose the agent at prompt time, not alias time",
    "02-zsh/folio/index.html#Test the recipe: build a pi resume family",
    "02-zsh/folio/index.html#Practical action"
  ],
  "collection": "factory",
  "categoryId": "tools",
  "wordCount": 1984,
  "url": "/topics/factory-zsh-launchers-reference-patterns/",
  "markdownUrl": "/markdown/factory-zsh-launchers-reference-patterns.md?raw=1&v=22ce5d34dbcb5a78",
  "jsonUrl": "/api/v1/documents/factory-zsh-launchers-reference-patterns.json",
  "headings": [
    {
      "id": "abstract",
      "text": "Abstract",
      "level": 2
    },
    {
      "id": "notice-what-launching-an-agent-really-costs",
      "text": "Notice what launching an agent really costs",
      "level": 2
    },
    {
      "id": "compare-an-alias-with-a-defended-function",
      "text": "Compare an alias with a defended function",
      "level": 2
    },
    {
      "id": "explain-why-composed-families-beat-one-off-wrappers",
      "text": "Explain why composed families beat one-off wrappers",
      "level": 2
    },
    {
      "id": "choose-the-agent-at-prompt-time-not-alias-time",
      "text": "Choose the agent at prompt time, not alias time",
      "level": 2
    },
    {
      "id": "test-the-recipe-build-a-pi-resume-family",
      "text": "Test the recipe: build a pi resume family",
      "level": 2
    },
    {
      "id": "practical-action",
      "text": "Practical action",
      "level": 2
    }
  ],
  "markdown": "# Thin zsh launchers and composable command families — reference patterns\n\nExtended explanations, comparisons, experiments, and practical actions for the same operating pattern.\n\n## Abstract\n\nTiny zsh functions are the cheapest layer of an agentic system. This document argues five steps: agent CLIs impose a real flag-recall tax; a two-letter wrapper function removes it; composing wrappers into families multiplies the payoff; a self-printing cheat sheet keeps the layer discoverable; and the recipe repeats for any new CLI, shown here by building a resume family for the pi agent. All evidence comes from one machine's working configuration, so treat the specific flags as examples, not standards.\n\n## Notice what launching an agent really costs\n\nYou start a coding agent many times a day. Each launch needs the same environment variable, the same config override, and the same sandbox flag. The common mistake is to lean on shell history: you search backward, hope the right variant surfaces, and sometimes launch with a flag missing. A launch with a missing flag is worse than a failed launch, because the agent starts in a different permission posture than you expect.\n\nThe dotfiles solve this with a one-letter function. The `x` function pins the Codex home directory, injects a config marker, and applies the sandbox-bypass flag in one place (source S1, `conf.d/40-ai.zsh`). [1](https://sacred-ritual-w7as.here.now/#note-1)\n\n1\\. The config override sets `CODEX_LOAD_ZSH_DSL=\"1\"` in the agent's shell environment. The same dotfiles use that marker to expose their shell helpers inside agent tool shells (S1, S3). [↩](https://sacred-ritual-w7as.here.now/#note-ref-1)\n\n``` text\n# ~/.config/zsh/conf.d/40-ai.zsh — the real wrapper (email replaced)\nunalias x 2>/dev/null\nx() {\n  # Default account: <personal-account> via ~/.codex\n  CODEX_HOME=\"${CODEX_PRIMARY_HOME:-$HOME/.codex}\" \\\n    codex -c 'shell_environment_policy.set.CODEX_LOAD_ZSH_DSL=\"1\"' \\\n    --dangerously-bypass-approvals-and-sandbox \"$@\"\n}\n```\n\n**Figure 1.** Source evidence: the `x` function, quoted from S1 with one comment edited to replace a personal email address.\n\n**Safety trade** The `--dangerously-bypass-approvals-and-sandbox` flag removes the agent's approval prompts. The wrapper makes that posture deliberate and visible in one place, but it does not make it safe. Do not copy the flag into your own wrapper unless you accept unattended file and shell access.\n\nTry the check yourself: run `which x` in a shell where the wrapper is loaded. If it prints a function body with every flag pinned, launches can no longer drift. If it prints nothing, or prints an alias, you are still paying the recall tax. Your next move is an inventory: write down every agent command you retyped this week.\n\n## Compare an alias with a defended function\n\nThe tempting shortcut is an alias. An alias substitutes text; it cannot take a positional argument in the middle, cannot run setup logic, and loses quietly when a plugin defines the same name. A function can do all three. The dotfiles treat that last risk as real: nearly every definition starts with `unalias <name> 2>/dev/null`, because oh-my-zsh ships single-letter aliases that would otherwise shadow the function (S1).\n\nThe same wrapper shape repeats across a second agent. The `clx` family wraps Claude Code exactly the way `x` wraps Codex: base flags in the short name, an environment variable for the second account, a positional argument for worktrees (S1).\n\n``` text\nclx()  { claude --dangerously-skip-permissions \"$@\"; }\n\nclx2() {\n  local config_dir=\"${CLAUDE_SECOND_CONFIG_DIR:-$HOME/.claude-second}\"\n  mkdir -p \"$config_dir\" || return\n  CLAUDE_CONFIG_DIR=\"$config_dir\" claude --dangerously-skip-permissions \"$@\"\n}\n\nclxw() {\n  local name=\"$1\"; shift\n  CLAUDE_WORKTREE_NAME=\"$name\" claude --worktree \"$name\" --dangerously-skip-permissions \"$@\"\n}\n```\n\n**Figure 2.** Source evidence: three members of the Claude Code family, quoted from S1. Note what an alias cannot do here: `clxw` consumes its first argument before passing the rest through.\n\nWrappers also absorb upstream bugs. The `pi` wrapper deletes a malformed lock file before every launch, so a known failure in the pi agent's locking library never reaches the user (source S2, `local.zsh`). [2](https://sacred-ritual-w7as.here.now/#note-2)\n\n2\\. The source comment explains the mechanism: pi's lockfile dependency expects a directory at `auth.json.lock`. A stray regular file there causes recurring auth failures, so the wrapper removes it (S2). [↩](https://sacred-ritual-w7as.here.now/#note-ref-2)\n\nThe decision rule: reach for an alias only when the command is pure text substitution with no arguments, no environment, and no collision risk. Otherwise write a function with the `unalias` guard and `\"$@\"` pass-through. The feedback signal is the same as before — `which <name>` tells you which one you actually got.\n\n## Explain why composed families beat one-off wrappers\n\nA single wrapper saves keystrokes. The compounding payoff appears when wrappers call other wrappers. If `x` owns the account and the flags, then every session action becomes a one-line composition on top of it — and inherits any future fix to `x` for free.\n\nThe dotfiles build a whole resume-and-fork vocabulary this way: `xr` resumes, `xrl` resumes the last session, `xrm` resumes a session named \"m\", and `xfmc` forks that session, compacts the fork, and resumes it — all routed through `x` (S1).\n\n``` text\nxr()  { x resume \"$@\"; }\nxrl() { x resume --last \"$@\"; }\nxrm() { x resume m \"$@\"; }\nxf()  { x fork \"$@\"; }\n\nxfmc() {\n  local fork_id\n  fork_id=\"$(_codex_app_server_fork_compact_latest m)\" || return 1\n  print -r -- \"$fork_id\"\n  _codex_cmux_name_current_tab\n  x resume \"$fork_id\" \"$@\"\n}\n```\n\n**Figure 3.** Source evidence: the resume and fork family, quoted from S1. Each helper is a thin composition over `x`; only `xfmc` adds real logic.\n\nComposition also solves multi-account work. The `x2` function runs the same agent under a second account by pointing `CODEX_HOME` at a second directory that shares the primary's state through symlinks — while auth files stay local to each account (S1). [3](https://sacred-ritual-w7as.here.now/#note-3)\n\n3\\. A helper named `_codex_egghead_ensure_home` builds the second home. It symlinks every top-level entry except auth-related names such as `auth.json`, and it refuses to run if the auth file ever becomes a symlink (S1). Accounts share sessions and config, never credentials. [↩](https://sacred-ritual-w7as.here.now/#note-ref-3)\n\nA family this large needs its own memory aid, and the dotfiles make the family print one. Running `x-` lists every helper with a one-line description, straight from the same file that defines them (S1; output captured in S3).\n\n``` text\nx        Primary Codex (<personal-account> / ~/.codex) with agent-safe zsh DSL marker.\nx2       Secondary Codex (<work-account> / ~/.codex-work); shared state via symlinks, local auth only.\nxr       Resume a Codex session through the base x wrapper.\nxrl      Resume the most recent Codex session through the base x wrapper.\nxf       Run x fork; pass the conversation id/name first, then the prompt.\nxfmc     Fork conversation m, compact the fork, then resume it interactively.\np-f      Compose a prompt in p, then fork using the prompt-builder --fork-from toggle.\n```\n\n**Figure 4.** Source evidence: excerpt of the `x-` cheat sheet captured the recorded snapshot (S3). Email addresses are replaced with placeholders; the full listing covers 35 helpers.\n\n**Drift risk** Composed families inherit fixes, but they also inherit breakage. When the underlying CLI renames a subcommand or flag, every wrapper above it fails at once. The cheat-sheet function reduces the cost of the audit; it does not remove the need for one.\n\nThe test for your own setup: pick your most common session action — resuming — and count the keystrokes it takes today. If the answer is more than three or four, you have found the first family worth building.\n\n## Choose the agent at prompt time, not alias time\n\nWrappers fix the launch. They do not fix a second, subtler mistake: deciding which agent to use before you have written the prompt. Once the prompt exists, you often realize it belongs to a different agent, a different account, or a forked copy of an old session.\n\nThe `p` command inverts the order. It is a separate terminal program — \"Terminal prompt builder for handing prompts to Pi, Codex, or Claude Code,\" in its own help text — that lets you compose the prompt first and then launch any configured target with it (S3).\n\n``` text\n$ p target list\npi            pi     bin=pi\ncodex         codex  bin=codex   config=shell_environment_policy...\nclaude        claude bin=claude\nwork-profile       codex  bin=codex   CODEX_HOME=~/.codex-work ...\nclaude-second claude bin=claude  CLAUDE_CONFIG_DIR=~/.claude-second\nclaude-third  claude bin=claude  CLAUDE_CONFIG_DIR=~/.claude-third\n```\n\n**Figure 5.** Source evidence: launch targets captured the recorded snapshot (S3), abbreviated to fit. One prompt can go to any of three agents across five accounts.\n\nThe two layers then compose with each other. Helpers such as `p-f` and `p-c` open the prompt builder, and hand the finished prompt to a zsh function that forks a session, optionally compacts it, and resumes it (S1).\n\nYou can rehearse this without launching anything: `p --print-prompt \"explain this repo\"` prints the composed prompt and exits, and `--dry-run` skips the launch entirely (S3). If the printed prompt matches what you meant to send, the pipeline is wired correctly. The limit to keep in mind: the target list above is one machine's configuration file, not a default that ships with the tool.\n\n## Test the recipe: build a pi resume family\n\nThe claim that this recipe repeats \"in minutes\" is testable, and the workshop tests it live. The pi agent has a base wrapper but no session helpers yet. Step one is always the same: ask the CLI what it can do, instead of guessing.\n\n``` text\n$ pi --help | grep -E -- \"--resume|--continue|--fork|--name|--no-session\"\n  --continue, -c        Continue previous session\n  --resume, -r          Select a session to resume\n  --fork <path|id>      Fork specific session file or partial UUID into a new session\n  --name, -n <name>     Set session display name\n  --no-session          Don't save session (ephemeral)\n```\n\n**Figure 6.** Source evidence: session flags from pi's own help output, version 0.80.10, captured the recorded snapshot (S3).\n\nEach flag becomes one short function, and the family gets its own cheat sheet in the `x-` style. This is the exact file built for the workshop (source S4, `demo/pi-utils.zsh`).\n\n``` text\npir() { pi --resume \"$@\"; }        # pick a session to resume\npic() { pi --continue \"$@\"; }      # continue the most recent session\npif() { pi --fork \"$@\"; }          # fork a session: pif <path|id>\npin() {                            # start a named session\n  local name=\"${1:?Usage: pin <name> [prompt...]}\"; shift\n  pi --name \"$name\" \"$@\"\n}\npit() { pi --no-session \"$@\"; }    # throwaway session\n```\n\n**Figure 7.** Source evidence: the new pi family, quoted from S4. A `pi-` cheat-sheet function completes the file.\n\n``` text\n$ zsh -n demo/pi-utils.zsh && echo \"syntax OK\"\nsyntax OK\n$ zsh -fc 'pi() { echo \"[stub pi] $@\"; }; source demo/pi-utils.zsh; pir --check'\n[stub pi] --resume --check\n```\n\n**Figure 8.** Derived display: the verification run from the recorded snapshot (S4), reformatted from the build log. A stub replaces the real binary, proving each helper passes the intended flags.\n\n**Evidence limit** The stub test proves flag wiring, not end-to-end behavior. A live `pir` only opens the session picker when pi has saved sessions on that machine. The sources also do not measure the \"five minutes\" figure; it is the presenter's estimate for this walkthrough.\n\nRun the same two commands against any wrapper file you write. Syntax check first, stub test second. If the stub echoes the flags you expected, load the file for real and watch `pir` open the picker. If it echoes something else, the bug is in your function, not in the agent — which is exactly where you want bugs to live.\n\n## Practical action\n\nApply the recipe to one agent CLI this week:\n\n1.  **Capture** the exact launch command you retype most, flags and all.\n2.  **Wrap** it: `unalias` guard, short function name, env pinning inside, `\"$@\"` at the end.\n3.  **Compose** the first family on top — resume is usually the highest-value action.\n4.  **Document** with a `<name>-` cheat-sheet function so the family stays discoverable.\n5.  **Verify** with `zsh -n`, then a stub test, before sourcing it in your real shell.\n\nSuccess looks like this: a week later, `which` shows functions instead of history searches, and the cheat sheet answers \"what was that helper called?\" without leaving the terminal. If a wrapper breaks after a CLI update, that is the drift caveat arriving on schedule — re-run the CLI's `--help` and adjust the one function that owns the changed flag."
}
