Skip to content

fix(shell): repair worktree HISTFILE in plain zsh panes via one positive feature channel - #15258

Merged
nwparker merged 5 commits into
mainfrom
nwparker/zsh-shell-feature-channel
Aug 18, 2026
Merged

nwparker merged 5 commits into
mainfrom
nwparker/zsh-shell-feature-channel

Conversation

@nwparker

@nwparker nwparker commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 36 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1442 $\color{#cf222e}{\Huge{\mathbf{−}}}$​197 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1245
Prod 47 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1765 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1181 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​584

#15245 (nwparker/zsh-wrapper-shared-builder) has merged. This branch is rebased onto main and its base is main, so the diff below is only this change.

This replaces #15197, which should be closed in favour of this one — its approach was abandoned rather than iterated on; see "Why not #15197" below.

ELI5

Every Orca worktree is supposed to get its own shell history. On macOS the system's /etc/zshrc overwrites HISTFILE on the way to your prompt, and Orca's repair for that only ran in panes that were already wrapped for some other reason. An ordinary pane was never wrapped, so it never got the repair — your per-worktree history quietly went nowhere.

To wrap those panes, Orca needs a way to tell the shell "turn on exactly these things". This PR makes that one variable carrying a list of things to turn on, which the wrapper reads and then deletes before your own config runs. Nothing you launch from that pane can see it, so it can't leak into anything else.

What Changed

One channel, positive, consumed and destroyed

  • New ORCA_SHELL_FEATURES: a comma-separated allowlist from a closed token set — history, markers, ready, identity, overlay. Absent = no features (fail-safe). There is no negative/suppression variable anywhere; ORCA_SHELL_READY_MARKER and ORCA_SHELL_STARTUP_IDENTITY are gone, including the : '0' pins in src/relay/pty-handler.ts.
  • The wrapper .zshenv consumes it in its first executable lines, before the user's .zshenv is sourced:
    typeset -ga _orca_shell_features
    _orca_shell_features=(${(s:,:)${ORCA_SHELL_FEATURES:-}})
    builtin unset ORCA_SHELL_FEATURES
    __orca_has_feature() { (( ${_orca_shell_features[(Ie)$1]} )) }
    _orca_shell_features is a plain, non-exported shell variable: it survives .zshenv -> .zprofile -> .zshrc -> .zlogin in this process and physically cannot reach a child. The bash rcfile does the equivalent and destroys the channel in its first six lines. fish needs no variable — its selection is baked into the per-pane --init-command, so the if test "$ORCA_SHELL_READY_MARKER" = 1 gate is gone from the init text.
  • ORCA_HISTFILE is consume-and-destroy too: the epilogue does HISTFILE=$ORCA_HISTFILE; builtin unset ORCA_HISTFILE. That removes the root cause of fix(terminal): keep worktree HISTFILE after macOS /etc/zshrc #11146 rather than patching it. The existing TypeScript delete env.ORCA_HISTFILE calls stay as belt-and-braces but are no longer load-bearing. HISTFILE itself stays exported.
  • Because HISTFILE stays exported, a wrapped pane now hands the worktree history path to everything it launches — including another Orca. src/main/worktree-history-file-path.ts drops an inherited HISTFILE that Orca itself minted (desktop, desktop-WSL and relay path shapes) before every check-before-set, on the desktop, daemon and relay injection paths and on both history-disabled branches, so a nested Orca cannot silently scope all of its panes to the launching worktree's history file. A user-supplied HISTFILE still wins. Same fix shape as fix(terminal-history): drop an inherited Orca fish_history so nested Orca panes stop merging worktree histories (STA-4682) #15195 for fish_history; see follow-up Fix PTY listener leak, use local restty with selection support #5.

One epilogue

All Orca-owned, order-sensitive work moved into a single __orca_shell_epilogue defined in the wrapper .zshenv and invoked exactly once — from the end of .zshrc for a non-login shell, from the end of .zlogin for a login shell — guarded by a (( $+_orca_epilogue_done )) once-flag. Inside it, each feature is an independent guard: overlay (CODEX_HOME / OPENCODE_CONFIG_DIR / MIMOCODE_HOME / omp wrapper / agent-teams PATH shim / remote-CLI bin dir), markers (OSC 133, still prepended to precmd_functions/preexec_functions), ready (the zle-line-init OSC 777 widget with its existing prior-widget chaining). identity stays early in .zshenv, gated on the snapshotted array. The epilogue ends by restoring the user's real ZDOTDIR, unsetting _orca_shell_features, and unfunction-ing itself.

Its first statement is emulate -L zsh. The epilogue runs after the user's own config, so it would otherwise inherit whatever shell options that config left set — and a single consolidated function means the first failure inside it skips everything after it. Two real options broke it (both measured on zsh 5.9, see "Review follow-ups"): setopt no_unset made precmd_functions=(… ${precmd_functions[@]}) a fatal parameter not set, and setopt ksh_arrays (also implied by emulate sh/emulate ksh) made the 1-based [(Ie)…] feature subscript return 0 for whichever feature is listed first. emulate -L zsh restores zsh-native option state for the body and LOCAL_OPTIONS puts the user's options back on return.

The /etc/zshrc HISTFILE repair is not behind a feature guard. It undoes damage the wrapper's own ZDOTDIR caused, so it must also run for a shell that re-enters the wrapper after the allowlist has been consumed — e.g. an interactive zsh started from a non-interactive one, which ran .zshenv (exporting Orca's ZDOTDIR) but never the epilogue that restores it. Its elif fires only when HISTFILE is byte-identical to $ZDOTDIR/.zsh_history with $ZDOTDIR being Orca's own wrapper dir, so that branch never touches a HISTFILE the user set deliberately. The if branch is not so narrow, and the earlier claim that "a HISTFILE the user set deliberately is never touched" was only true of the elif: whenever Orca injected an ORCA_HISTFILE it assigns it unconditionally, which overrides a HISTFILE the user set inside their own .zshrc. A HISTFILE already present in the spawn env cannot collide with it — injectHistoryEnv's check-before-set means Orca never mints ORCA_HISTFILE in that case. For every pane Orca actually launches this is equivalent to the guarded form (features.length > 0 ⟺ history ∈ features for zsh).

One launch config

getShellReadyLaunchConfig / getMarkerlessShellLaunchConfig collapse into getShellLaunchConfig(shellPath, features) (local and daemon) plus getRelayShellLaunchConfig. Selection is selectShellStartupFeatures(...) — a pure function of spawn env + launch intent, in src/main/shell-startup-features.ts:

token selected when
overlay any Orca overlay dir var is in the spawn env
history zsh only, and either this spawn injected ORCA_HISTFILE, or the pane was already wrapped
markers the pane was already wrapped before this change (overlay, or a startup command)
ready the startup-command delivery waits for the readiness marker
identity Orca needs the shell PID announced at startup

Empty token set ⇒ do not wrap at all and do not set the variable. history is zsh-only because the unguarded HISTFILE assignment lives in the system zshrc; bash has no equivalent, and wrapping bash via --rcfile for history alone would swap its login startup-file chain for Orca's approximation of one.

Fail-closed generation

writeShellWrapperFiles writes each file to a temp name and renames, and generation returns a boolean. ZDOTDIR is set only when that is true and every required path exists non-empty. Otherwise the launch returns plain login zsh (['-l'], no env) so the user's real config still loads. Previously a failed write still pointed ZDOTDIR at an empty dir and the user silently lost their entire zsh config, on every pane, until it was noticed. The relay's ensureOverlayRestoreWrappers (which can throw EACCES straight through getRelayShellLaunchConfig on a root-owned remote $HOME) is wrapped in try/catch with the same fallback.

Stacked-ZDOTDIR guard

Orca recognised only its own wrapper path shape (case "${ORCA_ORIG_ZDOTDIR}" in ""|*/shell-ready/zsh)). Launched from any other terminal that had already hijacked ZDOTDIR, Orca captured that as "the user's config dir" and re-sourced it. Narrow today; far more panes get wrapped after this change, so it is widened here rather than left as exposure. Ownership is now established positively: a stamped .orca-shell-wrapper marker file Orca writes into its wrapper dirs, or Orca's own */shell-ready/zsh shape for wrappers written by older builds. Additionally, an inherited ZDOTDIR containing no readable .zshenv/.zshrc/.zprofile/.zlogin is ignored. No other vendor is detected by name — that can never be complete. Both the shell side (__orca_resolve_user_config_dir / __orca_resolve_inherited_config_dir) and the Node side (src/main/zsh-wrapper-dir-ownership.ts) apply it.

Why

The bug

Orca gives each workspace its own zsh history by injecting HISTFILE into the spawn env. On macOS, /etc/zshrc contains an unguarded

HISTFILE=${ZDOTDIR:-$HOME}/.zsh_history

that runs before the user's rc and before any wrapper file Orca controls, so the injected value is already gone by the first prompt. Orca has a repair block for this, but it only ran when the pane was already wrapped for some other reason (an overlay env var, or a startup command). A plain pane was never wrapped, so it never got the repair.

Confirmed directly:

$ HISTFILE=/tmp/x ORCA_HISTFILE=/tmp/x HOME=/tmp/fake zsh -li -c 'echo $HISTFILE'
/tmp/fake/.zsh_history

Why not #15197

#15197 introduced a new regression in each of three review rounds, twice by the same mechanism:

  1. It gated on env.ORCA_HISTFILE but nothing scrubbed an inherited one, so a pane opened with history scoping off wrote into the launching worktree's history — re-opening fix(terminal): keep worktree HISTFILE after macOS /etc/zshrc #11146.
  2. It suppressed OSC 133 with ORCA_SHELL_COMMAND_MARKERS=0. That variable lives in the pane's PTY env and is inherited by every child, so an Orca launched from such a pane had markers disabled for all its own agent panes, leaving agent rows stuck on "working".

Both are the same defect class: a negative, exported switch used as a cross-process control channel. The fix is not to add another scrub; it is to make that class unrepresentable. Hence: one positive allowlist, no suppression value at any level, and a variable that stops existing before anything can inherit it.

Linked Issue

Fixes #11044

Also removes the root cause of #11146 (an inherited ORCA_HISTFILE reaching a pane it was not meant for) rather than patching the symptom.

Also closes the HISTFILE half of the same inheritance class (a wrapped pane exporting its worktree history path to a nested Orca), the sibling of the fish_history fix in #15195.

Visual Proof

N/A — there is no UI surface here. The change is which env/args a PTY is spawned with and what the generated shell wrapper files contain; the observable effect is where a history file is written, which is a filesystem path, not pixels. The behaviour is covered by real-shell tests below.

Testing

Platform: macOS 15 (Darwin 25.3.0), arm64, zsh 5.9 with the system /etc/zshrc present. The clobber-premised assertions are probed, not hardcoded to a platform (systemZshrcClobbersHistfile launches a real login zsh with an injected HISTFILE and checks whether it survives). On this machine the probe returned true, so both clobber-premised assertions in zsh-scoped-histfile.live-shell.test.ts ran for real and were meaningful. On a stock Ubuntu zsh with no such assignment they skip rather than assert a tautology.

Leak proof

src/main/shell-startup-feature-channel.test.ts:

  • selectShellStartupFeatures given env.ORCA_SHELL_FEATURES = 'overlay,markers,ready,identity,history' and nothing else returns [] — an inherited value is not an input and cannot enable anything.
  • The same function given ORCA_SHELL_FEATURES: '' plus an injected ORCA_HISTFILE still returns ['history'] — there is no value of the variable that disables anything.
  • getShellLaunchConfig('/bin/zsh', ['history']) with a stale process.env.ORCA_SHELL_FEATURES = 'overlay,markers,ready,identity' publishes exactly history.
  • Real shell: a history-only pane launched through the real launch config runs print ORCA_SHELL_FEATURES; zsh -c 'printenv ORCA_SHELL_FEATURES' and the variable is unset in both the launched shell and the grandchild.
  • src/relay/pty-handler-revive.test.ts seeds process.env.ORCA_SHELL_FEATURES = 'ready,identity,markers,overlay' before a revive and asserts the spawned pane gets neither ready nor identity — the case the deleted : '0' pins used to cover.
  • src/main/zsh-scoped-histfile.live-shell.test.ts asserts ORCA_HISTFILE is empty in the launched shell after the epilogue consumed it.

Behaviour parity

src/main/shell-startup-feature-channel.test.ts builds a temp $HOME whose .zshenv/.zprofile/.zshrc/.zlogin each announce that they ran, then launches the same command through (a) the real history-only launch config and (b) a plain zsh -l, and compares the full output: startup-file order, precmd_functions, preexec_functions, widgets[zle-line-init]. They are identical, precmd_functions is empty, and the output contains no OSC 133. The one documented carried-over difference — already true of every pane Orca wrapped before this change — is that a wrapped shell ends with ZDOTDIR explicitly set to the user's config dir, which is the value zsh itself defaults to when it is unset; the test asserts that explicitly rather than hiding it.

Review follow-ups

Defects found in release-readiness and adversarial review, each verified against a real zsh 5.9 on macOS before and after the fix.

1 — the consolidated epilogue was not option-proof (P1). With setopt no_unset in the user's .zshrc:

before: __orca_shell_epilogue:82: precmd_functions[@]: parameter not set
        ZDOTDIR=/tmp/orcachk/wrap/zsh        widget=none
after:  ZDOTDIR=/tmp/orcachk/home            widget=user:__orca_prompt_mark

Because everything now lives in one function, that error returned from the epilogue and skipped the ready widget and the final ZDOTDIR restore — before this PR the same error only truncated the wrapper .zshrc, and .zlogin still did both. With setopt ksh_arrays the feature lookup silently dropped the first token (overlay for an agent pane, so OPENCODE_CONFIG_DIR/CODEX_HOME were not restored). emulate -L zsh as the epilogue's first line fixes both, plus sh_word_split and emulate sh for non-login shells.

2 — the relay wrapping gate was built on a false premise, and has been removed (P0, self-inflicted then reverted). An earlier round added a relay-only wrapping list (ORCA_OPENCODE_CONFIG_DIR, ORCA_MIMOCODE_HOME, ORCA_OMP_STATUS_EXTENSION, ORCA_REMOTE_CLI_BIN_DIR) to avoid "newly wrapping" remote zsh panes, on the theory that the relay's overlay-user-zdotdir .zshenv would lose a relocated user ZDOTDIR. The premise about which panes were newly wrapped was wrong:

  • origin/main's hasOverlayRestoreEnv already included ORCA_REMOTE_CLI_BIN_DIR (src/relay/pty-shell-launch.ts:53).
  • src/main/providers/ssh-pty-spawn-env.ts sets ORCA_REMOTE_CLI_BIN_DIR on every SSH pane whenever the CLI bridge exists, and ssh-relay-session.ts populates remoteCliBridgeEnv for every relay session whose host reports its platform.

So ordinary remote zsh panes were already wrapped on main, the relocated-ZDOTDIR defect is pre-existing and untouched by this PR, and the gate was a no-op for them. Where it was not a no-op it was strictly worse: on a host too old to report its platform, remoteCliBridgeEnv is null, no overlay key is set, and the gate kept that pane unwrapped — silently losing its worktree history, which features.length > 0 repairs. The gate is gone; all three transports now share one rule (features.length === 0 ⇒ plain -l, bash excepted). The test that pinned an env with no ORCA_REMOTE_CLI_BIN_DIR — a configuration production never produces — is replaced by three tests built from the real buildSshPtySpawnEnv output.

3 — the HISTFILE repair lost its self-healing property (P2). Putting the /etc/zshrc clobber repair behind if __orca_has_feature history meant a zsh that re-enters the wrapper with Orca's ZDOTDIR inherited but the (deliberately destroyed) allowlist absent kept HISTFILE=<orca-wrapper-dir>/.zsh_history — silently reproducing #11044. The repair is now emitted ungated, as it was on main.

4 — the shell-fallback path leaked the previous attempt's launch env (P2). spawnShellWithFallback merged the fallback's launch env into the same object without clearing the primary's, and an unwrapped fallback (/bin/bash with no features) contributes {}. A bash pane therefore inherited ORCA_SHELL_FEATURES=history and ZDOTDIR=<userData>/shell-ready/zsh, which nothing in that pane consumes — so typing zsh there loaded Orca's wrapper via the stale ZDOTDIR and enabled a feature Orca never selected for it. The keys to scrub are now tracked per attempt: the first fix computed them once from the primary, so a wrapped first fallback leaked its own ZDOTDIR/ORCA_SHELL_FEATURES into the second. The key list is also passed in from the launch config the provider already computed, instead of re-invoking getShellReadyConfig(shellPath) — for zsh/bash that call re-runs ensureShellReadyWrappers() and rewrites six files purely to read back key names.

5 — the PR widened the identical leak on HISTFILE that it closes on ORCA_HISTFILE (P1). HISTFILE stays exported by design. A newly wrapped plain zsh pane now ends startup with the worktree history path exported to every child; before this PR /etc/zshrc had already overwritten it with $HOME/.zsh_history, so the worktree value never escaped the pane. Measured: a child sees HISTFILE=[/tmp/leak/wtA/.zsh_history] on this branch vs [/tmp/base1/home/.zsh_history] pre-PR. The next Orca launched from that pane honours it — every pane env starts from stripInheritedBuildModeEnv(process.env), and injectHistoryEnv's check-before-set (src/main/terminal-history.ts) early-returns on any HISTFILE, so every pane of the nested app, in every worktree, appended into worktree A's history file. Same bug class as the inherited fish_history fixed in #15195 (3d29a2604ed), and the same shape of fix: src/main/worktree-history-file-path.ts recognises a path Orca itself minted (desktop terminal-history/<hash>/<file>, desktop-WSL terminal-history-wsl/<distro>/<hash>/<file>, relay .orca-remote/terminal-history/<hash>-<file>) and drops only that, before the check-before-set. A HISTFILE the user set themselves still wins. Applied on the desktop injection path, the desktop history-disabled branch, the daemon subprocess spawn, injectRelayHistoryEnv, and the relay's buildSpawnEnv (covering relay spawn, revive, and isolation-off), exactly as the fish fix did.

6 — a login zsh lost the whole epilogue under emulate sh (P2, regression vs main). zsh's sourcehome() ignores ZDOTDIR once the shell is in EMULATE_SH/EMULATE_KSH, so a user .zshrc ending in emulate sh makes a login shell read $HOME/.zlogin instead of the wrapper's — the epilogue never ran. Measured on zsh 5.9: main still registered the OSC 133 hooks (its .zshrc carried them inline), this branch registered nothing, the ready widget never registered (so startup-command delivery waited out the pre-ready timeout), and HISTFILE was left at <wrapper dir>/.zsh_history — #11044 itself. The wrapper .zshrc now runs the epilogue when [[ ! -o login || "$(emulate 2>/dev/null)" != zsh ]]. Ordering is preserved for every normal login shell (the .zlogin invocation still runs after the user's own .zlogin); only in the emulation case does the epilogue run earlier, where the user's .zlogin can undo its overlay restores — which beats not running it at all. An old zsh with no query form of emulate prints nothing, fails the comparison and runs the epilogue from .zshrc too; the once-flag makes the later .zlogin call a no-op.

7 — the version-mismatch mitigation covered one cross-file call out of four (P2, self-inflicted). The (( ${+functions[__orca_shell_epilogue]} )) && … guard was added so a wrapper dir written by two concurrently installed builds degrades quietly. It did not: .zprofile, .zshrc and .zlogin each begin with __orca_resolve_user_config_dir "${ORCA_ORIG_ZDOTDIR:-$HOME}", a function only .zshenv defined. Measured on zsh 5.9 / macOS 15 with this branch's three files beside an older .zshenv:

before: <wrap>/.zprofile:2: command not found: __orca_resolve_user_config_dir
        <wrap>/.zshrc:2:    command not found: __orca_resolve_user_config_dir
        <wrap>/.zlogin:2:   command not found: __orca_resolve_user_config_dir
        (the user's own .zprofile/.zshrc/.zlogin never ran)
after:  RAN .zprofile / RAN .zshrc / RAN .zlogin, no diagnostics

So the cost was not "the epilogue's features": $REPLY was left empty, every -f "$_orca_home/<file>" check failed, and the user's entire zsh config was skipped — while three errors printed into the pane. Fix: ZSH_USER_CONFIG_DIR_RESOLVER_BLOCK is now emitted at the top of all four generated files (the stricter inherited-value resolver stays in .zshenv, which is the only file that reads an inherited value). +7 lines per file × 3 files × 3 transports in the byte snapshots; .zshenv is byte-identical. The epilogue is now the only cross-file dependency left, and it is the one thing the existing guard actually covers. New live-shell test: src/main/zsh-wrapper-version-mismatch.live-shell.test.ts.

8 — stale assertions on variables this PR deleted (CI red). ORCA_SHELL_READY_MARKER / ORCA_SHELL_STARTUP_IDENTITY are gone from production, but seven test sites still named them; one (src/main/ipc/pty-hidden-at-spawn-mark.test.ts, "falls back when SHELL points to a non-executable binary") asserted ORCA_SHELL_READY_MARKER: '0' inside an objectContaining on the spawn env and failed in CI. Repo-wide sweep and disposition:

site disposition
src/main/ipc/pty-hidden-at-spawn-mark.test.ts:415 → ORCA_SHELL_FEATURES: 'overlay,history,markers' (the real selection for that pane: overlay env, worktree history, no startup command ⇒ no ready)
src/main/daemon/pty-subprocess.test.ts (×6) scrub + toBeUndefined() retargeted to ORCA_SHELL_FEATURES; the old assertion had become vacuous
src/main/daemon/bash-prompt-command-composition.test.ts:32 → ORCA_SHELL_FEATURES: 'ready' (live bash, same intent)
src/main/providers/local-pty-shell-ready-wrapper-generation.test.ts:54 → ORCA_SHELL_FEATURES: 'ready' (live bash, same intent)
src/main/pty/codex-preflight-profile-path-rewrite.test.ts:75-76 deleted — an absent ORCA_SHELL_FEATURES already means no markers, so both keys were dead
src/main/providers/__tests__/shell-ready-framework/README.md:42 → getShellLaunchConfig() + selectShellStartupFeatures()
src/main/shell-startup-features.ts:6-7 kept — prose naming the old switches to explain why the new one is a positive allowlist

No harness scrub was needed for hermeticity: production now deletes ORCA_SHELL_FEATURES and ORCA_HISTFILE from the spawn env on every path before selectShellStartupFeatures runs, so a developer's own exported values cannot reach the selection. That is what made the old ORCA_SHELL_READY_MARKER pins fragile (they read straight off process.env) and is structurally gone.

9 — the HISTFILE scrub matched a shape with no Orca token (nit, tightened + justified). isOrcaMintedHistFile now requires a leading /, so a path relative to the user's cwd with the same tail is theirs. Beyond that the shape is left as-is, deliberately: two of the three forms already carry an Orca token (.orca-remote, terminal-history-wsl), the third needs an absolute path whose last two segments are a 16-char lowercase-hex directory directly under terminal-history holding a file named exactly zsh_history/bash_history, and the blast radius of a false positive is one spawn's env — the pane gets Orca's own worktree history (isolation on) or the shell's default (isolation off), with nothing on disk read, written, moved or deleted. Resolving a real root is not available to the predicate: it runs in the desktop (Electron userData), the daemon subprocess (no Electron), and the relay on a remote host.

10 — the config-dir resolver collided on zsh's shared REPLY global (P0, regression vs main). __orca_resolve_user_config_dir used REPLY as its out-parameter, and this PR emits that block at the top of all four wrapper files, on every zsh pane. REPLY is zsh's conventional shared scratch global, so a user config is entitled to constrain it. Reproduced on zsh 5.9 / macOS, all three transports, plain history-only pane:

user .zshrc ends in result before result now
typeset -r REPLY __orca_resolve_user_config_dir:1: read-only variable: REPLY printed into the pane; the assignment is fatal, so the wrapper file aborts at its first executable line, the epilogue never runs, ZDOTDIR stays at <wrapper>/zsh, HISTFILE=<wrapper>/zsh/.zsh_history, ORCA_HISTFILE leaks to every child HISTFILE=<worktree>/zsh_history, ZDOTDIR=$HOME, ORCA_HISTFILE consumed, nothing printed
typeset -i REPLY every resolved path becomes 0; same wrong HISTFILE, ZDOTDIR exported empty, epilogue skipped same as above

main never touched REPLY (its snapshots use _orca_home only), so this is a regression this PR introduced and then widened to 100% of zsh panes. The out-parameter is now _orca_resolved_config_dir, assigned with typeset -g — a plain assignment would have traded the REPLY collision for a warn_create_global warning on every call, since .zshrc/.zlogin call the resolver after the user's own config.

The class, not the instance. Every shell global the generated wrapper writes was enumerated across all four zsh files, the bash rcfile and the fish init command, for all three transports. REPLY was the only name outside Orca's namespace that was not a deliberate contract. A new rule test (shell-wrapper-generated-file-snapshot.test.ts) now scans every generated file and fails on any assignment or export whose name is neither _orca_*/__orca_*/ORCA_* nor one of nine documented contract names (HISTFILE, ZDOTDIR, PATH, PROMPT_COMMAND, precmd_functions, preexec_functions, CODEX_HOME, OPENCODE_CONFIG_DIR, MIMOCODE_HOME). Reverting the rename makes it fail with expected { 'zsh/.zshenv': [ 'REPLY' ] } to deeply equal { 'zsh/.zshenv': [] }.

11 — the daemon and the relay dropped an inherited HISTFILE but never an inherited ORCA_HISTFILE (P1). Follow-up #5 added dropInheritedOrcaHistFile on five paths; ORCA_HISTFILE — which is also exported into every pane, and which the bash wrapper never consumes — was only cleared where injectHistoryEnv/injectRelayHistoryEnv ran. createPtySubprocess builds {...stripInheritedBuildModeEnv(process.env), ...opts.env} and deleted neither; the relay's buildSpawnEnv deleted it only via injectRelayHistoryEnv, i.e. never on the isolation-off or revive paths. This PR is what makes that bite: selectShellStartupFeatures selects history on Boolean(env.ORCA_HISTFILE), so an inherited value now wraps a pane the client scoped nothing for and is then re-installed by the epilogue (HISTFILE="$ORCA_HISTFILE"). On main the same inherited value was inert because the pane was not wrapped. Both paths now mirror the desktop, which deletes it on both of its branches.

12 — emulate sh in a user .zshenv or .zprofile skipped the wrapper entirely (P1, regression vs main) — the pane now degrades to unwrapped. Follow-up #6 handled emulation entered from the user's .zshrc. Entered earlier, it is worse: zsh's sourcehome() ignores ZDOTDIR from that point on, so no later wrapper file is read — not .zprofile, not .zshrc, not .zlogin — and the epilogue runs zero times, while the user's own $HOME startup files load normally. Reproduced on zsh 5.9, plain pane, features=history: ZDOTDIR=[<wrapper>/zsh], HISTFILE=[<wrapper>/zsh/.zsh_history], ORCA_HISTFILE still exported, epilogue never ran — the shell looks completely normal while history goes somewhere the user will never find and ~/.zsh_history stops growing. On main that pane was unwrapped and correctly got HISTFILE=$HOME/.zsh_history, so widening wrapping turned "isolation off" into "history written somewhere invisible".

Nothing can repair HISTFILE from there — /etc/zshrc assigns it after both .zshenv and .zprofile, so running the epilogue early (the .zshrc fix from #6) repairs nothing. The wrapper therefore does the only other thing worth doing: after sourcing the user's file it checks case "$(emulate 2>/dev/null)" in sh|ksh), and if so restores ZDOTDIR to the user's own config dir, consumes ORCA_HISTFILE, drops its own variables and functions, and returns. The pane is then exactly the unwrapped pane it was before this PR rather than something worse. Measured after the fix, both trigger files: HISTFILE equal to an unwrapped run's, ZDOTDIR=$HOME, ORCA_HISTFILE unset.

Two details worth stating. The match is positive (sh|ksh), not != zsh, so a zsh too old for the query form of emulate — which prints nothing — does not unwrap every pane. And the probe is gated on "did this file actually source a user file", because $(emulate) forks and every zsh pane now pays for it; that gate loses no coverage, since a wrapper file is itself reached through ZDOTDIR, so anything that had already entered emulation (a system /etc/zshenv or /etc/zprofile) would have hidden that very file too. Measured: with no user .zshenv/.zprofile, wrapped startup is unchanged (≈10.5 ms/run before and after, 30 runs, zsh 5.9 / macOS); with one, it costs a single extra fork.

13 — warn_create_global noise above every command (nit, fixed). __orca_in_command=1 in __orca_osc133_preexec creates a global inside a function, which setopt warn_create_global reports on every command line. Not a regression (identical on main, and markers is gated on wrappedBefore so newly wrapped plain panes never had it), but typeset -g removes it, and the same reasoning is why the new resolver out-parameter uses typeset -g too.

Every new test fails without its fix

Verified by reverting each fix in place and re-running:

reverted tests that fail
builtin unset ORCA_SHELL_FEATURES in the zsh channel grandchild-leak + parity (2)
markers gate → always select markers 6, incl. parity
history gate → only when already wrapped 6, incl. the live-shell clobber tests
fail-closed verification → always trust the write fail-closed fallback (1)
ownership check → suffix-only, no readability check stacked-ZDOTDIR guard (1)
emulate -L zsh in the epilogue both hostile-option cases (2), on real zsh
HISTFILE repair back behind the history guard re-entrant clobber repair (1), on real zsh
relay gate reinstated (overlay-key list) remote pane with no CLI bridge keeps its worktree history (1)
per-attempt key delete in spawnShellWithFallback first-fallback env leak into the second fallback (1)
dropInheritedOrcaHistFile removed from all five call sites inherited-HISTFILE tests (8): desktop inject ×2, desktop isolation-off, daemon, relay inject ×2, relay buildSpawnEnv ×2
.zshrc epilogue call back to [[ -o login ]] || … emulate sh login shell (1), on real zsh
resolver block removed from .zprofile/.zshrc/.zlogin mixed-build wrapper dir (1), on real zsh — both the command not found and the skipped-user-config assertions
isOrcaMintedHistFile anchor back to (?:^|/) relative-shape HISTFILE preserved (1)
resolver out-parameter back to REPLY typeset -r REPLY + typeset -i REPLY panes (2) on real zsh, plus the three namespace-rule cases and all three wrapper byte snapshots
emulation degrade removed from .zshenv/.zprofile emulate sh/emulate ksh degrade cases (3), on real zsh
delete env.ORCA_HISTFILE in createPtySubprocess daemon inherited-ORCA_HISTFILE case (1)
delete result.ORCA_HISTFILE in the relay's buildSpawnEnv relay inherited/client-carried ORCA_HISTFILE cases (4)

Suites

All run with ORCA_SHELL_FEATURES, ORCA_HISTFILE and ORCA_SHELL_READY_MARKER explicitly unset, so no assertion can pass on a value inherited from the developer's own Orca pane.

  • npx oxlint and npx oxfmt --check on every changed file — clean. No max-lines disable added, no mobile ratchet bump.
  • npx tsc --noEmit -p config/tsconfig.node.json — clean.
  • src/main/ipc src/main/providers src/main/daemon src/relay src/main/shell-startup-feature-channel.test.ts src/main/shell-wrapper-generated-file-snapshot.test.ts — 6639 passed, 16 skipped, 10 failed, plus 8 suites that fail to collect. Every one of them fails identically on origin/main in the same checkout, verified by detaching to origin/main and re-running them: the 8 collection failures are Error: Cannot find package 'psl' (a dependency this checkout's shared node_modules predates, reached via src/main/browser/browser-cookie-import-policy.ts), and the 10 are xterm snapshot/emulator-fidelity assertions in terminal-snapshot-osc8-roundtrip, terminal-snapshot-color-parity and headless-emulator-fidelity.fuzz. None of those files is touched by this PR.
  • src/main/zsh-scoped-histfile.live-shell.test.ts against real zsh 5.9 / macOS: 12/12, none skipped (7 pre-existing + 5 new: two REPLY declarations, emulate sh and emulate ksh in .zshenv, emulate sh in .zprofile). It drives the real launch decision (selectShellStartupFeatures + getShellLaunchConfig), so a pane Orca would not wrap cannot pass it by construction.
  • src/main/shell-startup-feature-channel.test.ts (real zsh) — 13/13. src/main/zsh-wrapper-version-mismatch.live-shell.test.ts (real zsh) — 1/1. src/main/shell-wrapper-generated-file-snapshot.test.ts — 7/7 including the three new namespace-rule cases. src/main/terminal-history.test.ts + src/relay/terminal-history.test.ts — green.

CI failures that are not this PR's

  • typecheck — was red on the previous run with src/renderer/src/components/tab-bar/TabBarCreateEntry.tab-results.test.tsx(51,9): Property 'occupantAgent' is missing, a pre-existing origin/main breakage since fixed on main by fix(tab-bar): restore the tab-results fixture after occupantAgent became required #15277. It passes on this run. This branch's own target, config/tsconfig.node.json, was clean throughout.
  • e2e / changed e2e specs and e2e / ssh docker watcher isolation — still failing, and every failing spec dies on the same line: Orca's local relay build is missing its version marker at out/relay/linux-x64/.version. That is the e2e lane's relay build artifact, not shell-wrapper behaviour; e2e is deliberately absent from verify's needs because it is red on main. Not fixed here — it needs its own blast radius in the e2e packaging lane.

Everything else is green: static analysis, typecheck, shell contracts, and all 32 tests node shards.

  • verify — the aggregator; it reports the above.

Snapshot updates (#15245's byte snapshots)

These had to change here — that is the point of this PR, and unlike in #15245 updating them is correct. Every changed line falls into one of eight buckets:

  1. .zshenv gains the feature channel + config-dir resolver + the epilogue. The channel is 4 lines; the resolver replaces the repeated case "${x%/}" in */shell-ready/zsh) pattern; the epilogue is the code that moved out of .zshrc/.zlogin.

  2. .zshrc and .zlogin shrink to "source the user's file, then call the epilogue." .zlogin ends with (( ${+functions[__orca_shell_epilogue]} )) && __orca_shell_epilogue; .zshrc wraps the same call in if [[ ! -o login || "$(emulate 2>/dev/null)" != zsh ]] (a login shell normally has .zlogin to load — unless sh/ksh emulation sent it to $HOME/.zlogin; follow-up Fix MaxListenersExceededWarning with singleton PTY dispatcher #6). The ${+functions[…]} guard is braced because KSH_ARRAYS rejects the unbraced form outright, and it exists so a wrapper dir shared by two concurrently installed builds loses the epilogue's features rather than erroring (follow-up Improve terminal font rendering, per-pane zoom, and UI zoom #7 and "Scoped out"). Everything deleted from these two files reappears verbatim inside the epilogue.
    .zprofile/.zshrc/.zlogin also each carry the 7-line __orca_resolve_user_config_dir definition (follow-up Improve terminal font rendering, per-pane zoom, and UI zoom #7): they call it on their first executable line, so defining it only in .zshenv made a mixed-build wrapper dir fail loudly and skip the user's config.

  3. ORCA_SHELL_STARTUP_IDENTITY gate → __orca_has_feature identity, and ORCA_SHELL_READY_MARKER gate → the ready guard (zsh) / __orca_ready_marker (bash). Same emission, different channel.

  4. ORCA_HISTFILE branch gains builtin unset ORCA_HISTFILE. The consume-and-destroy step.

  5. fish init loses its if test "$ORCA_SHELL_READY_MARKER" = 1 wrapper. The command is only passed when ready is selected, so the gate was dead weight; this also removes the last reader of that variable.

  6. Relay .zlogin ready-marker ordering. The pre-existing readyMarkerOrder drift field is deleted: local/daemon registered the widget before the final ZDOTDIR restore, relay after. The widget registration does not read ZDOTDIR, so the order was immaterial; unifying it removes a spec field whose only job was to preserve cosmetic drift. Same for the legacyFormatting indent/comment drift, which became meaningless once the restores were re-indented into a function body.

  7. The resolver's out-parameter is _orca_resolved_config_dir, declared typeset -g, instead of REPLY. Pure rename plus the declaration; the resolver's logic is unchanged (follow-up Add card gap and quick-create in worktree dialog #10).

  8. .zshenv and .zprofile gain the sh/ksh emulation degrade block, gated on having sourced a user file (follow-up Add application screenshot to README #12), and the OSC 133 preexec hook gains typeset -g (follow-up Add Orca logo and polish README header #13).

No generated line changed for any reason outside those eight.

  • I manually tested these changes locally
  • Automated tests added/updated

Blast radius

Honestly stated, because this is the part that matters.

Exactly which pane classes get the history repair (one rule for all three transports: an empty feature set is never wrapped; relay bash is the one unconditional wrap, unchanged):

pane class wrapped on main wrapped after this PR /etc/zshrc HISTFILE repair
local PTY / daemon zsh, worktree history on, no overlay var, no startup command no yes (new) new
local PTY / daemon zsh with an overlay var or a startup command yes yes already had it
relay (SSH) zsh, host reports a CLI bridge — i.e. every normal remote pane, since ssh-pty-spawn-env.ts always sets ORCA_REMOTE_CLI_BIN_DIR yes yes already had it
relay zsh on a host too old to report its platform (remoteCliBridgeEnv === null), worktree history on no yes (new) new
any zsh with nothing Orca-owned (history off, no overlay, no startup command), all transports no no n/a — nothing to repair
zsh that re-enters an inherited wrapper ZDOTDIR with the allowlist already consumed wrapped, repair ran wrapped, repair runs (ungated) unchanged
bash — local/daemon (overlay or startup command only) and relay (always) unchanged unchanged n/a: the unguarded assignment is in the system zshrc, zsh only
fish init-command only unchanged n/a (fish_history, not HISTFILE)
Windows PowerShell / cmd / the WSL outer exe unchanged unchanged n/a

Newly wrapped, therefore: local and daemon plain zsh panes, and the one relay class above. Everything else was already wrapped or stays unwrapped. The relay is not excluded — an earlier revision of this PR said it was, and that was wrong (see follow-up #2).

What that does: the /etc/zshrc HISTFILE clobber is repaired, so per-worktree history actually works on macOS for the first time. That is the whole fix.

What it does not change: those panes get no OSC 133 (the markers token is gated on "was this pane wrapped before"), no readiness marker, no identity marker, and no overlay restores. They run .zshenv, .zprofile, .zshrc, .zlogin from the user's real config dir in the normal order, with the same prompt hooks and the same zle-line-init, proven by the parity test above. Launch args are unchanged: local POSIX panes already spawned ['-l'].

What it also changes for a newly wrapped pane: HISTFILE now reaches the pane's children with the worktree path in it, where before /etc/zshrc had already overwritten it with $HOME/.zsh_history. That is inherent to repairing the value at all — the repair has to happen after the system zshrc, and HISTFILE is exported. The one case where that mattered (an Orca launched from such a pane) is closed by follow-up #5; other children simply see the history file the pane is actually using, which is the intended contract.

What it costs: those panes now source four small generated files and run one function. A login zsh additionally forks once for $(emulate) in the wrapper .zshrc (follow-up #6), and once more per user .zshenv/.zprofile that actually exists (follow-up #12 — the probe is gated on having sourced one, so a user with neither pays nothing). Measured on zsh 5.9 / macOS over 30 runs: wrapped startup is ≈10.5 ms/run with and without the emulation probes when no user .zshenv/.zprofile exists, against ≈8.5 ms/run unwrapped. The rest is a handful of [[ ]] tests and, in the guard, up to four -r stats on the user's config dir.

Panes deliberately left alone: bash is never wrapped for history alone, so its login startup-file chain is untouched. Relay bash stays wrapped unconditionally, exactly as before, because its rcfile carries the OSC 133 hooks that agent status depends on — unwrapping it would have been regression #2 in a new costume. Windows/PowerShell and non-zsh/bash shells are untouched. WSL panes go through the bash path and are unchanged.

Backwards compatibility: the wrapper is regenerated on launch, and the */shell-ready/zsh shape is still accepted as proof of Orca ownership, so a stale wrapper dir written by an older build is still recognised and not mistaken for the user's config. A wrapper dir left half-rewritten by a different build no longer costs the user their zsh config either — see follow-up #7. Nothing here crosses the client/host wire — ORCA_SHELL_FEATURES only travels from a relay process into a PTY it spawns on the same host, never over an RPC or stream frame, so no capability negotiation is needed.

Scoped out

  • Reconciling the relay's overlay-user-zdotdir .zshenv with the local/daemon discover-user-zdotdir one. Still two strategies behind one spec field, preserved from refactor(shell): build every zsh startup wrapper from one shared builder #15245. Unifying them changes which file the remote shell's ZDOTDIR is discovered from and deserves its own PR. Disclosed defect: the overlay body never unset ZDOTDIR before sourcing the user's .zshenv, so for a wrapped relay pane whose user keeps their zsh config in a relocated ZDOTDIR, ORCA_USER_ZDOTDIR collapses to $HOME and that config is not loaded. This is present on origin/main today and reaches every already-wrapped remote pane there (which is every remote pane whose host reports a CLI bridge). This PR adds exactly one newly exposed class — a remote zsh pane on a host too old to report its platform, with worktree history on — and does not fix the defect. The fix is unset ZDOTDIR + re-resolve inside getZshOverlayEnvBody, which changes remote startup for every already-wrapped relay pane and belongs in the reconciliation PR.

  • emulate sh/emulate ksh is now handled everywhere it can be, not scoped out. zsh does not "skip $ZDOTDIR/.zlogin" as an earlier revision of this note claimed — its sourcehome() ignores ZDOTDIR under those emulations and reads the $HOME file instead, so the wrapper's file never runs while the user's does. Entered from the user's .zshrc, the epilogue now runs from the wrapper .zshrc (follow-up Fix MaxListenersExceededWarning with singleton PTY dispatcher #6) and the residual is ordering, not omission. Entered from the user's .zshenv or .zprofile, no wrapper file after it is read at all and HISTFILE cannot be repaired from there, so the pane is handed back unwrapped instead (follow-up Add application screenshot to README #12) — the same shell main produced for it. Residual, accepted: such a pane gets none of Orca's features, including the readiness marker, so a startup command in it waits out the pre-ready timeout before delivery. That is exactly what happened on main for these configurations too; nothing here makes it worse.

  • skipUserZshrcWhenHomeIsWrapperDir. With positive ownership identification this check can no longer fire, but it is left in place rather than removed in the same PR that widens wrapping.

  • Making a wrapped pane leave ZDOTDIR unset when the spawn env had none. Documented in the parity test as the single carried-over difference; it predates this PR and applies to every pane Orca has ever wrapped.

  • Versioning the relay wrapper dir (~/.orca-relay/shell-ready/zsh). It is shared by every Orca build that connects to that remote user, and the generated files are now inter-dependent — the .zlogin/.zshrc call a function defined in the .zshenv. Two concurrently installed builds that disagree about the file contents rewrite the dir on every spawn, so a shell can in principle read one build's .zshenv and another's .zlogin. Mitigated, not eliminated: every function these files call except the epilogue is now redefined at the top of each file that calls it (follow-up Improve terminal font rendering, per-pane zoom, and UI zoom #7), and the epilogue call is guarded on the function existing — so the worst a mismatch costs is the epilogue's features for that one shell, with nothing printed into the pane, and the next spawn rewrites the dir consistently. Redefining one shared constant per file is not the drift the shared builder removed: there is still exactly one source for the text. A real fix is a versioned dir (which then needs its own GC for abandoned versions), and that does not belong here.

  • docs/reference/* for the feature channel. The contract is documented in the module header of src/main/shell-startup-features.ts, next to the code that owns it.

Agent skill upstream boundary

  • Not applicable.

Notes

  • Security: the change removes a cross-process control channel rather than adding one. Nothing new is exported to child processes; one variable that used to be exported (ORCA_SHELL_READY_MARKER) is gone, and the new one is destroyed before user code runs.
  • Cross-platform: zsh/bash paths are POSIX-only and already guarded by process.platform !== 'win32'; Windows PowerShell/cmd and the Git Bash and WSL launch paths are unchanged apart from getBashWrapperLaunchArgs() now returning null (and falling back to a plain login bash) when the rcfile is missing, which is strictly safer than handing ConPTY a path to a file that does not exist.
  • Remote SSH: covered — the relay and daemon transports both go through the same selection and the same fail-closed generation, and the relay path additionally tolerates an EACCES $HOME.
  • Folder workspaces and git worktrees: the selection reads ORCA_HISTFILE from the spawn env and does not care how the workspace was created.
  • Performance: unchanged for already-wrapped panes; for newly wrapped panes, four small generated files and one function call at startup, plus the gated $(emulate) probes described under Blast radius (≈2 ms of the ≈10.5 ms wrapped startup measured on zsh 5.9 / macOS, and zero for a user with no .zshenv/.zprofile).

@nwparker
nwparker changed the base branch from nwparker/zsh-wrapper-shared-builder to main August 18, 2026 06:51
…ive feature channel

A plain zsh pane — no startup command, no agent overlay — was never wrapped, so
Orca's HISTFILE repair never ran in it. macOS `/etc/zshrc` assigns
`HISTFILE=${ZDOTDIR:-$HOME}/.zsh_history` with no check-before-set and runs
before any file Orca controls, so per-worktree history was a silent no-op for
every ordinary pane on the primary platform.

Wrapping those panes needs a way to say which wrapper features a shell should
turn on. That channel is one exported variable, ORCA_SHELL_FEATURES, carrying a
comma-separated positive allowlist from a closed set (history, markers, ready,
identity, overlay). The wrapper .zshenv reads it into a plain, non-exported
array and unsets it in its first executable lines, before the user's own
.zshenv — so the selection survives .zshenv -> .zprofile -> .zshrc -> .zlogin in
this process but physically cannot reach a child. There is no negative or
suppression variable anywhere; an absent or inherited value can only ever mean
fewer features. ORCA_HISTFILE is consumed and destroyed the same way, which
removes the root cause of #11146 instead of patching it.

All order-sensitive wrapper work now lives in one `__orca_shell_epilogue`
defined in .zshenv and invoked exactly once, from .zshrc for a non-login shell
and .zlogin for a login shell, with each feature an independent guard.

Selection is a pure function of spawn env and launch intent, so a pane wrapped
only for history gets no OSC 133 and is observably identical to the unwrapped
pane it used to be.

Generation is now fail-closed: wrapper files are written to a temp name and
renamed, every required path is verified non-empty, and ZDOTDIR is only set when
that holds. Previously a failed write still pointed ZDOTDIR at an empty dir and
the user silently lost their entire zsh config.

Orca also recognised only its own `*/shell-ready/zsh` dir shape when deciding
what the user's ZDOTDIR was, so being launched from any other terminal that had
hijacked ZDOTDIR captured that as the user's config dir. Ownership is now
established positively — a stamped marker file, or Orca's own dir shape for
wrappers written by older builds — and an inherited ZDOTDIR holding no zsh
startup file is ignored. No vendor is detected by name.
@nwparker
nwparker force-pushed the nwparker/zsh-shell-feature-channel branch from 351c0fc to 2326cbb Compare August 18, 2026 06:52
@coderabbitai

coderabbitai Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ff7eac84-e2b0-404b-b5d7-e06b46e0716f

📥 Commits

Reviewing files that changed from the base of the PR and between c7d5f2f and f32ed24.

📒 Files selected for processing (23)
  • src/main/daemon/pty-subprocess-env-inheritance.test.ts
  • src/main/daemon/pty-subprocess.ts
  • src/main/daemon/shell-ready.test.ts
  • src/main/providers/local-pty-shell-ready-wrapper-generation.test.ts
  • src/main/shell-templates.ts
  • src/main/shell-wrapper-generated-file-snapshot.test.ts
  • src/main/shell-wrapper-snapshots/daemon-zsh-zlogin.txt
  • src/main/shell-wrapper-snapshots/daemon-zsh-zprofile.txt
  • src/main/shell-wrapper-snapshots/daemon-zsh-zshenv.txt
  • src/main/shell-wrapper-snapshots/daemon-zsh-zshrc.txt
  • src/main/shell-wrapper-snapshots/local-zsh-zlogin.txt
  • src/main/shell-wrapper-snapshots/local-zsh-zprofile.txt
  • src/main/shell-wrapper-snapshots/local-zsh-zshenv.txt
  • src/main/shell-wrapper-snapshots/local-zsh-zshrc.txt
  • src/main/shell-wrapper-snapshots/relay-zsh-zlogin.txt
  • src/main/shell-wrapper-snapshots/relay-zsh-zprofile.txt
  • src/main/shell-wrapper-snapshots/relay-zsh-zshenv.txt
  • src/main/shell-wrapper-snapshots/relay-zsh-zshrc.txt
  • src/main/zsh-scoped-histfile.live-shell.test.ts
  • src/main/zsh-startup-wrapper-builder.ts
  • src/relay/pty-handler-spawn-environment.test.ts
  • src/relay/pty-handler.ts
  • src/relay/pty-shell-launch.test.ts
🚧 Files skipped from review as they are similar to previous changes (16)
  • src/main/shell-wrapper-snapshots/relay-zsh-zshrc.txt
  • src/relay/pty-handler-spawn-environment.test.ts
  • src/main/shell-wrapper-snapshots/local-zsh-zlogin.txt
  • src/main/shell-wrapper-snapshots/relay-zsh-zshenv.txt
  • src/main/daemon/pty-subprocess.ts
  • src/main/shell-wrapper-snapshots/relay-zsh-zlogin.txt
  • src/main/shell-wrapper-snapshots/local-zsh-zshrc.txt
  • src/main/shell-wrapper-snapshots/local-zsh-zshenv.txt
  • src/relay/pty-handler.ts
  • src/main/shell-wrapper-snapshots/daemon-zsh-zlogin.txt
  • src/main/shell-wrapper-snapshots/daemon-zsh-zshenv.txt
  • src/relay/pty-shell-launch.test.ts
  • src/main/shell-wrapper-snapshots/daemon-zsh-zshrc.txt
  • src/main/shell-templates.ts
  • src/main/providers/local-pty-shell-ready-wrapper-generation.test.ts
  • src/main/daemon/shell-ready.test.ts

Included review availability: Your plan includes up to 10 reviews per rolling hour; 3 remain after this review.


📝 Walkthrough

Walkthrough

The change replaces legacy shell readiness and identity environment variables with the ORCA_SHELL_FEATURES channel. Shell launch configuration now selects and encodes startup features for daemon, local provider, relay, and Windows paths. Zsh wrappers centralize restoration and marker setup in .zshenv, resolve inherited configuration directories, and clean up internal state. Wrapper files use atomic writes and non-empty validation. Tests cover feature selection, readiness, history, ZDOTDIR handling, fallback behavior, and PTY environments.

Merge Risk: 🟡 Moderate · up to f32ed

This PR changes shell startup, history propagation, and relay wrapper generation. At the current head, unresolved issues could block relay PTY startup on FIFO paths and allow scoped-history state to be altered or remain available across startup paths, while test-isolation issues may produce misleading results. Merge should pause for owner follow-up on the runtime and history concerns.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.70% 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 primary fix: repairing worktree HISTFILE behavior in plain zsh panes through a feature channel.
Description check ✅ Passed The description covers the required sections, explains the design and scope, links issue #11044, and documents testing, risks, and platform impact.
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: 8

🧹 Nitpick comments (4)
src/main/providers/local-pty-provider.ts (1)

868-870: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use SHELL_STARTUP_FEATURE_ENV instead of the literal key.

src/relay/pty-handler.ts clears the same channel through the exported constant. This site hardcodes ORCA_SHELL_FEATURES, so a rename of the constant leaves an inherited value alive on this path only.

♻️ Proposed refactor
-import { selectShellStartupFeatures } from '../shell-startup-features'
+import { selectShellStartupFeatures, SHELL_STARTUP_FEATURE_ENV } from '../shell-startup-features'
-      delete finalEnv.ORCA_SHELL_FEATURES
+      delete finalEnv[SHELL_STARTUP_FEATURE_ENV]
src/main/daemon/pty-subprocess.ts (1)

835-837: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use SHELL_STARTUP_FEATURE_ENV instead of the literal key.

This line hardcodes ORCA_SHELL_FEATURES. The name is already exported as SHELL_STARTUP_FEATURE_ENV from ../shell-startup-features, and this file imports from that module at Line 9. A literal here can drift from the constant that every wrapper and launch path uses.

♻️ Proposed fix for the feature-channel key
-import { selectShellStartupFeatures } from '../shell-startup-features'
+import { SHELL_STARTUP_FEATURE_ENV, selectShellStartupFeatures } from '../shell-startup-features'
-    delete env.ORCA_SHELL_FEATURES
+    delete env[SHELL_STARTUP_FEATURE_ENV]
src/main/daemon/shell-ready.test.ts (1)

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

Variable names still describe the old wrapper layout. The epilogue moved into .zshenv, but these variables read .zshenv while keeping names that say .zshrc or .zlogin. A reader cannot tell which file an assertion covers.

  • src/main/daemon/shell-ready.test.ts#L642-L645: rename zshrc to zshenv and remove the zlogin alias, then update the assertions in that test.
  • src/main/providers/local-pty-shell-ready-wrapper-generation.test.ts#L286-L289: rename zshrc to zshenv and remove the zlogin alias, then update the assertions in that test.
  • src/main/providers/local-pty-shell-ready-wrapper-generation.test.ts#L331-L332: rename zshRc to zshenv because it holds getZshShellReadyWrapperFiles().zshenv.
src/main/zsh-scoped-histfile.live-shell.test.ts (1)

82-101: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Isolate the shell-ready wrapper root in a temporary user-data directory.

getShellLaunchConfig writes wrappers under ORCA_USER_DATA_PATH or tmpdir() when unset. This path is outside withTempHome, so the test does not clean it. If wrapper creation fails, launch.env.ZDOTDIR is undefined and the assertion reports a misleading failure. Use a temporary ORCA_USER_DATA_PATH with setTestUserDataPath and importFreshLocalPtyShellReady, following src/main/shell-startup-feature-channel.test.ts.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 96e195c6-8665-406e-a3b2-1aabfb1cd003

📥 Commits

Reviewing files that changed from the base of the PR and between 545b3fb and 2326cbb.

📒 Files selected for processing (66)
  • src/main/daemon/daemon-bash-shell-ready-rcfile.ts
  • src/main/daemon/daemon-zsh-shell-ready-wrapper-spec.ts
  • src/main/daemon/pty-subprocess-managed-agent-env.test.ts
  • src/main/daemon/pty-subprocess.ts
  • src/main/daemon/shell-ready.test.ts
  • src/main/daemon/shell-ready.ts
  • src/main/ipc/pty-ipc-mock-registry.ts
  • src/main/ipc/pty-ipc-spawn-drivers.ts
  • src/main/ipc/pty-ipc-suite-environment.ts
  • src/main/ipc/pty-listener-teardown-and-orphans.test.ts
  • src/main/ipc/pty-login-shell-startup-commands.test.ts
  • src/main/ipc/pty-wsl-cwd-validation.test.ts
  • src/main/providers/__tests__/shell-ready-framework/shell-script-test.ts
  • src/main/providers/local-pty-provider-foreground-process.test.ts
  • src/main/providers/local-pty-provider-io-events.test.ts
  • src/main/providers/local-pty-provider-session-inventory.test.ts
  • src/main/providers/local-pty-provider-shell-readiness.test.ts
  • src/main/providers/local-pty-provider-shutdown.test.ts
  • src/main/providers/local-pty-provider-spawn-cwd-safety.test.ts
  • src/main/providers/local-pty-provider-spawn-env.test.ts
  • src/main/providers/local-pty-provider-spawn-session.test.ts
  • src/main/providers/local-pty-provider-test-harness.ts
  • src/main/providers/local-pty-provider-windows-shell-launch.test.ts
  • src/main/providers/local-pty-provider.ts
  • src/main/providers/local-pty-shell-ready-bash-rcfile.ts
  • src/main/providers/local-pty-shell-ready-test-harness.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-wrapper-root.ts
  • src/main/providers/local-pty-shell-ready-zsh-launch-environment.test.ts
  • src/main/providers/local-pty-shell-ready.ts
  • src/main/providers/windows-shell-args.test.ts
  • src/main/providers/windows-shell-args.ts
  • src/main/shell-startup-feature-channel.test.ts
  • src/main/shell-startup-features.ts
  • src/main/shell-startup-launch-intent-fixtures.ts
  • src/main/shell-templates.ts
  • src/main/shell-wrapper-file-writer.ts
  • src/main/shell-wrapper-generated-file-snapshot.test.ts
  • src/main/shell-wrapper-snapshots/daemon-bash-rcfile.txt
  • src/main/shell-wrapper-snapshots/daemon-fish-init.txt
  • src/main/shell-wrapper-snapshots/daemon-zsh-zlogin.txt
  • src/main/shell-wrapper-snapshots/daemon-zsh-zprofile.txt
  • src/main/shell-wrapper-snapshots/daemon-zsh-zshenv.txt
  • src/main/shell-wrapper-snapshots/daemon-zsh-zshrc.txt
  • src/main/shell-wrapper-snapshots/local-bash-rcfile.txt
  • src/main/shell-wrapper-snapshots/local-fish-init.txt
  • src/main/shell-wrapper-snapshots/local-zsh-zlogin.txt
  • src/main/shell-wrapper-snapshots/local-zsh-zprofile.txt
  • src/main/shell-wrapper-snapshots/local-zsh-zshenv.txt
  • src/main/shell-wrapper-snapshots/local-zsh-zshrc.txt
  • src/main/shell-wrapper-snapshots/relay-bash-rcfile.txt
  • src/main/shell-wrapper-snapshots/relay-zsh-zlogin.txt
  • src/main/shell-wrapper-snapshots/relay-zsh-zprofile.txt
  • src/main/shell-wrapper-snapshots/relay-zsh-zshenv.txt
  • src/main/shell-wrapper-snapshots/relay-zsh-zshrc.txt
  • src/main/zsh-scoped-histfile.live-shell.test.ts
  • src/main/zsh-startup-wrapper-builder.ts
  • src/main/zsh-user-config-dir-fixture.ts
  • src/main/zsh-wrapper-dir-ownership.ts
  • src/relay/pty-handler-revive.test.ts
  • src/relay/pty-handler-startup-command-delivery.test.ts
  • src/relay/pty-handler.ts
  • src/relay/pty-shell-launch.test.ts
  • src/relay/pty-shell-launch.ts
  • src/relay/pty-shell-overlay-wrappers.ts

Included review availability: Your plan includes up to 10 reviews per rolling hour; 0 remain after this review.

Comment on lines +828 to +851
const waitsForShellReady =
Boolean(opts.command) &&
(!isCodexStartupCommand ||
shouldUseShellReadyStartupDelivery({
command: opts.command as string,
startupCommandDelivery: opts.startupCommandDelivery
}))
// Why delete: ORCA_SHELL_FEATURES is Orca-owned, and only the launch config
// below may name features for this shell.
delete env.ORCA_SHELL_FEATURES
const shellLaunch = getShellLaunchConfig(
shellPath,
selectShellStartupFeatures({
shellPath,
env,
hasStartupCommand: Boolean(opts.command),
waitsForShellReady,
// Why identical: the identity marker exists so the readiness handshake
// can bind output to the right shell PID.
emitsStartupIdentity: waitsForShellReady
})
// Why: payload-bearing Codex startup text can be dropped by rc-file noise; plain Codex stays markerless for the startup-speed path.
shellLaunch = shouldWaitForShellReady
? getShellReadyLaunchConfig(shellPath)
: getMarkerlessShellLaunchConfig(shellPath)
} else if (opts.command) {
shellLaunch = getShellReadyLaunchConfig(shellPath)
} else {
shellLaunch =
env.ORCA_OPENCODE_CONFIG_DIR ||
env.ORCA_MIMOCODE_HOME ||
env.ORCA_OMP_STATUS_EXTENSION ||
env.ORCA_CODEX_HOME ||
env.ORCA_AGENT_TEAMS_SHIM_DIR
? getMarkerlessShellLaunchConfig(shellPath)
: null
}
if (shellLaunch) {
Object.assign(env, shellLaunch.env)
}
shellArgs = shellLaunch?.args ?? ['-l']
)
Object.assign(env, shellLaunch.env)
shellArgs = shellLaunch.args ?? ['-l']

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 | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Find every consumer of supportsReadyMarker and the daemon-side ready-marker wait.
set -euo pipefail

rg -n -C 8 'supportsReadyMarker' --type=ts
rg -n -C 8 'SHELL_READY_MARKER' --type=ts -g '!**/shell-wrapper-snapshots/**' -g '!**/*.test.ts'

Repository: stablyai/orca

Length of output: 151


🏁 Script executed:

set -euo pipefail
printf '%s\n' '--- readiness symbols ---'
rg -n -C 6 'supportsReadyMarker|SHELL_READY_MARKER|ensureShellReadyWrappers|shouldUseShellReadyStartupDelivery|startupCommandDelivery|waitsForShellReady' --hidden -g '!**/node_modules/**' -g '!**/shell-wrapper-snapshots/**' .
printf '%s\n' '--- candidate file outline ---'
ast-grep outline src/main/daemon/pty-subprocess.ts --view compact
printf '%s\n' '--- relevant implementation ---'
sed -n '730,920p' src/main/daemon/pty-subprocess.ts

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

set -euo pipefail
printf '%s\n' '--- daemon/provider readiness consumers ---'
rg -n -C 10 'supportsReadyMarker|SHELL_READY_MARKER|ensureShellReadyWrappers|shouldUseShellReadyStartupDelivery|startupCommandDelivery|waitsForShellReady' src/main/daemon src/main/providers src/shared
printf '%s\n' '--- pty-subprocess launch path ---'
sed -n '780,900p' src/main/daemon/pty-subprocess.ts
printf '%s\n' '--- local provider readiness path ---'
sed -n '830,900p' src/main/providers/local-pty-provider.ts
sed -n '980,1075p' src/main/providers/local-pty-provider.ts
sed -n '1115,1165p' src/main/providers/local-pty-provider.ts

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

set -euo pipefail
printf '%s\n' '--- pty-subprocess startup and returned capability ---'
rg -n -C 12 'shellLaunch|supportsReadyMarker|shellReady|startupCommand|writeStartup|spawn\(|return \{' src/main/daemon/pty-subprocess.ts
printf '%s\n' '--- launch-config definitions and failure paths ---'
rg -n -C 14 'function getShellLaunchConfig|const getShellLaunchConfig|export .*getShellLaunchConfig|ensureShellReadyWrappers|supportsReadyMarker' src/main/daemon src/main/providers
printf '%s\n' '--- terminal-host capability propagation ---'
sed -n '70,125p' src/main/daemon/terminal-host-session-create.ts
rg -n -C 8 'shellReadySupported|shellReadyTimeoutMs|supportsReadyMarker' src/main/daemon --glob '!*.test.ts'

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

set -euo pipefail
printf '%s\n' '--- daemon startup-command consumers ---'
rg -n -C 14 'startupCommandDelivery|startupCommandDeliveredInShellArgs|opts\.command|command\)' src/main/daemon --glob '!*.test.ts'
printf '%s\n' '--- subprocess creation and write call sites ---'
rg -n -C 12 'createPtySubprocess|spawnSubprocess|\.write\(|proc\.write|subprocess\.write' src/main/daemon --glob '!*.test.ts'
printf '%s\n' '--- session creation implementation ---'
sed -n '1,145p' src/main/daemon/terminal-host-session-create.ts
printf '%s\n' '--- daemon subprocess result contract ---'
sed -n '1080,1160p' src/main/daemon/pty-subprocess.ts

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

set -euo pipefail
printf '%s\n' '--- session shell-ready gate ---'
rg -n -C 16 'shellReadySupported|shellReadyTimeoutMs|STARTUP_COMMAND_READY|ready marker|SHELL_READY_MARKER|shell-ready' src/main/daemon --glob '!*.test.ts'
printf '%s\n' '--- session construction and startup write ---'
sed -n '95,160p' src/main/daemon/terminal-host-session-create.ts
rg -n -C 12 'new Session|shellReadySupported|shellReadyTimeoutMs|buildStartupCommandSubmission|startupCommand' src/main/daemon/session*.ts src/main/daemon/*session*.ts
printf '%s\n' '--- adapter capability calculation ---'
sed -n '600,665p' src/main/daemon/daemon-pty-adapter.ts

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

set -euo pipefail
barrier_file="$(fd -t f 'session-shell-ready-barrier\.ts$' src/main/daemon | head -n 1)"
printf '--- barrier file: %s ---\n' "$barrier_file"
wc -l "$barrier_file"
cat -n "$barrier_file"
printf '%s\n' '--- barrier tests and timeout constants ---'
rg -n -C 10 'SessionShellReadyBarrier|shellReadyTimeoutMs|STARTUP_COMMAND_READY|readySupported|supportsReady|timeout' src/main/daemon --glob '*session-shell-ready*' --glob '*.test.ts'
printf '%s\n' '--- read-only branch model ---'
python3 - <<'PY'
from pathlib import Path
p = next(Path("src/main/daemon").glob("session-shell-ready-barrier.ts"))
s = p.read_text()
checks = {
    "unsupported capability releases immediately": "shellReadySupported" in s and "finish" in s,
    "timeout branch exists": "setTimeout" in s,
    "marker scan exists": "orca-shell-ready" in s or "SHELL_READY_MARKER" in s,
}
for name, value in checks.items():
    print(f"{name}: {value}")
for needle in ("shellReadySupported", "shellReadyTimeoutMs", "setTimeout", "finishShellReady", "release"):
    print(f"\n[{needle}]")
    for i, line in enumerate(s.splitlines(), 1):
        if needle in line:
            lo, hi = max(1, i-3), min(len(s.splitlines()), i+5)
            print("\n".join(f"{n}: {s.splitlines()[n-1]}" for n in range(lo, hi+1)))
PY

Repository: stablyai/orca

Length of output: 242


🏁 Script executed:

set -euo pipefail
barrier_file="$(fd -t f 'session-shell-ready-barrier\.ts$' src/main/daemon | head -n 1)"
printf '%s\n' "--- barrier file: $barrier_file ---"
wc -l "$barrier_file"
cat -n "$barrier_file"
printf '%s\n' '--- barrier tests and timeout constants ---'
rg -n -C 10 'SessionShellReadyBarrier|shellReadyTimeoutMs|STARTUP_COMMAND_READY|readySupported|supportsReady|timeout' src/main/daemon --glob '*session-shell-ready*' --glob '*.test.ts'
printf '%s\n' '--- read-only branch model ---'
python3 - <<'PY'
from pathlib import Path
p = next(Path("src/main/daemon").glob("session-shell-ready-barrier.ts"))
lines = p.read_text().splitlines()
for name, needles in {
    "unsupported capability branch": ("shellReadySupported",),
    "timeout branch": ("setTimeout",),
    "marker scan": ("orca-shell-ready", "SHELL_READY_MARKER"),
    "release path": ("release", "finish"),
}.items():
    print(f"{name}: {any(any(needle in line for needle in needles) for line in lines)}")
for needle in ("shellReadySupported", "shellReadyTimeoutMs", "setTimeout", "finish", "release"):
    print(f"\n[{needle}]")
    for i, line in enumerate(lines, 1):
        if needle in line:
            lo, hi = max(1, i-3), min(len(lines), i+5)
            print("\n".join(f"{n}: {lines[n-1]}" for n in range(lo, hi+1)))

Repository: stablyai/orca

Length of output: 50370


Propagate shellLaunch.supportsReadyMarker to the daemon startup barrier. When wrapper creation fails, the plain shell cannot emit the marker, but the daemon discards this capability and enables the barrier from the shell type alone. The startup command then waits for the configured timeout, 15 seconds by default.

Comment on lines +152 to +153
ORCA_ORIG_ZDOTDIR: resolveInheritedZdotdir(process.env),
ORCA_ZSHENV_SOURCE_DIR: resolveInheritedZshenvSourceDir(process.env),

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Compare every resolveInheritedZdotdir / resolveInheritedZshenvSourceDir call site and its env source.
set -euo pipefail

rg -n -C 6 'resolveInherited(Zdotdir|ZshenvSourceDir)\s*\(' --type=ts

Repository: stablyai/orca

Length of output: 151


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- candidate files ---'
fd -i 'shell-ready\.ts|pty-shell-launch\.ts' .

printf '%s\n' '--- resolver definitions and call sites ---'
rg -n -C 8 'resolveInherited(Zdotdir|ZshenvSourceDir)' . --glob '*.{ts,tsx,js,jsx}'

printf '%s\n' '--- shell-ready structure ---'
ast-grep outline src/main/daemon/shell-ready.ts --lang typescript

printf '%s\n' '--- relay structure ---'
ast-grep outline src/relay/pty-shell-launch.ts --lang typescript

Repository: stablyai/orca

Length of output: 10933


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- daemon shell launch implementation ---'
cat -n src/main/daemon/shell-ready.ts | sed -n '90,180p'

printf '%s\n' '--- relay shell launch implementation ---'
cat -n src/relay/pty-shell-launch.ts | sed -n '50,155p'

printf '%s\n' '--- environment preparation and launch-config callers ---'
rg -n -C 10 'createPtySubprocess|getShellLaunchConfig|RelayShellLaunchConfig|resolvePtyShellPath' src --glob '*.{ts,tsx}'

printf '%s\n' '--- relevant tests and fixtures ---'
rg -n -C 8 'ORCA_ORIG_ZDOTDIR|ORCA_ZSHENV_SOURCE_DIR|ZDOTDIR|createPtySubprocess|getShellLaunchConfig' --glob '*.{test,spec}.{ts,tsx,js,jsx}' --glob '*.{ts,tsx,js,jsx}'

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- daemon launch config ---'
sed -n '118,165p' src/main/daemon/shell-ready.ts

printf '%s\n' '--- relay launch config ---'
sed -n '55,145p' src/relay/pty-shell-launch.ts

printf '%s\n' '--- daemon environment and launch-config handoff ---'
sed -n '630,680p' src/main/daemon/pty-subprocess.ts
sed -n '828,865p' src/main/daemon/pty-subprocess.ts

printf '%s\n' '--- ZDOTDIR-focused tests ---'
rg -n -C 12 'ZDOTDIR|ORCA_ORIG_ZDOTDIR|ORCA_ZSHENV_SOURCE_DIR' src/main/daemon --glob '*.{test,spec}.ts' | head -n 240

printf '%s\n' '--- wrapper consumers ---'
rg -n -C 8 'ORCA_ORIG_ZDOTDIR|ORCA_ZSHENV_SOURCE_DIR' src --glob '*.{ts,tsx}'

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- exact daemon ZDOTDIR-related tests ---'
rg -l 'ZDOTDIR|ORCA_ORIG_ZDOTDIR|ORCA_ZSHENV_SOURCE_DIR' src/main/daemon --glob '*.{test,spec}.ts' |
  while IFS= read -r file; do
    echo "--- $file ---"
    rg -n -C 5 'ZDOTDIR|ORCA_ORIG_ZDOTDIR|ORCA_ZSHENV_SOURCE_DIR' "$file"
  done

printf '%s\n' '--- requested environment deletion implementation ---'
rg -n -C 12 'function deleteRequestedDaemonEnvKeys|deleteRequestedDaemonEnvKeys' src/main/daemon/pty-subprocess.ts src/main/daemon --glob '*.ts' | head -n 160

printf '%s\n' '--- wrapper source resolution ---'
rg -n -C 12 'ORCA_ZSHENV_SOURCE_DIR|zshenvSourceDir|source.*zshenv|ZSHENV' src/main --glob '*.{ts,tsx}' | head -n 220

printf '%s\n' '--- resolver behavior probe ---'
python3 - <<'PY'
from pathlib import Path

source = Path("src/main/zsh-wrapper-dir-ownership.ts").read_text()
start = source.index("export function resolveInheritedZdotdir")
end = source.index("\n}", start) + 2
print(source[start:end])

def usable(value):
    return value if value and value.strip() else None

def resolve(env, fallback=""):
    return usable(env.get("ZDOTDIR")) or usable(env.get("ORCA_ORIG_ZDOTDIR")) or env.get("HOME") or fallback

process_env = {"ZDOTDIR": "/host/config", "HOME": "/host/home"}
spawn_env = {"HOME": "/pane/home"}
print("process.env source:", resolve(process_env))
print("per-spawn source after ZDOTDIR deletion:", resolve(spawn_env))
PY

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- resolver definitions ---'
sed -n '1,65p' src/main/zsh-wrapper-dir-ownership.ts

printf '%s\n' '--- focused environment-resolution verifier ---'
python3 - <<'PY'
def usable(value):
    return value if value and value.strip() and not value.rstrip("/").endswith("/shell-ready/zsh") else None

def resolve_zdotdir(env, home_fallback=""):
    return (
        usable(env.get("ZDOTDIR"))
        or usable(env.get("ORCA_ORIG_ZDOTDIR"))
        or env.get("HOME")
        or home_fallback
    )

def resolve_zshenv_source_dir(env, home_fallback=""):
    return usable(env.get("ZDOTDIR")) or env.get("HOME") or home_fallback

process_env = {
    "HOME": "/host/home",
    "ZDOTDIR": "/host/config",
}
spawn_env = {
    "HOME": "/pane/home",
}
print("daemon/process.env ORCA_ORIG_ZDOTDIR =", resolve_zdotdir(process_env))
print("daemon/process.env ORCA_ZSHENV_SOURCE_DIR =", resolve_zshenv_source_dir(process_env))
print("relay/per-spawn env ORCA_ORIG_ZDOTDIR =", resolve_zdotdir(spawn_env, "/host/home"))
print("relay/per-spawn env ORCA_ZSHENV_SOURCE_DIR =", resolve_zshenv_source_dir(spawn_env, "/host/home"))
assert resolve_zdotdir(process_env) != resolve_zdotdir(spawn_env, "/host/home")
assert resolve_zshenv_source_dir(process_env) != resolve_zshenv_source_dir(spawn_env, "/host/home")
PY

printf '%s\n' '--- launch-config call signature and call ---'
rg -n -C 5 'export function getShellLaunchConfig|const shellLaunch = getShellLaunchConfig' \
  src/main/daemon/shell-ready.ts src/main/daemon/pty-subprocess.ts

Repository: stablyai/orca

Length of output: 4082


Resolve zsh inheritance from the per-spawn environment.

createPtySubprocess applies envToDelete before getShellLaunchConfig, but that function reads process.env. A pane that clears or overrides ZDOTDIR still receives the daemon's values for both ORCA_ORIG_ZDOTDIR and ORCA_ZSHENV_SOURCE_DIR. Pass env to getShellLaunchConfig and resolve both values from it.

Comment on lines +20 to +21
export const renameSyncMock: Mock = vi.fn()
export const rmSyncMock: Mock = vi.fn()

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 | 🟡 Minor | ⚡ Quick win

Reset the new filesystem mocks between tests.

renameSyncMock and rmSyncMock are added to fsModuleMock, but src/main/ipc/pty-ipc-suite-environment.ts does not reset them in beforeEach. Call history or custom implementations can leak into later PTY tests. Add both mockReset() calls beside chmodSyncMock.mockReset().

This is based on the shared suite reset list in src/main/ipc/pty-ipc-suite-environment.ts.

Also applies to: 90-91

Comment on lines 73 to +80
const env: Record<string, string> = {
...config.env,
// Why: these examples inspect startup-file discovery, not the PTY-owner protocol stream.
ORCA_SHELL_STARTUP_IDENTITY: '0',
// Why: these examples inspect startup-file discovery, not the PTY-owner
// protocol stream, so drop the tokens that write to stdout.
ORCA_SHELL_FEATURES: (config.env.ORCA_SHELL_FEATURES ?? '')
.split(',')
.filter((feature) => feature !== 'identity' && feature !== 'markers')
.join(','),

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

Remove the ready feature from this non-PTY fixture.

The helper says it removes features that write to stdout, but it retains ready in ORCA_SHELL_FEATURES. getShellLaunchConfig treats ready as shell-ready marker support, so the wrapper can emit the readiness OSC sequence into stdout and pollute startup-file assertions. Filter ready with identity and markers, or explicitly assert the protocol output.

This follows the launch contract in src/main/providers/local-pty-shell-ready.ts.

Proposed filter update
      ORCA_SHELL_FEATURES: (config.env.ORCA_SHELL_FEATURES ?? '')
        .split(',')
-        .filter((feature) => feature !== 'identity' && feature !== 'markers')
+        .filter(
+          (feature) =>
+            feature !== 'identity' && feature !== 'markers' && feature !== 'ready'
+        )
        .join(','),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const env: Record<string, string> = {
...config.env,
// Why: these examples inspect startup-file discovery, not the PTY-owner protocol stream.
ORCA_SHELL_STARTUP_IDENTITY: '0',
// Why: these examples inspect startup-file discovery, not the PTY-owner
// protocol stream, so drop the tokens that write to stdout.
ORCA_SHELL_FEATURES: (config.env.ORCA_SHELL_FEATURES ?? '')
.split(',')
.filter((feature) => feature !== 'identity' && feature !== 'markers')
.join(','),
const env: Record<string, string> = {
...config.env,
// Why: these examples inspect startup-file discovery, not the PTY-owner
// protocol stream, so drop the tokens that write to stdout.
ORCA_SHELL_FEATURES: (config.env.ORCA_SHELL_FEATURES ?? '')
.split(',')
.filter(
(feature) =>
feature !== 'identity' && feature !== 'markers' && feature !== 'ready'
)
.join(','),

Comment on lines +148 to +160
if __orca_has_feature history; then
if [[ -n "${ORCA_HISTFILE:-}" ]]; then
HISTFILE="$ORCA_HISTFILE"
builtin unset ORCA_HISTFILE
elif [[ "${HISTFILE:-}" == "$ZDOTDIR/.zsh_history" ]]; then
# Why also when Orca injected nothing: /etc/zshrc derived this from Orca's
# wrapper ZDOTDIR, so history would accumulate INSIDE the wrapper dir and the
# user's real history would be invisible — the plain #11044 bug, with no
# per-worktree scoping involved. Matching the exact clobbered value means a
# HISTFILE the user set deliberately is never touched.
HISTFILE="${ORCA_ORIG_ZDOTDIR:-$HOME}/.zsh_history"
fi
fi

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

Unset ORCA_HISTFILE on every epilogue path.

The current code leaves this imported variable set when history is not selected, and also when ORCA_HISTFILE is empty. Keep the history assignment inside the feature guard, but run builtin unset ORCA_HISTFILE after the conditional so the internal path cannot reach later commands or child processes.

Comment on lines +148 to +151
if __orca_has_feature history; then
if [[ -n "${ORCA_HISTFILE:-}" ]]; then
HISTFILE="$ORCA_HISTFILE"
builtin unset ORCA_HISTFILE

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

Consume ORCA_HISTFILE before user startup configuration.

The PR contract requires ORCA_HISTFILE to be consumed and unset. These wrappers wait until after user startup files run. User configuration can then read, unset, or overwrite the variable and disable scoped-history restoration.

  • src/main/shell-wrapper-snapshots/local-zsh-zshenv.txt#L148-L151: capture ORCA_HISTFILE in an internal variable and unset it before sourcing user .zshenv; restore HISTFILE from the internal value in the epilogue.
  • src/main/shell-wrapper-snapshots/relay-zsh-zshenv.txt#L69-L72: capture and unset ORCA_HISTFILE before sourcing the user .zshenv; use the captured value in the epilogue.
  • src/main/shell-wrapper-snapshots/relay-bash-rcfile.txt#L57-L59: capture and unset ORCA_HISTFILE before sourcing profile files; restore HISTFILE from the captured value afterward.
📍 Affects 3 files
  • src/main/shell-wrapper-snapshots/local-zsh-zshenv.txt#L148-L151 (this comment)
  • src/main/shell-wrapper-snapshots/relay-zsh-zshenv.txt#L69-L72
  • src/main/shell-wrapper-snapshots/relay-bash-rcfile.txt#L57-L59

Comment on lines +174 to +196
// Why: relay wrapper files persist under ~/.orca-relay across app upgrades.
// Existence alone is not enough; stale wrappers would miss later fixes such
// as preserving post-.zshenv ZDOTDIR.
const stale = files.filter(([path, content]) => readFileOrNull(path) !== content)
if (stale.length > 0 && !writeShellWrapperFiles(stale, '[relay/shell-overlay]')) {
return false
}
return files.every(([path]) => isNonEmptyFile(path))
}

function readFileOrNull(path: string): string | null {
try {
return readFileSync(path, 'utf8')
} catch {
return null
}
}

function isNonEmptyFile(path: string): boolean {
try {
return statSync(path).size > 0
} catch {
return false

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 | ⚡ Quick win

Do not read existing wrapper paths before launch.

readFileSync() blocks when a wrapper path is a FIFO. A FIFO in ~/.orca-relay can hang the relay process during PTY startup. The false fallback cannot run while the synchronous read is blocked.

Write the complete wrapper set with writeShellWrapperFiles() instead of comparing file contents first.

Proposed fix
-  const stale = files.filter(([path, content]) => readFileOrNull(path) !== content)
-  if (stale.length > 0 && !writeShellWrapperFiles(stale, '[relay/shell-overlay]')) {
+  if (!writeShellWrapperFiles(files, '[relay/shell-overlay]')) {
     return false
   }
   return files.every(([path]) => isNonEmptyFile(path))
 }
-
-function readFileOrNull(path: string): string | null {
-  try {
-    return readFileSync(path, 'utf8')
-  } catch {
-    return null
-  }
-}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Why: relay wrapper files persist under ~/.orca-relay across app upgrades.
// Existence alone is not enough; stale wrappers would miss later fixes such
// as preserving post-.zshenv ZDOTDIR.
const stale = files.filter(([path, content]) => readFileOrNull(path) !== content)
if (stale.length > 0 && !writeShellWrapperFiles(stale, '[relay/shell-overlay]')) {
return false
}
return files.every(([path]) => isNonEmptyFile(path))
}
function readFileOrNull(path: string): string | null {
try {
return readFileSync(path, 'utf8')
} catch {
return null
}
}
function isNonEmptyFile(path: string): boolean {
try {
return statSync(path).size > 0
} catch {
return false
// Why: relay wrapper files persist under ~/.orca-relay across app upgrades.
// Existence alone is not enough; stale wrappers would miss later fixes such
// as preserving post-.zshenv ZDOTDIR.
if (!writeShellWrapperFiles(files, '[relay/shell-overlay]')) {
return false
}
return files.every(([path]) => isNonEmptyFile(path))
}
function isNonEmptyFile(path: string): boolean {
try {
return statSync(path).size > 0
} catch {
return false

…ing relay wrapping

Review follow-ups on the feature-channel PR.

- `emulate -L zsh` as the epilogue's first statement. It runs after the user's
  own config, so `setopt no_unset` made the precmd_functions append a fatal
  error that returned from the whole function (no ready widget, ZDOTDIR left at
  Orca's wrapper dir), and `setopt ksh_arrays` made the 1-based feature
  subscript drop whichever feature is listed first.
- The `/etc/zshrc` HISTFILE repair is no longer behind the `history` guard: it
  undoes damage Orca's own ZDOTDIR caused, so it must also run for a shell that
  re-enters the wrapper after the allowlist was consumed.
- The relay keeps its own wrapping gate. Its .zshenv resolves the user's config
  dir from a ZDOTDIR Orca has already overwritten, so wrapping a remote pane
  just for `history` cost a relocated-ZDOTDIR user their whole shell config.
- A failed primary spawn no longer leaks the primary shell's launch env
  (wrapper ZDOTDIR + feature channel) into an unwrapped fallback pane.

@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/relay/pty-shell-launch.ts (1)

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

Reduce this comment to its decision.

Lines 57-67 repeat implementation detail that the code already shows. Keep only the reason that history-only relay zsh panes stay unwrapped.

Proposed change
-/**
- * Overlay values the relay's own wrapper re-applies. Only these (or a startup
- * command) may pull a remote zsh off the plain login fast path.
- *
- * Why the relay gates on its own list instead of `features.length`: its .zshenv
- * uses the overlay strategy, which resolves the user's config dir from a ZDOTDIR
- * Orca has already overwritten. A remote user whose zsh config lives in a
- * relocated ZDOTDIR therefore loses that config the moment the pane is wrapped,
- * so wrapping a pane just for `history` would trade a real config for a history
- * repair. Reconciling the overlay and discovery strategies is a follow-up.
- */
+// Keep history-only relay zsh panes unwrapped because the overlay wrapper cannot restore a relocated ZDOTDIR.

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: a2a3235d-bf8f-444f-9cf0-2bd1541905d2

📥 Commits

Reviewing files that changed from the base of the PR and between 2326cbb and 574cce4.

📒 Files selected for processing (10)
  • src/main/providers/local-pty-utils.test.ts
  • src/main/providers/local-pty-utils.ts
  • src/main/shell-startup-feature-channel.test.ts
  • src/main/shell-wrapper-snapshots/daemon-zsh-zshenv.txt
  • src/main/shell-wrapper-snapshots/local-zsh-zshenv.txt
  • src/main/shell-wrapper-snapshots/relay-zsh-zshenv.txt
  • src/main/zsh-scoped-histfile.live-shell.test.ts
  • src/main/zsh-startup-wrapper-builder.ts
  • src/relay/pty-shell-launch.test.ts
  • src/relay/pty-shell-launch.ts
🚧 Files skipped from review as they are similar to previous changes (6)
  • src/main/shell-wrapper-snapshots/daemon-zsh-zshenv.txt
  • src/relay/pty-shell-launch.test.ts
  • src/main/zsh-scoped-histfile.live-shell.test.ts
  • src/main/shell-wrapper-snapshots/local-zsh-zshenv.txt
  • src/main/shell-wrapper-snapshots/relay-zsh-zshenv.txt
  • src/main/zsh-startup-wrapper-builder.ts

Included review availability: Your plan includes up to 10 reviews per rolling hour; 2 remain after this review.

… across Orca instances

The relay-specific gate added last round rested on a false premise:
main's hasOverlayRestoreEnv already included ORCA_REMOTE_CLI_BIN_DIR, and
ssh-pty-spawn-env sets that on every SSH pane whose session has a CLI
bridge — so ordinary remote zsh panes were already wrapped. The gate only
bit where remoteCliBridgeEnv is null (a host too old to report its
platform), where it silently dropped that pane's worktree history. All
three transports now share the features.length rule.

HISTFILE stays exported, so a newly wrapped pane handed the worktree
history path to every child, including a nested Orca whose panes then all
hit injectHistoryEnv's check-before-set and appended into the launching
worktree's file. Same class as the fish_history fix in #15195: recognise a
path Orca minted and drop it before the check, on the desktop, daemon and
relay injection paths and both history-disabled branches.

Also: run the epilogue from the wrapper .zshrc when zsh is in sh/ksh
emulation, since sourcehome() then reads $HOME/.zlogin and the wrapper's
.zlogin never runs; track fallback launch-env keys per attempt rather than
once from the primary; and guard the cross-file epilogue call so a wrapper
dir shared by two builds degrades quietly.
…leted marker vars from tests

- .zprofile/.zshrc/.zlogin each define __orca_resolve_user_config_dir. They
  called it on line 2 while only .zshenv defined it, so a wrapper dir written by
  two concurrently installed builds printed three "command not found" and
  skipped the user's entire zsh config. New live-shell test covers it.
- Retarget every remaining ORCA_SHELL_READY_MARKER/ORCA_SHELL_STARTUP_IDENTITY
  reference onto ORCA_SHELL_FEATURES, or delete it where the key is now dead.
- isOrcaMintedHistFile requires a leading '/', so a relative path of the same
  shape stays the user's.
- Drop an unused no-control-regex disable, and register the two real-zsh suites
  in the dedicated shell-contracts lane.

@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/shell-templates.ts (1)

48-79: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Shorten the resolver documentation.

Keep one concise sentence that states the mixed-build compatibility reason. Remove the detailed failure sequence from these comments.

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: e707d9c9-1673-4f15-911a-9888d428d837

📥 Commits

Reviewing files that changed from the base of the PR and between a83d873 and c7d5f2f.

📒 Files selected for processing (23)
  • .github/workflows/pr.yml
  • config/scripts/pr-workflow-parallelism.test.mjs
  • src/main/daemon/bash-prompt-command-composition.test.ts
  • src/main/daemon/pty-subprocess.test.ts
  • src/main/ipc/pty-hidden-at-spawn-mark.test.ts
  • src/main/providers/__tests__/shell-ready-framework/README.md
  • src/main/providers/local-pty-shell-ready-wrapper-generation.test.ts
  • src/main/pty/codex-preflight-profile-path-rewrite.test.ts
  • src/main/shell-startup-feature-channel.test.ts
  • src/main/shell-templates.ts
  • src/main/shell-wrapper-snapshots/daemon-zsh-zlogin.txt
  • src/main/shell-wrapper-snapshots/daemon-zsh-zprofile.txt
  • src/main/shell-wrapper-snapshots/daemon-zsh-zshrc.txt
  • src/main/shell-wrapper-snapshots/local-zsh-zlogin.txt
  • src/main/shell-wrapper-snapshots/local-zsh-zprofile.txt
  • src/main/shell-wrapper-snapshots/local-zsh-zshrc.txt
  • src/main/shell-wrapper-snapshots/relay-zsh-zlogin.txt
  • src/main/shell-wrapper-snapshots/relay-zsh-zprofile.txt
  • src/main/shell-wrapper-snapshots/relay-zsh-zshrc.txt
  • src/main/terminal-history.test.ts
  • src/main/worktree-history-file-path.ts
  • src/main/zsh-startup-wrapper-builder.ts
  • src/main/zsh-wrapper-version-mismatch.live-shell.test.ts
🚧 Files skipped from review as they are similar to previous changes (11)
  • src/main/shell-wrapper-snapshots/daemon-zsh-zprofile.txt
  • src/main/worktree-history-file-path.ts
  • src/main/shell-wrapper-snapshots/local-zsh-zshrc.txt
  • src/main/terminal-history.test.ts
  • src/main/shell-wrapper-snapshots/relay-zsh-zlogin.txt
  • src/main/shell-wrapper-snapshots/local-zsh-zlogin.txt
  • src/main/shell-startup-feature-channel.test.ts
  • src/main/shell-wrapper-snapshots/relay-zsh-zprofile.txt
  • src/main/shell-wrapper-snapshots/relay-zsh-zshrc.txt
  • src/main/zsh-startup-wrapper-builder.ts
  • src/main/providers/local-pty-shell-ready-wrapper-generation.test.ts

Included review availability: Your plan includes up to 10 reviews per rolling hour; 4 remain after this review.

… sh emulation

Widening wrapping from overlay/startup panes to every zsh pane turned three
latent wrapper defects into user-visible ones.

- The config-dir resolver used `REPLY`, zsh's shared scratch global, as its
  out-parameter. `typeset -r REPLY` in a user config made the wrapper's first
  executable assignment fatal, `typeset -i REPLY` silently resolved every path
  to 0; both left HISTFILE inside Orca's wrapper dir. It now writes an
  Orca-private `_orca_resolved_config_dir`, declared `typeset -g` so the
  rename introduces no `warn_create_global` noise. A new rule test fails on any
  generated wrapper file that writes a global outside Orca's namespace.

- The daemon dropped an inherited HISTFILE but never an inherited
  ORCA_HISTFILE, which now both wraps a pane the client scoped nothing for and
  re-exports another worktree's history path. The relay had the same gap on its
  isolation-off and revive paths. Both now mirror the desktop.

- A user .zshenv or .zprofile ending in `emulate sh` makes zsh ignore ZDOTDIR,
  so no later wrapper file is read and the epilogue never runs. Nothing can
  repair HISTFILE from there, so the wrapper now detects the emulation and
  hands the pane back unwrapped instead of leaving history somewhere invisible.

Also `typeset -g __orca_in_command` so the OSC 133 preexec hook prints no
warning under `setopt warn_create_global`.
@nwparker
nwparker merged commit 66a5e5d into main Aug 18, 2026
53 of 55 checks passed
nwparker added a commit that referenced this pull request Aug 18, 2026
…king to probe zsh emulation (STA-4682)

Two residuals left behind by #15236 and #15258.

Relay revive called resolveDefaultShell() and ignored the entry's shell
override, so a restarted relay handed the user a PowerShell pane where a
WSL one had been -- and with it the host default shell's history rather
than the worktree-scoped one #15236 injects on spawn. The override and
the requested distro are now serialized (optional fields; state from an
older relay still revives the default shell) and re-resolved through the
same allowlist a fresh spawn uses, so revive re-launches the same shell
with the same guest-visible HISTFILE and the same WSLENV carrier. A bad
override degrades that one pane instead of failing the whole batch.

The wrapper's three `$(emulate)` probes each fork a zsh carrying
everything the user's config has loaded, and since wrapping widened to
every zsh pane every pane pays for them. Each probe now sits behind a
fork-free option test that is true whenever `emulate sh`/`emulate ksh`
has run; the exact probe still runs when that test passes, so no answer
changes. Measured on zsh 5.9 / macOS: 9.97 ms/run unwrapped, 14.20 ms/run
wrapped, 12.27 ms/run wrapped after -- about half the wrapper's cost.
nwparker added a commit that referenced this pull request Aug 18, 2026
…king to probe zsh emulation (STA-4682)

Two residuals left behind by #15236 and #15258.

Relay revive called resolveDefaultShell() and ignored the entry's shell
override, so a restarted relay handed the user a PowerShell pane where a
WSL one had been -- and with it the host default shell's history rather
than the worktree-scoped one #15236 injects on spawn. The override and
the requested distro are now serialized (optional fields; state from an
older relay still revives the default shell) and re-resolved through the
same allowlist a fresh spawn uses, so revive re-launches the same shell
with the same guest-visible HISTFILE and the same WSLENV carrier. A bad
override degrades that one pane instead of failing the whole batch.

The wrapper's three `$(emulate)` probes each fork a zsh carrying
everything the user's config has loaded, and since wrapping widened to
every zsh pane every pane pays for them. Each probe now sits behind a
fork-free option test that is true whenever `emulate sh`/`emulate ksh`
has run; the exact probe still runs when that test passes, so no answer
changes. Measured on zsh 5.9 / macOS: 9.97 ms/run unwrapped, 14.20 ms/run
wrapped, 12.27 ms/run wrapped after -- about half the wrapper's cost.
nwparker added a commit that referenced this pull request Aug 18, 2026
…king to probe zsh emulation (STA-4682) (#15361)

* fix(shell): carry a WSL pane's shell across relay revive and stop forking to probe zsh emulation (STA-4682)

Two residuals left behind by #15236 and #15258.

Relay revive called resolveDefaultShell() and ignored the entry's shell
override, so a restarted relay handed the user a PowerShell pane where a
WSL one had been -- and with it the host default shell's history rather
than the worktree-scoped one #15236 injects on spawn. The override and
the requested distro are now serialized (optional fields; state from an
older relay still revives the default shell) and re-resolved through the
same allowlist a fresh spawn uses, so revive re-launches the same shell
with the same guest-visible HISTFILE and the same WSLENV carrier. A bad
override degrades that one pane instead of failing the whole batch.

The wrapper's three `$(emulate)` probes each fork a zsh carrying
everything the user's config has loaded, and since wrapping widened to
every zsh pane every pane pays for them. Each probe now sits behind a
fork-free option test that is true whenever `emulate sh`/`emulate ksh`
has run; the exact probe still runs when that test passes, so no answer
changes. Measured on zsh 5.9 / macOS: 9.97 ms/run unwrapped, 14.20 ms/run
wrapped, 12.27 ms/run wrapped after -- about half the wrapper's cost.

* fix(shell): harden the revive override path and silence the option probe on an exotic zsh

Readiness-review follow-ups on this branch.

- `[[ -o <name> ]]` prints "no such option" to stderr and returns false rather
  than aborting, so a zsh lacking one of the three Bourne option names would put
  that text in the user's pane. All three predate every supported zsh, so
  `2>/dev/null` is belt and braces -- but the belt costs nothing.
- Bound the WSL distro name revive replays into `wsl.exe -d <name>`. It is the
  one field this branch newly routes from untrusted serialized state into argv,
  and reviveEntry's stated job is to re-apply fresh-spawn bounds.
- Skip a pane whose overridden shell can no longer spawn instead of letting the
  throw escape the revive loop and cost every later entry its state. Skipping,
  not falling back to the host default shell: substituting a different shell is
  the defect the override exists to fix, and the args and history env are built
  for the shell that is gone. The worktree-removal fence throws before this,
  outside reviveEntry, so it stays a hard failure.
nwparker added a commit that referenced this pull request Aug 19, 2026
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 added a commit that referenced this pull request Aug 19, 2026
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 added a commit that referenced this pull request Aug 20, 2026
… hook (STA-4786) (#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 (#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.

* 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

#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

#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.

- #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.
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 21, 2026
…ive feature channel (stablyai#15258)

* fix(shell): repair worktree HISTFILE in plain zsh panes via one positive feature channel

A plain zsh pane — no startup command, no agent overlay — was never wrapped, so
Orca's HISTFILE repair never ran in it. macOS `/etc/zshrc` assigns
`HISTFILE=${ZDOTDIR:-$HOME}/.zsh_history` with no check-before-set and runs
before any file Orca controls, so per-worktree history was a silent no-op for
every ordinary pane on the primary platform.

Wrapping those panes needs a way to say which wrapper features a shell should
turn on. That channel is one exported variable, ORCA_SHELL_FEATURES, carrying a
comma-separated positive allowlist from a closed set (history, markers, ready,
identity, overlay). The wrapper .zshenv reads it into a plain, non-exported
array and unsets it in its first executable lines, before the user's own
.zshenv — so the selection survives .zshenv -> .zprofile -> .zshrc -> .zlogin in
this process but physically cannot reach a child. There is no negative or
suppression variable anywhere; an absent or inherited value can only ever mean
fewer features. ORCA_HISTFILE is consumed and destroyed the same way, which
removes the root cause of stablyai#11146 instead of patching it.

All order-sensitive wrapper work now lives in one `__orca_shell_epilogue`
defined in .zshenv and invoked exactly once, from .zshrc for a non-login shell
and .zlogin for a login shell, with each feature an independent guard.

Selection is a pure function of spawn env and launch intent, so a pane wrapped
only for history gets no OSC 133 and is observably identical to the unwrapped
pane it used to be.

Generation is now fail-closed: wrapper files are written to a temp name and
renamed, every required path is verified non-empty, and ZDOTDIR is only set when
that holds. Previously a failed write still pointed ZDOTDIR at an empty dir and
the user silently lost their entire zsh config.

Orca also recognised only its own `*/shell-ready/zsh` dir shape when deciding
what the user's ZDOTDIR was, so being launched from any other terminal that had
hijacked ZDOTDIR captured that as the user's config dir. Ownership is now
established positively — a stamped marker file, or Orca's own dir shape for
wrappers written by older builds — and an inherited ZDOTDIR holding no zsh
startup file is ignored. No vendor is detected by name.

* fix(shell): make the zsh epilogue option-proof and stop history widening relay wrapping

Review follow-ups on the feature-channel PR.

- `emulate -L zsh` as the epilogue's first statement. It runs after the user's
  own config, so `setopt no_unset` made the precmd_functions append a fatal
  error that returned from the whole function (no ready widget, ZDOTDIR left at
  Orca's wrapper dir), and `setopt ksh_arrays` made the 1-based feature
  subscript drop whichever feature is listed first.
- The `/etc/zshrc` HISTFILE repair is no longer behind the `history` guard: it
  undoes damage Orca's own ZDOTDIR caused, so it must also run for a shell that
  re-enters the wrapper after the allowlist was consumed.
- The relay keeps its own wrapping gate. Its .zshenv resolves the user's config
  dir from a ZDOTDIR Orca has already overwritten, so wrapping a remote pane
  just for `history` cost a relocated-ZDOTDIR user their whole shell config.
- A failed primary spawn no longer leaks the primary shell's launch env
  (wrapper ZDOTDIR + feature channel) into an unwrapped fallback pane.

* fix(shell): drop the relay wrapping gate and stop HISTFILE inheriting across Orca instances

The relay-specific gate added last round rested on a false premise:
main's hasOverlayRestoreEnv already included ORCA_REMOTE_CLI_BIN_DIR, and
ssh-pty-spawn-env sets that on every SSH pane whose session has a CLI
bridge — so ordinary remote zsh panes were already wrapped. The gate only
bit where remoteCliBridgeEnv is null (a host too old to report its
platform), where it silently dropped that pane's worktree history. All
three transports now share the features.length rule.

HISTFILE stays exported, so a newly wrapped pane handed the worktree
history path to every child, including a nested Orca whose panes then all
hit injectHistoryEnv's check-before-set and appended into the launching
worktree's file. Same class as the fish_history fix in stablyai#15195: recognise a
path Orca minted and drop it before the check, on the desktop, daemon and
relay injection paths and both history-disabled branches.

Also: run the epilogue from the wrapper .zshrc when zsh is in sh/ksh
emulation, since sourcehome() then reads $HOME/.zlogin and the wrapper's
.zlogin never runs; track fallback launch-env keys per attempt rather than
once from the primary; and guard the cross-file epilogue call so a wrapper
dir shared by two builds degrades quietly.

* fix(shell): make every wrapper file self-sufficient and retire the deleted marker vars from tests

- .zprofile/.zshrc/.zlogin each define __orca_resolve_user_config_dir. They
  called it on line 2 while only .zshenv defined it, so a wrapper dir written by
  two concurrently installed builds printed three "command not found" and
  skipped the user's entire zsh config. New live-shell test covers it.
- Retarget every remaining ORCA_SHELL_READY_MARKER/ORCA_SHELL_STARTUP_IDENTITY
  reference onto ORCA_SHELL_FEATURES, or delete it where the key is now dead.
- isOrcaMintedHistFile requires a leading '/', so a relative path of the same
  shape stays the user's.
- Drop an unused no-control-regex disable, and register the two real-zsh suites
  in the dedicated shell-contracts lane.

* fix(shell): stop the zsh wrapper colliding on REPLY and degrade under sh emulation

Widening wrapping from overlay/startup panes to every zsh pane turned three
latent wrapper defects into user-visible ones.

- The config-dir resolver used `REPLY`, zsh's shared scratch global, as its
  out-parameter. `typeset -r REPLY` in a user config made the wrapper's first
  executable assignment fatal, `typeset -i REPLY` silently resolved every path
  to 0; both left HISTFILE inside Orca's wrapper dir. It now writes an
  Orca-private `_orca_resolved_config_dir`, declared `typeset -g` so the
  rename introduces no `warn_create_global` noise. A new rule test fails on any
  generated wrapper file that writes a global outside Orca's namespace.

- The daemon dropped an inherited HISTFILE but never an inherited
  ORCA_HISTFILE, which now both wraps a pane the client scoped nothing for and
  re-exports another worktree's history path. The relay had the same gap on its
  isolation-off and revive paths. Both now mirror the desktop.

- A user .zshenv or .zprofile ending in `emulate sh` makes zsh ignore ZDOTDIR,
  so no later wrapper file is read and the epilogue never runs. Nothing can
  repair HISTFILE from there, so the wrapper now detects the emulation and
  hands the pane back unwrapped instead of leaving history somewhere invisible.

Also `typeset -g __orca_in_command` so the OSC 133 preexec hook prints no
warning under `setopt warn_create_global`.
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 21, 2026
…king to probe zsh emulation (STA-4682) (stablyai#15361)

* fix(shell): carry a WSL pane's shell across relay revive and stop forking to probe zsh emulation (STA-4682)

Two residuals left behind by stablyai#15236 and stablyai#15258.

Relay revive called resolveDefaultShell() and ignored the entry's shell
override, so a restarted relay handed the user a PowerShell pane where a
WSL one had been -- and with it the host default shell's history rather
than the worktree-scoped one stablyai#15236 injects on spawn. The override and
the requested distro are now serialized (optional fields; state from an
older relay still revives the default shell) and re-resolved through the
same allowlist a fresh spawn uses, so revive re-launches the same shell
with the same guest-visible HISTFILE and the same WSLENV carrier. A bad
override degrades that one pane instead of failing the whole batch.

The wrapper's three `$(emulate)` probes each fork a zsh carrying
everything the user's config has loaded, and since wrapping widened to
every zsh pane every pane pays for them. Each probe now sits behind a
fork-free option test that is true whenever `emulate sh`/`emulate ksh`
has run; the exact probe still runs when that test passes, so no answer
changes. Measured on zsh 5.9 / macOS: 9.97 ms/run unwrapped, 14.20 ms/run
wrapped, 12.27 ms/run wrapped after -- about half the wrapper's cost.

* fix(shell): harden the revive override path and silence the option probe on an exotic zsh

Readiness-review follow-ups on this branch.

- `[[ -o <name> ]]` prints "no such option" to stderr and returns false rather
  than aborting, so a zsh lacking one of the three Bourne option names would put
  that text in the user's pane. All three predate every supported zsh, so
  `2>/dev/null` is belt and braces -- but the belt costs nothing.
- Bound the WSL distro name revive replays into `wsl.exe -d <name>`. It is the
  one field this branch newly routes from untrusted serialized state into argv,
  and reviveEntry's stated job is to re-apply fresh-spawn bounds.
- Skip a pane whose overridden shell can no longer spawn instead of letting the
  throw escape the revive loop and cost every later entry its state. Skipping,
  not falling back to the host default shell: substituting a different shell is
  the defect the override exists to fix, and the args and history env are built
  for the shell that is gone. The worktree-removal fence throws before this,
  outside reviveEntry, so it stays a hard failure.
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
…ive feature channel (stablyai#15258)

* fix(shell): repair worktree HISTFILE in plain zsh panes via one positive feature channel

A plain zsh pane — no startup command, no agent overlay — was never wrapped, so
Orca's HISTFILE repair never ran in it. macOS `/etc/zshrc` assigns
`HISTFILE=${ZDOTDIR:-$HOME}/.zsh_history` with no check-before-set and runs
before any file Orca controls, so per-worktree history was a silent no-op for
every ordinary pane on the primary platform.

Wrapping those panes needs a way to say which wrapper features a shell should
turn on. That channel is one exported variable, ORCA_SHELL_FEATURES, carrying a
comma-separated positive allowlist from a closed set (history, markers, ready,
identity, overlay). The wrapper .zshenv reads it into a plain, non-exported
array and unsets it in its first executable lines, before the user's own
.zshenv — so the selection survives .zshenv -> .zprofile -> .zshrc -> .zlogin in
this process but physically cannot reach a child. There is no negative or
suppression variable anywhere; an absent or inherited value can only ever mean
fewer features. ORCA_HISTFILE is consumed and destroyed the same way, which
removes the root cause of stablyai#11146 instead of patching it.

All order-sensitive wrapper work now lives in one `__orca_shell_epilogue`
defined in .zshenv and invoked exactly once, from .zshrc for a non-login shell
and .zlogin for a login shell, with each feature an independent guard.

Selection is a pure function of spawn env and launch intent, so a pane wrapped
only for history gets no OSC 133 and is observably identical to the unwrapped
pane it used to be.

Generation is now fail-closed: wrapper files are written to a temp name and
renamed, every required path is verified non-empty, and ZDOTDIR is only set when
that holds. Previously a failed write still pointed ZDOTDIR at an empty dir and
the user silently lost their entire zsh config.

Orca also recognised only its own `*/shell-ready/zsh` dir shape when deciding
what the user's ZDOTDIR was, so being launched from any other terminal that had
hijacked ZDOTDIR captured that as the user's config dir. Ownership is now
established positively — a stamped marker file, or Orca's own dir shape for
wrappers written by older builds — and an inherited ZDOTDIR holding no zsh
startup file is ignored. No vendor is detected by name.

* fix(shell): make the zsh epilogue option-proof and stop history widening relay wrapping

Review follow-ups on the feature-channel PR.

- `emulate -L zsh` as the epilogue's first statement. It runs after the user's
  own config, so `setopt no_unset` made the precmd_functions append a fatal
  error that returned from the whole function (no ready widget, ZDOTDIR left at
  Orca's wrapper dir), and `setopt ksh_arrays` made the 1-based feature
  subscript drop whichever feature is listed first.
- The `/etc/zshrc` HISTFILE repair is no longer behind the `history` guard: it
  undoes damage Orca's own ZDOTDIR caused, so it must also run for a shell that
  re-enters the wrapper after the allowlist was consumed.
- The relay keeps its own wrapping gate. Its .zshenv resolves the user's config
  dir from a ZDOTDIR Orca has already overwritten, so wrapping a remote pane
  just for `history` cost a relocated-ZDOTDIR user their whole shell config.
- A failed primary spawn no longer leaks the primary shell's launch env
  (wrapper ZDOTDIR + feature channel) into an unwrapped fallback pane.

* fix(shell): drop the relay wrapping gate and stop HISTFILE inheriting across Orca instances

The relay-specific gate added last round rested on a false premise:
main's hasOverlayRestoreEnv already included ORCA_REMOTE_CLI_BIN_DIR, and
ssh-pty-spawn-env sets that on every SSH pane whose session has a CLI
bridge — so ordinary remote zsh panes were already wrapped. The gate only
bit where remoteCliBridgeEnv is null (a host too old to report its
platform), where it silently dropped that pane's worktree history. All
three transports now share the features.length rule.

HISTFILE stays exported, so a newly wrapped pane handed the worktree
history path to every child, including a nested Orca whose panes then all
hit injectHistoryEnv's check-before-set and appended into the launching
worktree's file. Same class as the fish_history fix in stablyai#15195: recognise a
path Orca minted and drop it before the check, on the desktop, daemon and
relay injection paths and both history-disabled branches.

Also: run the epilogue from the wrapper .zshrc when zsh is in sh/ksh
emulation, since sourcehome() then reads $HOME/.zlogin and the wrapper's
.zlogin never runs; track fallback launch-env keys per attempt rather than
once from the primary; and guard the cross-file epilogue call so a wrapper
dir shared by two builds degrades quietly.

* fix(shell): make every wrapper file self-sufficient and retire the deleted marker vars from tests

- .zprofile/.zshrc/.zlogin each define __orca_resolve_user_config_dir. They
  called it on line 2 while only .zshenv defined it, so a wrapper dir written by
  two concurrently installed builds printed three "command not found" and
  skipped the user's entire zsh config. New live-shell test covers it.
- Retarget every remaining ORCA_SHELL_READY_MARKER/ORCA_SHELL_STARTUP_IDENTITY
  reference onto ORCA_SHELL_FEATURES, or delete it where the key is now dead.
- isOrcaMintedHistFile requires a leading '/', so a relative path of the same
  shape stays the user's.
- Drop an unused no-control-regex disable, and register the two real-zsh suites
  in the dedicated shell-contracts lane.

* fix(shell): stop the zsh wrapper colliding on REPLY and degrade under sh emulation

Widening wrapping from overlay/startup panes to every zsh pane turned three
latent wrapper defects into user-visible ones.

- The config-dir resolver used `REPLY`, zsh's shared scratch global, as its
  out-parameter. `typeset -r REPLY` in a user config made the wrapper's first
  executable assignment fatal, `typeset -i REPLY` silently resolved every path
  to 0; both left HISTFILE inside Orca's wrapper dir. It now writes an
  Orca-private `_orca_resolved_config_dir`, declared `typeset -g` so the
  rename introduces no `warn_create_global` noise. A new rule test fails on any
  generated wrapper file that writes a global outside Orca's namespace.

- The daemon dropped an inherited HISTFILE but never an inherited
  ORCA_HISTFILE, which now both wraps a pane the client scoped nothing for and
  re-exports another worktree's history path. The relay had the same gap on its
  isolation-off and revive paths. Both now mirror the desktop.

- A user .zshenv or .zprofile ending in `emulate sh` makes zsh ignore ZDOTDIR,
  so no later wrapper file is read and the epilogue never runs. Nothing can
  repair HISTFILE from there, so the wrapper now detects the emulation and
  hands the pane back unwrapped instead of leaving history somewhere invisible.

Also `typeset -g __orca_in_command` so the OSC 133 preexec hook prints no
warning under `setopt warn_create_global`.
dallascrilley pushed a commit to dallascrilley/orca that referenced this pull request Aug 27, 2026
…king to probe zsh emulation (STA-4682) (stablyai#15361)

* fix(shell): carry a WSL pane's shell across relay revive and stop forking to probe zsh emulation (STA-4682)

Two residuals left behind by stablyai#15236 and stablyai#15258.

Relay revive called resolveDefaultShell() and ignored the entry's shell
override, so a restarted relay handed the user a PowerShell pane where a
WSL one had been -- and with it the host default shell's history rather
than the worktree-scoped one stablyai#15236 injects on spawn. The override and
the requested distro are now serialized (optional fields; state from an
older relay still revives the default shell) and re-resolved through the
same allowlist a fresh spawn uses, so revive re-launches the same shell
with the same guest-visible HISTFILE and the same WSLENV carrier. A bad
override degrades that one pane instead of failing the whole batch.

The wrapper's three `$(emulate)` probes each fork a zsh carrying
everything the user's config has loaded, and since wrapping widened to
every zsh pane every pane pays for them. Each probe now sits behind a
fork-free option test that is true whenever `emulate sh`/`emulate ksh`
has run; the exact probe still runs when that test passes, so no answer
changes. Measured on zsh 5.9 / macOS: 9.97 ms/run unwrapped, 14.20 ms/run
wrapped, 12.27 ms/run wrapped after -- about half the wrapper's cost.

* fix(shell): harden the revive override path and silence the option probe on an exotic zsh

Readiness-review follow-ups on this branch.

- `[[ -o <name> ]]` prints "no such option" to stderr and returns false rather
  than aborting, so a zsh lacking one of the three Bourne option names would put
  that text in the user's pane. All three predate every supported zsh, so
  `2>/dev/null` is belt and braces -- but the belt costs nothing.
- Bound the WSL distro name revive replays into `wsl.exe -d <name>`. It is the
  one field this branch newly routes from untrusted serialized state into argv,
  and reviveEntry's stated job is to re-apply fresh-spawn bounds.
- Skip a pane whose overridden shell can no longer spawn instead of letting the
  throw escape the revive loop and cost every later entry its state. Skipping,
  not falling back to the host default shell: substituting a different shell is
  the defect the override exists to fix, and the args and history env are built
  for the shell that is gone. The worktree-removal fence throws before this,
  outside reviveEntry, so it stays a hard failure.
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
…ive feature channel (stablyai#15258)

* fix(shell): repair worktree HISTFILE in plain zsh panes via one positive feature channel

A plain zsh pane — no startup command, no agent overlay — was never wrapped, so
Orca's HISTFILE repair never ran in it. macOS `/etc/zshrc` assigns
`HISTFILE=${ZDOTDIR:-$HOME}/.zsh_history` with no check-before-set and runs
before any file Orca controls, so per-worktree history was a silent no-op for
every ordinary pane on the primary platform.

Wrapping those panes needs a way to say which wrapper features a shell should
turn on. That channel is one exported variable, ORCA_SHELL_FEATURES, carrying a
comma-separated positive allowlist from a closed set (history, markers, ready,
identity, overlay). The wrapper .zshenv reads it into a plain, non-exported
array and unsets it in its first executable lines, before the user's own
.zshenv — so the selection survives .zshenv -> .zprofile -> .zshrc -> .zlogin in
this process but physically cannot reach a child. There is no negative or
suppression variable anywhere; an absent or inherited value can only ever mean
fewer features. ORCA_HISTFILE is consumed and destroyed the same way, which
removes the root cause of stablyai#11146 instead of patching it.

All order-sensitive wrapper work now lives in one `__orca_shell_epilogue`
defined in .zshenv and invoked exactly once, from .zshrc for a non-login shell
and .zlogin for a login shell, with each feature an independent guard.

Selection is a pure function of spawn env and launch intent, so a pane wrapped
only for history gets no OSC 133 and is observably identical to the unwrapped
pane it used to be.

Generation is now fail-closed: wrapper files are written to a temp name and
renamed, every required path is verified non-empty, and ZDOTDIR is only set when
that holds. Previously a failed write still pointed ZDOTDIR at an empty dir and
the user silently lost their entire zsh config.

Orca also recognised only its own `*/shell-ready/zsh` dir shape when deciding
what the user's ZDOTDIR was, so being launched from any other terminal that had
hijacked ZDOTDIR captured that as the user's config dir. Ownership is now
established positively — a stamped marker file, or Orca's own dir shape for
wrappers written by older builds — and an inherited ZDOTDIR holding no zsh
startup file is ignored. No vendor is detected by name.

* fix(shell): make the zsh epilogue option-proof and stop history widening relay wrapping

Review follow-ups on the feature-channel PR.

- `emulate -L zsh` as the epilogue's first statement. It runs after the user's
  own config, so `setopt no_unset` made the precmd_functions append a fatal
  error that returned from the whole function (no ready widget, ZDOTDIR left at
  Orca's wrapper dir), and `setopt ksh_arrays` made the 1-based feature
  subscript drop whichever feature is listed first.
- The `/etc/zshrc` HISTFILE repair is no longer behind the `history` guard: it
  undoes damage Orca's own ZDOTDIR caused, so it must also run for a shell that
  re-enters the wrapper after the allowlist was consumed.
- The relay keeps its own wrapping gate. Its .zshenv resolves the user's config
  dir from a ZDOTDIR Orca has already overwritten, so wrapping a remote pane
  just for `history` cost a relocated-ZDOTDIR user their whole shell config.
- A failed primary spawn no longer leaks the primary shell's launch env
  (wrapper ZDOTDIR + feature channel) into an unwrapped fallback pane.

* fix(shell): drop the relay wrapping gate and stop HISTFILE inheriting across Orca instances

The relay-specific gate added last round rested on a false premise:
main's hasOverlayRestoreEnv already included ORCA_REMOTE_CLI_BIN_DIR, and
ssh-pty-spawn-env sets that on every SSH pane whose session has a CLI
bridge — so ordinary remote zsh panes were already wrapped. The gate only
bit where remoteCliBridgeEnv is null (a host too old to report its
platform), where it silently dropped that pane's worktree history. All
three transports now share the features.length rule.

HISTFILE stays exported, so a newly wrapped pane handed the worktree
history path to every child, including a nested Orca whose panes then all
hit injectHistoryEnv's check-before-set and appended into the launching
worktree's file. Same class as the fish_history fix in stablyai#15195: recognise a
path Orca minted and drop it before the check, on the desktop, daemon and
relay injection paths and both history-disabled branches.

Also: run the epilogue from the wrapper .zshrc when zsh is in sh/ksh
emulation, since sourcehome() then reads $HOME/.zlogin and the wrapper's
.zlogin never runs; track fallback launch-env keys per attempt rather than
once from the primary; and guard the cross-file epilogue call so a wrapper
dir shared by two builds degrades quietly.

* fix(shell): make every wrapper file self-sufficient and retire the deleted marker vars from tests

- .zprofile/.zshrc/.zlogin each define __orca_resolve_user_config_dir. They
  called it on line 2 while only .zshenv defined it, so a wrapper dir written by
  two concurrently installed builds printed three "command not found" and
  skipped the user's entire zsh config. New live-shell test covers it.
- Retarget every remaining ORCA_SHELL_READY_MARKER/ORCA_SHELL_STARTUP_IDENTITY
  reference onto ORCA_SHELL_FEATURES, or delete it where the key is now dead.
- isOrcaMintedHistFile requires a leading '/', so a relative path of the same
  shape stays the user's.
- Drop an unused no-control-regex disable, and register the two real-zsh suites
  in the dedicated shell-contracts lane.

* fix(shell): stop the zsh wrapper colliding on REPLY and degrade under sh emulation

Widening wrapping from overlay/startup panes to every zsh pane turned three
latent wrapper defects into user-visible ones.

- The config-dir resolver used `REPLY`, zsh's shared scratch global, as its
  out-parameter. `typeset -r REPLY` in a user config made the wrapper's first
  executable assignment fatal, `typeset -i REPLY` silently resolved every path
  to 0; both left HISTFILE inside Orca's wrapper dir. It now writes an
  Orca-private `_orca_resolved_config_dir`, declared `typeset -g` so the
  rename introduces no `warn_create_global` noise. A new rule test fails on any
  generated wrapper file that writes a global outside Orca's namespace.

- The daemon dropped an inherited HISTFILE but never an inherited
  ORCA_HISTFILE, which now both wraps a pane the client scoped nothing for and
  re-exports another worktree's history path. The relay had the same gap on its
  isolation-off and revive paths. Both now mirror the desktop.

- A user .zshenv or .zprofile ending in `emulate sh` makes zsh ignore ZDOTDIR,
  so no later wrapper file is read and the epilogue never runs. Nothing can
  repair HISTFILE from there, so the wrapper now detects the emulation and
  hands the pane back unwrapped instead of leaving history somewhere invisible.

Also `typeset -g __orca_in_command` so the OSC 133 preexec hook prints no
warning under `setopt warn_create_global`.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…king to probe zsh emulation (STA-4682) (stablyai#15361)

* fix(shell): carry a WSL pane's shell across relay revive and stop forking to probe zsh emulation (STA-4682)

Two residuals left behind by stablyai#15236 and stablyai#15258.

Relay revive called resolveDefaultShell() and ignored the entry's shell
override, so a restarted relay handed the user a PowerShell pane where a
WSL one had been -- and with it the host default shell's history rather
than the worktree-scoped one stablyai#15236 injects on spawn. The override and
the requested distro are now serialized (optional fields; state from an
older relay still revives the default shell) and re-resolved through the
same allowlist a fresh spawn uses, so revive re-launches the same shell
with the same guest-visible HISTFILE and the same WSLENV carrier. A bad
override degrades that one pane instead of failing the whole batch.

The wrapper's three `$(emulate)` probes each fork a zsh carrying
everything the user's config has loaded, and since wrapping widened to
every zsh pane every pane pays for them. Each probe now sits behind a
fork-free option test that is true whenever `emulate sh`/`emulate ksh`
has run; the exact probe still runs when that test passes, so no answer
changes. Measured on zsh 5.9 / macOS: 9.97 ms/run unwrapped, 14.20 ms/run
wrapped, 12.27 ms/run wrapped after -- about half the wrapper's cost.

* fix(shell): harden the revive override path and silence the option probe on an exotic zsh

Readiness-review follow-ups on this branch.

- `[[ -o <name> ]]` prints "no such option" to stderr and returns false rather
  than aborting, so a zsh lacking one of the three Bourne option names would put
  that text in the user's pane. All three predate every supported zsh, so
  `2>/dev/null` is belt and braces -- but the belt costs nothing.
- Bound the WSL distro name revive replays into `wsl.exe -d <name>`. It is the
  one field this branch newly routes from untrusted serialized state into argv,
  and reviveEntry's stated job is to re-apply fresh-spawn bounds.
- Skip a pane whose overridden shell can no longer spawn instead of letting the
  throw escape the revive loop and cost every later entry its state. Skipping,
  not falling back to the host default shell: substituting a different shell is
  the defect the override exists to fix, and the args and history env are built
  for the shell that is gone. The worktree-removal fence throws before this,
  outside reviveEntry, so it stays a hard failure.
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.

[Bug]: Per-worktree shell history is silently disabled on macOS — /etc/zshrc overwrites the injected HISTFILE

1 participant