Skip to content

refactor(shell): collapse the zsh wrapper to one .zshenv and a precmd hook (STA-4786) - #15391

Merged
nwparker merged 7 commits into
mainfrom
neil/sta-4786-single-file-zsh-wrapper
Aug 20, 2026
Merged

nwparker merged 7 commits into
mainfrom
neil/sta-4786-single-file-zsh-wrapper

Conversation

@nwparker

@nwparker nwparker commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 27 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1261 $\color{#cf222e}{\Huge{\mathbf{−}}}$​2236 $\color{#cf222e}{\Huge{\mathbf{−}}}$​975
Prod 13 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​427 $\color{#cf222e}{\Huge{\mathbf{−}}}$​503 $\color{#cf222e}{\Huge{\mathbf{−}}}$​76

ELI5

To run its own code after your zsh config, Orca used to point ZDOTDIR at a directory of its own and keep it there for the whole of startup, sourcing each of your startup files by hand. Four generated files, and a fake ZDOTDIR sitting in place while the system /etc/zshrc ran.

Almost every zsh bug Orca has had traces back to that one decision. This replaces it: give ZDOTDIR straight back on the first lines, let zsh read the rest of your config exactly as it would with no wrapper at all, and do Orca's work from a precmd hook that runs once at the first prompt and then removes itself.

Why

/etc/zshrc assigns HISTFILE=${ZDOTDIR:-$HOME}/.zsh_history unconditionally. With Orca's ZDOTDIR live when that line runs, history landed inside Orca's own wrapper dir (#11044), and an epilogue existed to repair it. Hand ZDOTDIR back first and that line derives the user's own path by itself — the bug stops being reachable rather than being repaired.

The same is true of the rest of the family:

bug class why it existed after
#11044, history inside the wrapper dir /etc/zshrc ran under Orca's ZDOTDIR unreachable; nothing to repair
emulate sh in a user file hid every later wrapper file zsh's sourcehome() ignores ZDOTDIR in sh/ksh emulation only one wrapper file, read before any user file can change modes
two installed builds mixing files in one dir four files, any of which could come from either build one file; and #15285 content-addressed the desktop/daemon trees
#8003, a Windows-generated wrapper unusable under WSL via /mnt/c a generation-time path baked in as a ZDOTDIR fallback nothing re-points ZDOTDIR, so no path is baked at all

Their machinery goes with them. Eight of thirteen exported blocks in shell-templates.ts are deleted, including both drifted discovery bodies — unifying those closes the "reconciling the two is a follow-up" note the file has carried since #15245 — and the relay's separate ORCA_USER_ZDOTDIR shape. Generated zsh drops from 819 lines across twelve files to 424 across three, and --exclude lists, helper duplication and the epilogue once-flag go with it. Net −1,295 lines.

What Changed

buildZshStartupHook replaces buildZshStartupWrapperFiles — one string instead of four, and the spec shrinks from nine fields to five (zshDir, zshenvStrategy, homeExpression, skipUserZshrcWhenHomeIsWrapperDir all become meaningless once nothing re-points ZDOTDIR).

Two things the design has to get right, both found by running it rather than reasoning about it:

  • Every function is defined above the source of the user's .zshenv. A user file ending in emulate sh puts the rest of the wrapper under sh parsing rules. The first prototype died there with parse error near '\n' — silently, leaving the pane unwrapped. Function bodies are parsed at definition time, so defining them first makes them immune; emulate -L zsh inside the hook restores option semantics at call time. The { } always { } compound is parsed as a unit, so the registration in its always block is safe too.
  • ORCA_ORIG_ZDOTDIR is vetted, not trusted. The launch config only sets it when it resolved a usable dir — but a pane inherits its parent's environment too, so a stale value from an older build can arrive on its own and would point ZDOTDIR back at a wrapper dir. The ownership check Node applies now also runs in the shell, where that route is visible. Identification stays positive: a stamped marker file, Orca's own path shape, or a dir holding no zsh startup file at all.

Orca stops inventing a ZDOTDIR. resolveInheritedZdotdir returns null rather than falling back to $HOME, so a user with no ZDOTDIR ends up with none. ZDOTDIR=$HOME and unset are identical to zsh reading startup files, but they are different environments for everything the pane launches. The equivalence suite below is what caught this.

Hook removal vs substitution. With markers on, the hook substitutes itself for the permanent OSC 133 precmd, preserving array position. With markers off it removes itself, so a history-only pane leaves no Orca name in the user's precmd_functions — the "observably identical to unwrapped" property, now asserted directly. I verified on zsh 5.9 that self-removal mid-sweep skips no later hook, from the head, middle and tail of the array; the earlier draft claimed the opposite in a comment and was wrong.

Testing

A PTY harness was mandatory, not a preference. Everything Orca owns now runs from a precmd hook, and zsh -i -c '<probe>' never reaches a prompt — so the existing probes could not have exercised this design at all. They would have reported the wrapper doing nothing, for the right reason, at the wrong question. src/main/zsh-startup-hook-pty-harness.ts drives a real zsh to its first prompt and reports through a file rather than stdout, which a PTY echoes.

Against real frameworks, on a real PTY — all five features (identity, ready, OSC 133 A/C/D, history, overlay). Each config also deliberately fought the overlay with export CODEX_HOME=/user/codex and export PATH=/user/bin:$PATH:

config identity ready 133 A/C/D scoped HISTFILE ZDOTDIR CODEX_HOME PATH[0]
bare yes yes yes yes user's Orca's Orca's shim
oh-my-zsh yes yes yes yes user's Orca's Orca's shim
powerlevel10k yes yes yes yes user's Orca's Orca's shim
p10k + instant prompt yes yes yes yes user's Orca's Orca's shim
prezto yes yes yes yes user's Orca's Orca's shim

Controls (same configs, unwrapped) show none of the markers and the user's own values, so the harness is not reporting false positives. Framework sources were also read directly: oh-my-zsh, powerlevel10k and prezto all splice precmd_functions rather than replacing it, so the one config shape that drops the hook is not something they do.

The hostile matrix moved in our favour. The two emulate sh cases the old design loses now pass:

user config before after
.zshenv ends emulate sh unwrapped, no ready scoped
.zprofile ends emulate sh unwrapped, no ready scoped
.zshrc ends emulate sh scoped scoped
setopt no_unset / ksharrays / typeset -r REPLY scoped scoped
.zshrc runs precmd_functions=() scoped unwrapped, and leaks nothing

The one loss degrades to exactly an unwrapped pane. ORCA_HISTFILE is consumed in .zshenv rather than in the hook precisely so a dropped hook cannot leak it to the pane's children (#11146's class).

Test changes, stated plainly. Three real-zsh files (33 tests) asserted on ORCA_ORIG_ZDOTDIR — the output of Orca's shell-side ZDOTDIR discovery. That discovery is gone; zsh resolves natively, so there is no Orca-computed value left to assert on. They are replaced by zsh-startup-hook-user-config-equivalence.live-shell.test.ts: 21 cases, each run twice on a PTY, wrapped and unwrapped, required to agree on ZDOTDIR, PATH, what the config exported, and whether the shell reached a prompt at all. That is stricter than the originals — it pins the pane to whatever the host's own zsh does rather than to values hardcoded here — and it covers every case they did (XDG dirs, spaces, single quotes, trailing slashes, whitespace-only, empty, nonexistent, set-twice, sourced-from-another-file, $HOME, conditional unset, syntax error, set -e/set -u, globs, unset HOME, exit, typeset -U path at top level). The #8003 and %x cases are gone because the baked literal they defended is gone; a new test asserts no generation-time path appears in the hook at all.

The relay variant (no OSC 133, remote CLI bin dir) now has live coverage it never had. The mixed-build proof moved to the relay, the one writer still on a fixed path after #15285.

Numbers. Time to first prompt — the measure that includes the hook — median of 40, five rounds, real PTY, user .zshenv + .zprofile + .zshrc present:

arm ms overhead
unwrapped 11.44 —
four files (current main) 12.23 +0.79
one file + precmd 11.41 −0.02

Three runs of that benchmark put the one-file arm at +0.55, +0.49 and −0.02 ms — every one inside the run-to-run spread, while the four-file arm lands above unwrapped every time (+0.79 to +1.33). The honest claim is not a point estimate: the four-file wrapper is measurably slower than an unwrapped shell and the one-file hook is not distinguishable from one. The last run is after the __orca_usable_zdotdir ownership check was added, so that check costs nothing measurable either.

Commands: npx tsc --noEmit -p config/tsconfig.node.json, npx oxlint src/ config/, npx oxfmt --check, and npx vitest run over the whole repo — 56,241 passed. src/shared/wsl-exec-mode-separator.test.ts fails identically with this branch stashed, i.e. it is red on main and not touched here.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

Not covered: macOS zsh 5.9 only — Linux and Windows/WSL hosts, and zsh older than 5.9, are untested here. I tried to exercise the WSL path on a real Windows host over the remote server, but its distro has no zsh installed; #8003's class is removed by construction rather than by test on that host.

Linked Issue

STA-4786 — https://linear.app/stably/issue/STA-4786 (child of STA-4682)

Fixes #

Visual Proof

N/A — no UI surface. Generated shell startup files and the code that writes them.

Review

Remote wire compatibility

Nothing crosses the wire. ORCA_SHELL_FEATURES and ORCA_ORIG_ZDOTDIR travel from a relay process into a PTY it spawns on the same host, never over an RPC or a stream frame, and the wrapper is regenerated on launch by whichever host runs the shell. ORCA_ZSHENV_SOURCE_DIR is retired; the wrapper unsets any inherited copy so a stale one cannot linger in a pane.

Rollout

The relay writes a fixed path shared across builds, so an older build's .zprofile/.zshrc/.zlogin can sit beside the new .zshenv. They are inert — the hook hands ZDOTDIR back before zsh looks for them — and generation deliberately does not delete them, because an older build checks for all four before calling its tree complete. Deleting would make it rewrite its own .zshenv over ours, and an older .zshenv points ZDOTDIR at a directory that would then hold no .zshrc, costing the user their whole config. Both halves are pinned by a live test.

Cross-platform

zsh only. bash and fish generation is untouched; the block the bash rcfile shares was renamed BASH_HISTFILE_RESTORE_BLOCK now that it is the only consumer. Windows and PowerShell are unaffected.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Security — the handback target is vetted with the same positive-identification rules Node uses, now on the one route Node cannot see (an inherited env var). Nothing new is read from or written to disk.
  • Performance — a net reduction: three fewer files sourced and no $(emulate) fork, against one precmd call that removes itself.
  • Backwards compatibility — the wrapper is regenerated on launch; a stale tree from an older build is either replaced or ignored, per the rollout note above.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@coderabbitai

coderabbitai Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR replaces generated zsh .zprofile, .zshrc, and .zlogin wrappers with one .zshenv startup hook. The hook restores usable ZDOTDIR, sources user configuration, captures history state, and defers Orca initialization. Local, daemon, and relay launch paths use the new hook contract. Tests now use a shared zsh PTY harness and cover startup equivalence, hostile configuration, history, markers, stale wrappers, and relay behavior. Workflow discovery includes the new live-shell test.

Merge Risk: 🟡 Moderate · up to f38ec

This refactor changes zsh startup-directory handling, and an unresolved edge case may cause valid empty ZDOTDIR values to be discarded, loading HOME-based startup files instead of the user's intended configuration. Merge should wait for that behavior to be fixed or explicitly accepted; the remaining concerns are bounded test-readiness follow-ups.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 61.76% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: replacing the four-file zsh wrapper with one .zshenv and a precmd hook.
Description check ✅ Passed The description covers the required sections, linked issue, rationale, testing, compatibility, rollout, and checklist; Visual Proof is correctly marked N/A.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (5)
src/main/zsh-startup-hook-pty-harness.ts (1)

102-104: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Move or correct this comment.

The comment explains a PROMPT override, but this line only injects ORCA_PTY_SENTINEL into the environment. The override happens at line 143, which already has its own PS1 explanation. Reword this comment to state why the sentinel travels through the environment.

src/main/zsh-startup-hook-user-config-equivalence.live-shell.test.ts (1)

266-271: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Prefer an explicit skip over an early return.

On a host with no zsh, the early return reports each case as passed. Sibling files in this layer use const itWithZsh = hasZsh ? it : it.skip. Use the same pattern here so the run reports skips.

src/main/shell-templates.ts (1)

44-64: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Condense the template rationale.

This 21-line comment is not concise. Keep the non-obvious invariant near the code. Move detailed history to an issue or design document.

As per coding guidelines: “Comments must be concise, non-obvious, and brief—prefer one line.”

Source: Coding guidelines

src/main/providers/local-pty-shell-ready-wrapper-fileset.ts (1)

36-43: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Build the wrapper paths with path.join.

The changed lines join path segments with a literal /. The daemon sibling src/main/daemon/daemon-shell-ready-wrapper-fileset.ts uses join for the same fileset. Use join here too so the two filesets stay identical in path handling.

As per coding guidelines: "Use path.join or Electron/Node path utilities for file paths; never assume / or \."

♻️ Proposed refactor
 export function buildLocalShellReadyWrapperFiles(root: string): readonly ShellWrapperFile[] {
-  const zshDir = `${root}/zsh`
+  const zshDir = join(root, 'zsh')
   return [
-    [`${zshDir}/.zshenv`, buildZshStartupHook(getLocalZshWrapperSpec())],
-    [`${zshDir}/${ZSH_WRAPPER_DIR_MARKER_FILE}`, ZSH_WRAPPER_DIR_MARKER_CONTENT],
-    [`${root}/bash/rcfile`, getBashShellReadyRcfileContent()]
+    [join(zshDir, '.zshenv'), buildZshStartupHook(getLocalZshWrapperSpec())],
+    [join(zshDir, ZSH_WRAPPER_DIR_MARKER_FILE), ZSH_WRAPPER_DIR_MARKER_CONTENT],
+    [join(root, 'bash', 'rcfile'), getBashShellReadyRcfileContent()]
   ]
 }

Note: the generated file content is hashed into the root, and the path form also feeds resolveShellWrapperRoot. Confirm that switching to join does not change the computed root for existing installs.

Source: Coding guidelines

src/main/shell-startup-feature-channel.test.ts (1)

19-19: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Minor import cleanup: reuse the existing hasZsh and ZSH_PATH exports from the PTY harness instead of duplicating shell probes, and merge the separate vitest imports in the equivalence test.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1bd55390-6745-4841-aa84-ba51efd9642f

📥 Commits

Reviewing files that changed from the base of the PR and between 1b5cc00 and b719ffd.

📒 Files selected for processing (40)
  • .github/workflows/pr.yml
  • config/scripts/pr-workflow-parallelism.test.mjs
  • src/main/__fixtures__/shell-wrapper-snapshots/daemon-zsh-zlogin.txt
  • src/main/__fixtures__/shell-wrapper-snapshots/daemon-zsh-zprofile.txt
  • src/main/__fixtures__/shell-wrapper-snapshots/daemon-zsh-zshenv.txt
  • src/main/__fixtures__/shell-wrapper-snapshots/daemon-zsh-zshrc.txt
  • src/main/__fixtures__/shell-wrapper-snapshots/local-zsh-zlogin.txt
  • src/main/__fixtures__/shell-wrapper-snapshots/local-zsh-zprofile.txt
  • src/main/__fixtures__/shell-wrapper-snapshots/local-zsh-zshenv.txt
  • src/main/__fixtures__/shell-wrapper-snapshots/local-zsh-zshrc.txt
  • src/main/__fixtures__/shell-wrapper-snapshots/relay-zsh-zlogin.txt
  • src/main/__fixtures__/shell-wrapper-snapshots/relay-zsh-zprofile.txt
  • src/main/__fixtures__/shell-wrapper-snapshots/relay-zsh-zshenv.txt
  • src/main/__fixtures__/shell-wrapper-snapshots/relay-zsh-zshrc.txt
  • src/main/daemon/daemon-shell-ready-wrapper-fileset.ts
  • src/main/daemon/daemon-zsh-shell-ready-wrapper-spec.ts
  • src/main/daemon/shell-ready.test.ts
  • src/main/daemon/shell-ready.ts
  • src/main/ipc/pty-wsl-cwd-validation.test.ts
  • src/main/providers/__tests__/shell-ready-framework-example.test.ts
  • src/main/providers/local-pty-shell-ready-wrapper-fileset.ts
  • src/main/providers/local-pty-shell-ready-wrapper-generation.test.ts
  • src/main/providers/local-pty-shell-ready-wrapper-generation.ts
  • src/main/providers/local-pty-shell-ready-zsh-launch-environment.test.ts
  • src/main/providers/local-pty-shell-ready-zsh-startup-file-behavior.test.ts
  • src/main/providers/local-pty-shell-ready-zsh-zdotdir-discovery.test.ts
  • src/main/providers/local-pty-shell-ready-zsh-zdotdir-normalization.test.ts
  • src/main/providers/local-pty-shell-ready.ts
  • src/main/shell-startup-feature-channel.test.ts
  • src/main/shell-templates.ts
  • src/main/shell-wrapper-generated-file-snapshot.test.ts
  • src/main/zsh-scoped-histfile.live-shell.test.ts
  • src/main/zsh-startup-hook-pty-harness.ts
  • src/main/zsh-startup-hook-user-config-equivalence.live-shell.test.ts
  • src/main/zsh-startup-wrapper-builder.ts
  • src/main/zsh-wrapper-dir-ownership.ts
  • src/main/zsh-wrapper-version-mismatch.live-shell.test.ts
  • src/relay/pty-shell-launch.test.ts
  • src/relay/pty-shell-launch.ts
  • src/relay/pty-shell-overlay-wrappers.ts
💤 Files with no reviewable changes (12)
  • src/main/fixtures/shell-wrapper-snapshots/daemon-zsh-zlogin.txt
  • src/main/fixtures/shell-wrapper-snapshots/daemon-zsh-zshrc.txt
  • src/main/fixtures/shell-wrapper-snapshots/relay-zsh-zprofile.txt
  • src/main/fixtures/shell-wrapper-snapshots/local-zsh-zshrc.txt
  • src/main/fixtures/shell-wrapper-snapshots/relay-zsh-zlogin.txt
  • src/main/fixtures/shell-wrapper-snapshots/relay-zsh-zshrc.txt
  • src/main/providers/local-pty-shell-ready-zsh-zdotdir-normalization.test.ts
  • src/main/providers/local-pty-shell-ready-zsh-startup-file-behavior.test.ts
  • src/main/fixtures/shell-wrapper-snapshots/local-zsh-zlogin.txt
  • src/main/providers/local-pty-shell-ready-zsh-zdotdir-discovery.test.ts
  • src/main/fixtures/shell-wrapper-snapshots/local-zsh-zprofile.txt
  • src/main/fixtures/shell-wrapper-snapshots/daemon-zsh-zprofile.txt

Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.

Comment on lines +541 to 557
it('sources the user .zshenv at wrapper top level, not inside a function', async () => {
// Why: PR #1737 sourced .zshenv in a wrapper function, breaking `typeset -U
// path`. Top-level sourcing is still the contract; only the surrounding
// machinery went away.
const { getShellReadyLaunchConfig } = await importFreshLocalPtyShellReady()

getShellReadyLaunchConfig('/bin/zsh')

const zshenv = readFileSync(join(getShellReadyWrapperRoot(), 'zsh', '.zshenv'), 'utf8')

// Save spawn-env value before sourcing user .zshenv
expect(zshenv.indexOf('_orca_user_zdotdir="$_orca_resolved_config_dir"')).toBeLessThan(
zshenv.indexOf('source "${_orca_zshenv_path}"')
expect(zshenv).toContain('builtin source -- "$_orca_user_zshenv"')
// Every function the hook needs is defined above the source, so a user
// `emulate sh` cannot leave the rest of this file unparseable.
expect(zshenv.indexOf('__orca_deferred_init() {')).toBeLessThan(
zshenv.indexOf('builtin source -- "$_orca_user_zshenv"')
)

// Fallback chain: discovered → normalized spawn-env path → HOME
expect(zshenv).toContain('${_orca_discovered_zdotdir:-${_orca_user_zdotdir:-$HOME}}')
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Ordering assertions can pass when the deferred-init definition is absent. Both tests compare indexOf results without first asserting that __orca_deferred_init() { exists. indexOf returns -1 for a missing substring, and -1 is less than any real index, so the ordering contract is not enforced if the definition line changes shape.

  • src/main/providers/local-pty-shell-ready-wrapper-generation.test.ts#L541-L557: add expect(zshenv).toContain('__orca_deferred_init() {') before the toBeLessThan comparison.
  • src/main/daemon/shell-ready.test.ts#L705-L719: add the same toContain check before the toBeLessThan comparison.
📍 Affects 2 files
  • src/main/providers/local-pty-shell-ready-wrapper-generation.test.ts#L541-L557 (this comment)
  • src/main/daemon/shell-ready.test.ts#L705-L719

Comment on lines +246 to +250
expect(output).toMatch(MARKERS.identity)
expect(output).toContain(MARKERS.ready)
expect(output).toContain(MARKERS.promptStart)
expect(output).toContain(MARKERS.commandStart)
expect(output).toMatch(MARKERS.commandDone)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Three of these marker assertions cannot fail.

MARKERS.ready, MARKERS.promptStart, and MARKERS.commandStart are empty strings in src/main/zsh-startup-hook-pty-harness.ts. toContain('') always passes, so lines 247-249 assert nothing. Fix the constants at the root cause.

Comment on lines +412 to +416
expect(output).toContain(MARKERS.ready)
// Remote panes get their command lifecycle from the bash rcfile, so the
// zsh variant must stay silent here.
expect(output).not.toContain(MARKERS.promptStart)
expect(output).not.toContain(MARKERS.commandStart)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

This test cannot pass while MARKERS.promptStart and MARKERS.commandStart are empty.

expect(output).not.toContain('') always fails, because every string contains the empty string. Lines 415-416 therefore fail on every run. Line 412 asserts nothing for the same reason. Set the marker constants in src/main/zsh-startup-hook-pty-harness.ts to the real OSC sequences.

Comment on lines +55 to 58
export function resolveInheritedZdotdir(env: EnvLike): string | null {
return (
usableInheritedZdotdir(env.ZDOTDIR) ??
usableInheritedZdotdir(env.ORCA_ORIG_ZDOTDIR) ??
env.HOME ??
homeFallback
usableInheritedZdotdir(env.ZDOTDIR) ?? usableInheritedZdotdir(env.ORCA_ORIG_ZDOTDIR) ?? null
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Preserve valid empty ZDOTDIR values. Both validators treat an empty configuration directory as unusable. zsh treats it as valid and does not load $HOME startup files.

  • src/main/zsh-wrapper-dir-ownership.ts#L55-L58: forward non-Orca-owned inherited ZDOTDIR values without requiring a startup file.
  • src/main/shell-templates.ts#L65-L85: use the same rule in __orca_usable_zdotdir.
📍 Affects 2 files
  • src/main/zsh-wrapper-dir-ownership.ts#L55-L58 (this comment)
  • src/main/shell-templates.ts#L65-L85

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/main/zsh-startup-hook-pty-harness.ts (1)

65-67: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Preserve empty values in probe output.

Line 66 uses :-UNSET, which applies to unset and empty parameters. HISTFILE='' is reported as HISTFILE=<UNSET>. The equivalence tests cannot detect a change between an empty and an unset history variable.

Test parameter existence separately. Emit <> when the parameter is set to an empty value. Add coverage for both states.

Proposed fix
-  const prints = report.map((name) => `print -r -- "${name}=<\${${name}:-UNSET}>";`).join(' ')
+  const prints = report
+    .map(
+      (name) =>
+        `if (( \${+${name}} )); then print -r -- "${name}=<\${${name}}>"; else print -r -- "${name}=<UNSET>"; fi;`
+    )
+    .join(' ')
🧹 Nitpick comments (1)
src/main/zsh-startup-hook-pty-harness.ts (1)

120-127: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Shorten the explanatory comments.

Keep one concise comment for each non-obvious decision. Move detailed rationale to test documentation if it must be retained.

As per coding guidelines, “Comments must be concise, non-obvious, and brief—prefer one line.”

Also applies to: 153-160, 176-186

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 38ac2916-3831-4e98-8517-057accb40ac7

📥 Commits

Reviewing files that changed from the base of the PR and between b719ffd and 4bc500d.

📒 Files selected for processing (2)
  • src/main/zsh-startup-hook-pty-harness.ts
  • src/main/zsh-startup-hook-user-config-equivalence.live-shell.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/zsh-startup-hook-user-config-equivalence.live-shell.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.

Comment on lines +161 to +172
async function waitForQuiet(quietMs: number): Promise<void> {
while (!hasExited) {
const idleFor = Date.now() - lastDataAt
if (idleFor >= quietMs) {
return
}
await new Promise((resolve) => setTimeout(resolve, quietMs - idleFor))
}
}

try {
await Promise.race([waitForQuiet(250), exited, timedOut])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Do not use output idleness as prompt readiness.

A shell can be silent while startup code still runs. For example, .zshrc can run sleep 1; read reply. waitForQuiet(250) returns before read runs, and the later PS1=... input becomes the reply. The harness then waits for a sentinel prompt that never appears.

Use a test-defined readiness marker or an explicit prompt-response contract before injecting commands. Add a delayed interactive-startup case.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/main/zsh-scoped-histfile.live-shell.test.ts (1)

343-348: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Condense the test rationale comments.

Keep the host-dependent contract in one sentence. Remove setup detail that the assertions already show.

  • src/main/zsh-scoped-histfile.live-shell.test.ts#L343-L348: Reduce this rationale to one sentence that states system startup can override HISTFILE, so the test compares an unwrapped shell.
  • src/main/shell-startup-feature-channel.test.ts#L377-L379: Reduce this rationale to one sentence that states host configuration can install LINEINIT, so the test compares an unwrapped shell.

As per coding guidelines: “Comments must be concise, non-obvious, and brief—prefer one line.”

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c1d73390-d482-4fc8-9b69-9cef7db55420

📥 Commits

Reviewing files that changed from the base of the PR and between 4bc500d and d4f517a.

📒 Files selected for processing (2)
  • src/main/shell-startup-feature-channel.test.ts
  • src/main/zsh-scoped-histfile.live-shell.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.

@nwparker

Copy link
Copy Markdown
Contributor Author

CI state: every lane this change owns is green — shell contracts, static analysis, typecheck, package. 46 passed, 4 skipped.

The four red shards (tests node 24|26 6/16 and 14/16) are not from this branch. They fail identically on #15392 and #15393, which touch nothing shell-related, and the failure is a wall-clock timeout rather than an assertion:

WslTranscriptFsError: WSL transcript files are temporarily unavailable because
filesystem access is taking too long.
  ❯ runWslTranscriptFsTask src/main/native-chat/wsl-transcript-fs-gate.ts:338

src/main/ai-vault/session-scanner-parse-wsl-stall.test.ts and session-scanner-index-cache-wsl-stall.test.ts pass locally here. They land in the same shards every run because shard assignment is stable by filename, which reads as "deterministic" but is a load-sensitive gate timing out on a busy runner. verify is red only because it aggregates those shards.

Worth its own ticket rather than a retry-until-green on unrelated PRs.

First run's shell-contract failures were real and are fixed, both from driving a real PTY where the old probes drove a pipe:

  • A host whose global zshrc runs compinit over directories it considers insecure stops startup and asks. A pipe-backed zsh -i -c never saw the question; a PTY sits at it until the timeout. The harness answers it, and waits for the shell to fall quiet before typing so the question cannot eat the PS1 line. ZSH_DISABLE_COMPFIX does not help — that is an oh-my-zsh convention and plain compinit ignores it, which I confirmed by reproducing the prompt locally rather than assuming.
  • Two of my own assertions encoded macOS behaviour instead of Orca's contract: LINEINIT pinned to none (that runner's global config installs its own zle-line-init widget), and the dropped-precmd_functions case asserting HISTFILE was no longer scoped (macOS /etc/zshrc overwrites HISTFILE; Ubuntu does not, so the spawn-env value survives with or without the hook). Both are now equivalence comparisons against an unwrapped pane, which is host-independent and stricter.

One limitation now stated in the test file rather than left to be discovered: the emulate sh cases are honest on every host but only discriminate where the system zshrc clobbers HISTFILE. On CI's Ubuntu the load-bearing assertion is ORCA_HISTFILE having been consumed.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/main/zsh-startup-hook-user-config-equivalence.live-shell.test.ts (1)

252-256: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Condense the test rationale comments.

These blocks explain historical behavior and implementation mechanics in detail. Keep only the non-obvious reason for each regression test in one concise comment.

As per coding guidelines: “Comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code.”

Also applies to: 302-307, 327-334, 357-361, 376-382, 399-402, 423-429, 451-454, 466-468

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a2dd79d6-2bf3-4f63-bdb0-cf8ca1f14504

📥 Commits

Reviewing files that changed from the base of the PR and between d4f517a and f38ecd8.

📒 Files selected for processing (1)
  • src/main/zsh-startup-hook-user-config-equivalence.live-shell.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.

… hook (STA-4786)

Orca needs to run code after the user's own zsh startup files. It bought that by
keeping ZDOTDIR pointed at its own wrapper dir for the whole of startup and
sourcing each user file by hand -- four generated files per transport, with a
fake ZDOTDIR live while /etc/zshrc ran. That single decision is the root of a
whole bug family:

- /etc/zshrc assigns HISTFILE=${ZDOTDIR:-$HOME}/.zsh_history unconditionally, so
  history landed inside Orca's own dir (#11044), and an epilogue had to repair it.
- zsh's sourcehome() ignores ZDOTDIR once the shell is in sh/ksh emulation, so a
  user .zshenv or .zprofile ending in `emulate sh` hid every later wrapper file.
  The emulation degrade blocks and their forked $(emulate) probes exist for that.
- One wrapper dir shared by two installed builds could mix files from both, so
  every generated file had to redefine the helpers it called.
- The baked generation-time ZDOTDIR literal is unusable when a Windows-generated
  wrapper is sourced inside WSL via /mnt/c (#8003), so the runtime path had to be
  re-derived from %x.

The wrapper now hands ZDOTDIR back on its first lines and defers Orca's work to a
precmd hook that runs at the first prompt -- after .zprofile, /etc/zshrc, .zshrc
and .zlogin, every one of which zsh reads from the user's own directory exactly
as in an unwrapped shell. Each bug above stops being reachable rather than being
repaired, and their machinery goes with them: eight of thirteen exported blocks in
shell-templates.ts, both drifted discovery bodies (unifying them closes the
"reconciling the two is a follow-up" note the file carried), and the relay's
separate ORCA_USER_ZDOTDIR shape. Generated zsh drops from 819 lines across
twelve files to 143 in three.

Two things the design has to get right, both found by running it rather than
reasoning about it:

- Every function is defined ABOVE the source of the user's .zshenv. A user file
  ending in `emulate sh` puts the rest of the wrapper under sh parsing rules, and
  the first prototype died there with `parse error near '\n'` -- silently, leaving
  the pane unwrapped. Function bodies are parsed at definition time.
- ORCA_ORIG_ZDOTDIR is vetted, not trusted. The launch config only sets it when it
  resolved a usable dir, but a pane inherits its parent's environment too, so a
  stale value from an older build can arrive on its own and would point ZDOTDIR
  back at a wrapper dir. The ownership check Node applies now also runs in the
  shell, where that route is visible.

Orca also stops inventing a ZDOTDIR: where the user has none, ORCA_ORIG_ZDOTDIR is
absent and the pane ends with ZDOTDIR unset, as an unwrapped login zsh does.

Verified on real zsh over a real PTY -- necessary, because a precmd hook never runs
in a shell started with -c, so the existing `zsh -i -c` probes could not have
exercised this design at all. src/main/zsh-startup-hook-pty-harness.ts drives the
shell to a prompt and reports through a file rather than stdout, which a PTY echoes.
The relay writes its own variant -- no OSC 133, remote CLI bin dir instead of the
agent-teams shim -- and it had no live coverage. It used to carry a second ZDOTDIR
shape as well, which is how it drifted from the desktop template in the first
place; now the spec flags are the only difference, and this pins that.
…r trees

#15285 landed content-addressed wrapper roots and a per-transport fileset module
while this branch was in flight. The fileset modules are now the single place the
tree is described, so 'only .zshenv' is stated once per transport and the
required-paths check follows from it rather than repeating the list.
…wrapper path

#15285 content-addressed the desktop and daemon trees, so two builds can no
longer write the same directory there and the scenario this file covers became
unreachable on those paths. The relay still writes a fixed ~/.orca-relay/
shell-ready, so that is where the hazard survives and where the proof belongs.
Two CI-only failures, both from driving a real PTY where the old probes drove a
pipe:

- A host whose global zshrc runs `compinit` over directories it considers
  insecure stops startup and ASKS. A pipe-backed `zsh -i -c` never saw the
  question; a PTY sits at it until the timeout. The harness now answers it.
  ZSH_DISABLE_COMPFIX does not help -- that is an oh-my-zsh convention and plain
  compinit ignores it, which I confirmed by reproducing the prompt locally.
- The PS1 line was typed at t=0, so on such a host the question consumed it as
  its answer. The harness now waits for the shell to fall quiet first, which
  also stops a slow prompt framework racing the same write.

Also merges a duplicate vitest import the native code-quality audit flagged.
Two of them hardcoded what my machine does rather than what Orca owes:

- LINEINIT was pinned to 'none'. A host whose global zsh config installs its own
  zle-line-init widget has one either way; the contract is that it looks the same
  wrapped as unwrapped, which the assertion beside it already states.
- The dropped-precmd_functions case asserted HISTFILE was no longer the scoped
  path. Whether the scoped value survives at all is the host's call: macOS
  /etc/zshrc overwrites HISTFILE so it does not, and a host with no such
  assignment keeps whatever the spawn env set. Now compared against an unwrapped
  pane given the same env, which is the real contract on both.

Also notes, where the emulation cases live, that they only discriminate on a host
whose system zshrc clobbers HISTFILE -- on CI's Ubuntu the load-bearing assertion
is ORCA_HISTFILE having been consumed.
Archaeology over the removed blocks: each existed for a bug, so each needs the
bug shown to be unreachable rather than just the code gone. Six restored or added,
each naming the change that introduced the behaviour.

- #8003, twice: the wrapper sourced from a relocated root, and from a non-ASCII
  (token-range) one. The old file baked its generation-time path in and had to
  re-derive the runtime one from %x to avoid using it; this one bakes nothing.
  Both runs assert ORCA_SHELL_FEATURES came back consumed, so 'the user's .zshrc
  loaded' cannot pass on a pane that never read the wrapper at all.
- #4667: user startup files must see their OWN ZDOTDIR while they run, or plugin
  and theme lookups resolve into Orca's dir. The old wrapper swapped ZDOTDIR
  around each source; this one never takes it away, and the values now have to
  match an unwrapped pane's.
- #1947: a user .zshenv that returns early.
- #15258: an inherited ZDOTDIR that is an Orca wrapper dir must be refused. CI
  proved this route is live -- the launch config only sets ORCA_ORIG_ZDOTDIR when
  it resolved a usable dir, but a pane inherits its parent's environment too.
- #11044/#11146: a nested Orca inherits neither cross-process channel and no
  ZDOTDIR of Orca's, which is what makes #11044's plain shape unreachable rather
  than repaired. Verified the child-env probe detects a real leak before trusting
  it to report the absence of one.
@nwparker
nwparker force-pushed the neil/sta-4786-single-file-zsh-wrapper branch from f38ecd8 to 5bd6139 Compare August 19, 2026 06:38
@nwparker
nwparker merged commit c72a4ee into main Aug 20, 2026
107 of 109 checks passed
@nwparker
nwparker deleted the neil/sta-4786-single-file-zsh-wrapper branch August 20, 2026 05:37
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 21, 2026
… hook (STA-4786) (stablyai#15391)

* refactor(shell): collapse the zsh wrapper to one .zshenv and a precmd hook (STA-4786)

Orca needs to run code after the user's own zsh startup files. It bought that by
keeping ZDOTDIR pointed at its own wrapper dir for the whole of startup and
sourcing each user file by hand -- four generated files per transport, with a
fake ZDOTDIR live while /etc/zshrc ran. That single decision is the root of a
whole bug family:

- /etc/zshrc assigns HISTFILE=${ZDOTDIR:-$HOME}/.zsh_history unconditionally, so
  history landed inside Orca's own dir (stablyai#11044), and an epilogue had to repair it.
- zsh's sourcehome() ignores ZDOTDIR once the shell is in sh/ksh emulation, so a
  user .zshenv or .zprofile ending in `emulate sh` hid every later wrapper file.
  The emulation degrade blocks and their forked $(emulate) probes exist for that.
- One wrapper dir shared by two installed builds could mix files from both, so
  every generated file had to redefine the helpers it called.
- The baked generation-time ZDOTDIR literal is unusable when a Windows-generated
  wrapper is sourced inside WSL via /mnt/c (stablyai#8003), so the runtime path had to be
  re-derived from %x.

The wrapper now hands ZDOTDIR back on its first lines and defers Orca's work to a
precmd hook that runs at the first prompt -- after .zprofile, /etc/zshrc, .zshrc
and .zlogin, every one of which zsh reads from the user's own directory exactly
as in an unwrapped shell. Each bug above stops being reachable rather than being
repaired, and their machinery goes with them: eight of thirteen exported blocks in
shell-templates.ts, both drifted discovery bodies (unifying them closes the
"reconciling the two is a follow-up" note the file carried), and the relay's
separate ORCA_USER_ZDOTDIR shape. Generated zsh drops from 819 lines across
twelve files to 143 in three.

Two things the design has to get right, both found by running it rather than
reasoning about it:

- Every function is defined ABOVE the source of the user's .zshenv. A user file
  ending in `emulate sh` puts the rest of the wrapper under sh parsing rules, and
  the first prototype died there with `parse error near '\n'` -- silently, leaving
  the pane unwrapped. Function bodies are parsed at definition time.
- ORCA_ORIG_ZDOTDIR is vetted, not trusted. The launch config only sets it when it
  resolved a usable dir, but a pane inherits its parent's environment too, so a
  stale value from an older build can arrive on its own and would point ZDOTDIR
  back at a wrapper dir. The ownership check Node applies now also runs in the
  shell, where that route is visible.

Orca also stops inventing a ZDOTDIR: where the user has none, ORCA_ORIG_ZDOTDIR is
absent and the pane ends with ZDOTDIR unset, as an unwrapped login zsh does.

Verified on real zsh over a real PTY -- necessary, because a precmd hook never runs
in a shell started with -c, so the existing `zsh -i -c` probes could not have
exercised this design at all. src/main/zsh-startup-hook-pty-harness.ts drives the
shell to a prompt and reports through a file rather than stdout, which a PTY echoes.

* test(shell): cover the relay variant of the zsh hook in a real shell

The relay writes its own variant -- no OSC 133, remote CLI bin dir instead of the
agent-teams shim -- and it had no live coverage. It used to carry a second ZDOTDIR
shape as well, which is how it drifted from the desktop template in the first
place; now the spec flags are the only difference, and this pins that.

* fix(shell): rebase the single-file hook onto content-addressed wrapper trees

stablyai#15285 landed content-addressed wrapper roots and a per-transport fileset module
while this branch was in flight. The fileset modules are now the single place the
tree is described, so 'only .zshenv' is stated once per transport and the
required-paths check follows from it rather than repeating the list.

* test(shell): point the mixed-build proof at the relay, the one fixed wrapper path

stablyai#15285 content-addressed the desktop and daemon trees, so two builds can no
longer write the same directory there and the scenario this file covers became
unreachable on those paths. The relay still writes a fixed ~/.orca-relay/
shell-ready, so that is where the hazard survives and where the proof belongs.

* fix(test): make the zsh PTY harness survive a startup that stops to ask

Two CI-only failures, both from driving a real PTY where the old probes drove a
pipe:

- A host whose global zshrc runs `compinit` over directories it considers
  insecure stops startup and ASKS. A pipe-backed `zsh -i -c` never saw the
  question; a PTY sits at it until the timeout. The harness now answers it.
  ZSH_DISABLE_COMPFIX does not help -- that is an oh-my-zsh convention and plain
  compinit ignores it, which I confirmed by reproducing the prompt locally.
- The PS1 line was typed at t=0, so on such a host the question consumed it as
  its answer. The harness now waits for the shell to fall quiet first, which
  also stops a slow prompt framework racing the same write.

Also merges a duplicate vitest import the native code-quality audit flagged.

* fix(test): stop the live-shell assertions assuming macOS host behaviour

Two of them hardcoded what my machine does rather than what Orca owes:

- LINEINIT was pinned to 'none'. A host whose global zsh config installs its own
  zle-line-init widget has one either way; the contract is that it looks the same
  wrapped as unwrapped, which the assertion beside it already states.
- The dropped-precmd_functions case asserted HISTFILE was no longer the scoped
  path. Whether the scoped value survives at all is the host's call: macOS
  /etc/zshrc overwrites HISTFILE so it does not, and a host with no such
  assignment keeps whatever the spawn env set. Now compared against an unwrapped
  pane given the same env, which is the real contract on both.

Also notes, where the emulation cases live, that they only discriminate on a host
whose system zshrc clobbers HISTFILE -- on CI's Ubuntu the load-bearing assertion
is ORCA_HISTFILE having been consumed.

* test(shell): re-pin the fixes the four-file wrapper was built for

Archaeology over the removed blocks: each existed for a bug, so each needs the
bug shown to be unreachable rather than just the code gone. Six restored or added,
each naming the change that introduced the behaviour.

- stablyai#8003, twice: the wrapper sourced from a relocated root, and from a non-ASCII
  (token-range) one. The old file baked its generation-time path in and had to
  re-derive the runtime one from %x to avoid using it; this one bakes nothing.
  Both runs assert ORCA_SHELL_FEATURES came back consumed, so 'the user's .zshrc
  loaded' cannot pass on a pane that never read the wrapper at all.
- stablyai#4667: user startup files must see their OWN ZDOTDIR while they run, or plugin
  and theme lookups resolve into Orca's dir. The old wrapper swapped ZDOTDIR
  around each source; this one never takes it away, and the values now have to
  match an unwrapped pane's.
- stablyai#1947: a user .zshenv that returns early.
- stablyai#15258: an inherited ZDOTDIR that is an Orca wrapper dir must be refused. CI
  proved this route is live -- the launch config only sets ORCA_ORIG_ZDOTDIR when
  it resolved a usable dir, but a pane inherits its parent's environment too.
- stablyai#11044/stablyai#11146: a nested Orca inherits neither cross-process channel and no
  ZDOTDIR of Orca's, which is what makes stablyai#11044's plain shape unreachable rather
  than repaired. Verified the child-env probe detects a real leak before trusting
  it to report the absence of one.
dallascrilley pushed a commit to dallascrilley/orca that referenced this pull request Aug 27, 2026
… hook (STA-4786) (stablyai#15391)

* refactor(shell): collapse the zsh wrapper to one .zshenv and a precmd hook (STA-4786)

Orca needs to run code after the user's own zsh startup files. It bought that by
keeping ZDOTDIR pointed at its own wrapper dir for the whole of startup and
sourcing each user file by hand -- four generated files per transport, with a
fake ZDOTDIR live while /etc/zshrc ran. That single decision is the root of a
whole bug family:

- /etc/zshrc assigns HISTFILE=${ZDOTDIR:-$HOME}/.zsh_history unconditionally, so
  history landed inside Orca's own dir (stablyai#11044), and an epilogue had to repair it.
- zsh's sourcehome() ignores ZDOTDIR once the shell is in sh/ksh emulation, so a
  user .zshenv or .zprofile ending in `emulate sh` hid every later wrapper file.
  The emulation degrade blocks and their forked $(emulate) probes exist for that.
- One wrapper dir shared by two installed builds could mix files from both, so
  every generated file had to redefine the helpers it called.
- The baked generation-time ZDOTDIR literal is unusable when a Windows-generated
  wrapper is sourced inside WSL via /mnt/c (stablyai#8003), so the runtime path had to be
  re-derived from %x.

The wrapper now hands ZDOTDIR back on its first lines and defers Orca's work to a
precmd hook that runs at the first prompt -- after .zprofile, /etc/zshrc, .zshrc
and .zlogin, every one of which zsh reads from the user's own directory exactly
as in an unwrapped shell. Each bug above stops being reachable rather than being
repaired, and their machinery goes with them: eight of thirteen exported blocks in
shell-templates.ts, both drifted discovery bodies (unifying them closes the
"reconciling the two is a follow-up" note the file carried), and the relay's
separate ORCA_USER_ZDOTDIR shape. Generated zsh drops from 819 lines across
twelve files to 143 in three.

Two things the design has to get right, both found by running it rather than
reasoning about it:

- Every function is defined ABOVE the source of the user's .zshenv. A user file
  ending in `emulate sh` puts the rest of the wrapper under sh parsing rules, and
  the first prototype died there with `parse error near '\n'` -- silently, leaving
  the pane unwrapped. Function bodies are parsed at definition time.
- ORCA_ORIG_ZDOTDIR is vetted, not trusted. The launch config only sets it when it
  resolved a usable dir, but a pane inherits its parent's environment too, so a
  stale value from an older build can arrive on its own and would point ZDOTDIR
  back at a wrapper dir. The ownership check Node applies now also runs in the
  shell, where that route is visible.

Orca also stops inventing a ZDOTDIR: where the user has none, ORCA_ORIG_ZDOTDIR is
absent and the pane ends with ZDOTDIR unset, as an unwrapped login zsh does.

Verified on real zsh over a real PTY -- necessary, because a precmd hook never runs
in a shell started with -c, so the existing `zsh -i -c` probes could not have
exercised this design at all. src/main/zsh-startup-hook-pty-harness.ts drives the
shell to a prompt and reports through a file rather than stdout, which a PTY echoes.

* test(shell): cover the relay variant of the zsh hook in a real shell

The relay writes its own variant -- no OSC 133, remote CLI bin dir instead of the
agent-teams shim -- and it had no live coverage. It used to carry a second ZDOTDIR
shape as well, which is how it drifted from the desktop template in the first
place; now the spec flags are the only difference, and this pins that.

* fix(shell): rebase the single-file hook onto content-addressed wrapper trees

stablyai#15285 landed content-addressed wrapper roots and a per-transport fileset module
while this branch was in flight. The fileset modules are now the single place the
tree is described, so 'only .zshenv' is stated once per transport and the
required-paths check follows from it rather than repeating the list.

* test(shell): point the mixed-build proof at the relay, the one fixed wrapper path

stablyai#15285 content-addressed the desktop and daemon trees, so two builds can no
longer write the same directory there and the scenario this file covers became
unreachable on those paths. The relay still writes a fixed ~/.orca-relay/
shell-ready, so that is where the hazard survives and where the proof belongs.

* fix(test): make the zsh PTY harness survive a startup that stops to ask

Two CI-only failures, both from driving a real PTY where the old probes drove a
pipe:

- A host whose global zshrc runs `compinit` over directories it considers
  insecure stops startup and ASKS. A pipe-backed `zsh -i -c` never saw the
  question; a PTY sits at it until the timeout. The harness now answers it.
  ZSH_DISABLE_COMPFIX does not help -- that is an oh-my-zsh convention and plain
  compinit ignores it, which I confirmed by reproducing the prompt locally.
- The PS1 line was typed at t=0, so on such a host the question consumed it as
  its answer. The harness now waits for the shell to fall quiet first, which
  also stops a slow prompt framework racing the same write.

Also merges a duplicate vitest import the native code-quality audit flagged.

* fix(test): stop the live-shell assertions assuming macOS host behaviour

Two of them hardcoded what my machine does rather than what Orca owes:

- LINEINIT was pinned to 'none'. A host whose global zsh config installs its own
  zle-line-init widget has one either way; the contract is that it looks the same
  wrapped as unwrapped, which the assertion beside it already states.
- The dropped-precmd_functions case asserted HISTFILE was no longer the scoped
  path. Whether the scoped value survives at all is the host's call: macOS
  /etc/zshrc overwrites HISTFILE so it does not, and a host with no such
  assignment keeps whatever the spawn env set. Now compared against an unwrapped
  pane given the same env, which is the real contract on both.

Also notes, where the emulation cases live, that they only discriminate on a host
whose system zshrc clobbers HISTFILE -- on CI's Ubuntu the load-bearing assertion
is ORCA_HISTFILE having been consumed.

* test(shell): re-pin the fixes the four-file wrapper was built for

Archaeology over the removed blocks: each existed for a bug, so each needs the
bug shown to be unreachable rather than just the code gone. Six restored or added,
each naming the change that introduced the behaviour.

- stablyai#8003, twice: the wrapper sourced from a relocated root, and from a non-ASCII
  (token-range) one. The old file baked its generation-time path in and had to
  re-derive the runtime one from %x to avoid using it; this one bakes nothing.
  Both runs assert ORCA_SHELL_FEATURES came back consumed, so 'the user's .zshrc
  loaded' cannot pass on a pane that never read the wrapper at all.
- stablyai#4667: user startup files must see their OWN ZDOTDIR while they run, or plugin
  and theme lookups resolve into Orca's dir. The old wrapper swapped ZDOTDIR
  around each source; this one never takes it away, and the values now have to
  match an unwrapped pane's.
- stablyai#1947: a user .zshenv that returns early.
- stablyai#15258: an inherited ZDOTDIR that is an Orca wrapper dir must be refused. CI
  proved this route is live -- the launch config only sets ORCA_ORIG_ZDOTDIR when
  it resolved a usable dir, but a pane inherits its parent's environment too.
- stablyai#11044/stablyai#11146: a nested Orca inherits neither cross-process channel and no
  ZDOTDIR of Orca's, which is what makes stablyai#11044's plain shape unreachable rather
  than repaired. Verified the child-env probe detects a real leak before trusting
  it to report the absence of one.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
… hook (STA-4786) (stablyai#15391)

* refactor(shell): collapse the zsh wrapper to one .zshenv and a precmd hook (STA-4786)

Orca needs to run code after the user's own zsh startup files. It bought that by
keeping ZDOTDIR pointed at its own wrapper dir for the whole of startup and
sourcing each user file by hand -- four generated files per transport, with a
fake ZDOTDIR live while /etc/zshrc ran. That single decision is the root of a
whole bug family:

- /etc/zshrc assigns HISTFILE=${ZDOTDIR:-$HOME}/.zsh_history unconditionally, so
  history landed inside Orca's own dir (stablyai#11044), and an epilogue had to repair it.
- zsh's sourcehome() ignores ZDOTDIR once the shell is in sh/ksh emulation, so a
  user .zshenv or .zprofile ending in `emulate sh` hid every later wrapper file.
  The emulation degrade blocks and their forked $(emulate) probes exist for that.
- One wrapper dir shared by two installed builds could mix files from both, so
  every generated file had to redefine the helpers it called.
- The baked generation-time ZDOTDIR literal is unusable when a Windows-generated
  wrapper is sourced inside WSL via /mnt/c (stablyai#8003), so the runtime path had to be
  re-derived from %x.

The wrapper now hands ZDOTDIR back on its first lines and defers Orca's work to a
precmd hook that runs at the first prompt -- after .zprofile, /etc/zshrc, .zshrc
and .zlogin, every one of which zsh reads from the user's own directory exactly
as in an unwrapped shell. Each bug above stops being reachable rather than being
repaired, and their machinery goes with them: eight of thirteen exported blocks in
shell-templates.ts, both drifted discovery bodies (unifying them closes the
"reconciling the two is a follow-up" note the file carried), and the relay's
separate ORCA_USER_ZDOTDIR shape. Generated zsh drops from 819 lines across
twelve files to 143 in three.

Two things the design has to get right, both found by running it rather than
reasoning about it:

- Every function is defined ABOVE the source of the user's .zshenv. A user file
  ending in `emulate sh` puts the rest of the wrapper under sh parsing rules, and
  the first prototype died there with `parse error near '\n'` -- silently, leaving
  the pane unwrapped. Function bodies are parsed at definition time.
- ORCA_ORIG_ZDOTDIR is vetted, not trusted. The launch config only sets it when it
  resolved a usable dir, but a pane inherits its parent's environment too, so a
  stale value from an older build can arrive on its own and would point ZDOTDIR
  back at a wrapper dir. The ownership check Node applies now also runs in the
  shell, where that route is visible.

Orca also stops inventing a ZDOTDIR: where the user has none, ORCA_ORIG_ZDOTDIR is
absent and the pane ends with ZDOTDIR unset, as an unwrapped login zsh does.

Verified on real zsh over a real PTY -- necessary, because a precmd hook never runs
in a shell started with -c, so the existing `zsh -i -c` probes could not have
exercised this design at all. src/main/zsh-startup-hook-pty-harness.ts drives the
shell to a prompt and reports through a file rather than stdout, which a PTY echoes.

* test(shell): cover the relay variant of the zsh hook in a real shell

The relay writes its own variant -- no OSC 133, remote CLI bin dir instead of the
agent-teams shim -- and it had no live coverage. It used to carry a second ZDOTDIR
shape as well, which is how it drifted from the desktop template in the first
place; now the spec flags are the only difference, and this pins that.

* fix(shell): rebase the single-file hook onto content-addressed wrapper trees

stablyai#15285 landed content-addressed wrapper roots and a per-transport fileset module
while this branch was in flight. The fileset modules are now the single place the
tree is described, so 'only .zshenv' is stated once per transport and the
required-paths check follows from it rather than repeating the list.

* test(shell): point the mixed-build proof at the relay, the one fixed wrapper path

stablyai#15285 content-addressed the desktop and daemon trees, so two builds can no
longer write the same directory there and the scenario this file covers became
unreachable on those paths. The relay still writes a fixed ~/.orca-relay/
shell-ready, so that is where the hazard survives and where the proof belongs.

* fix(test): make the zsh PTY harness survive a startup that stops to ask

Two CI-only failures, both from driving a real PTY where the old probes drove a
pipe:

- A host whose global zshrc runs `compinit` over directories it considers
  insecure stops startup and ASKS. A pipe-backed `zsh -i -c` never saw the
  question; a PTY sits at it until the timeout. The harness now answers it.
  ZSH_DISABLE_COMPFIX does not help -- that is an oh-my-zsh convention and plain
  compinit ignores it, which I confirmed by reproducing the prompt locally.
- The PS1 line was typed at t=0, so on such a host the question consumed it as
  its answer. The harness now waits for the shell to fall quiet first, which
  also stops a slow prompt framework racing the same write.

Also merges a duplicate vitest import the native code-quality audit flagged.

* fix(test): stop the live-shell assertions assuming macOS host behaviour

Two of them hardcoded what my machine does rather than what Orca owes:

- LINEINIT was pinned to 'none'. A host whose global zsh config installs its own
  zle-line-init widget has one either way; the contract is that it looks the same
  wrapped as unwrapped, which the assertion beside it already states.
- The dropped-precmd_functions case asserted HISTFILE was no longer the scoped
  path. Whether the scoped value survives at all is the host's call: macOS
  /etc/zshrc overwrites HISTFILE so it does not, and a host with no such
  assignment keeps whatever the spawn env set. Now compared against an unwrapped
  pane given the same env, which is the real contract on both.

Also notes, where the emulation cases live, that they only discriminate on a host
whose system zshrc clobbers HISTFILE -- on CI's Ubuntu the load-bearing assertion
is ORCA_HISTFILE having been consumed.

* test(shell): re-pin the fixes the four-file wrapper was built for

Archaeology over the removed blocks: each existed for a bug, so each needs the
bug shown to be unreachable rather than just the code gone. Six restored or added,
each naming the change that introduced the behaviour.

- stablyai#8003, twice: the wrapper sourced from a relocated root, and from a non-ASCII
  (token-range) one. The old file baked its generation-time path in and had to
  re-derive the runtime one from %x to avoid using it; this one bakes nothing.
  Both runs assert ORCA_SHELL_FEATURES came back consumed, so 'the user's .zshrc
  loaded' cannot pass on a pane that never read the wrapper at all.
- stablyai#4667: user startup files must see their OWN ZDOTDIR while they run, or plugin
  and theme lookups resolve into Orca's dir. The old wrapper swapped ZDOTDIR
  around each source; this one never takes it away, and the values now have to
  match an unwrapped pane's.
- stablyai#1947: a user .zshenv that returns early.
- stablyai#15258: an inherited ZDOTDIR that is an Orca wrapper dir must be refused. CI
  proved this route is live -- the launch config only sets ORCA_ORIG_ZDOTDIR when
  it resolved a usable dir, but a pane inherits its parent's environment too.
- stablyai#11044/stablyai#11146: a nested Orca inherits neither cross-process channel and no
  ZDOTDIR of Orca's, which is what makes stablyai#11044's plain shape unreachable rather
  than repaired. Verified the child-env probe detects a real leak before trusting
  it to report the absence of one.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant