Repository navigation
fix(shell): repair worktree HISTFILE in plain zsh panes via one positive feature channel - #15258
Conversation
…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.
351c0fc to
2326cbb
Compare
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (23)
🚧 Files skipped from review as they are similar to previous changes (16)
Included review availability: Your plan includes up to 10 reviews per rolling hour; 3 remain after this review. 📝 WalkthroughWalkthroughThe change replaces legacy shell readiness and identity environment variables with the Merge Risk: 🟡 Moderate · up to 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)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 8
🧹 Nitpick comments (4)
src/main/providers/local-pty-provider.ts (1)
868-870: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse
SHELL_STARTUP_FEATURE_ENVinstead of the literal key.
src/relay/pty-handler.tsclears the same channel through the exported constant. This site hardcodesORCA_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 winUse
SHELL_STARTUP_FEATURE_ENVinstead of the literal key.This line hardcodes
ORCA_SHELL_FEATURES. The name is already exported asSHELL_STARTUP_FEATURE_ENVfrom../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 valueVariable names still describe the old wrapper layout. The epilogue moved into
.zshenv, but these variables read.zshenvwhile keeping names that say.zshrcor.zlogin. A reader cannot tell which file an assertion covers.
src/main/daemon/shell-ready.test.ts#L642-L645: renamezshrctozshenvand remove thezloginalias, then update the assertions in that test.src/main/providers/local-pty-shell-ready-wrapper-generation.test.ts#L286-L289: renamezshrctozshenvand remove thezloginalias, then update the assertions in that test.src/main/providers/local-pty-shell-ready-wrapper-generation.test.ts#L331-L332: renamezshRctozshenvbecause it holdsgetZshShellReadyWrapperFiles().zshenv.src/main/zsh-scoped-histfile.live-shell.test.ts (1)
82-101: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winIsolate the shell-ready wrapper root in a temporary user-data directory.
getShellLaunchConfigwrites wrappers underORCA_USER_DATA_PATHortmpdir()when unset. This path is outsidewithTempHome, so the test does not clean it. If wrapper creation fails,launch.env.ZDOTDIRis undefined and the assertion reports a misleading failure. Use a temporaryORCA_USER_DATA_PATHwithsetTestUserDataPathandimportFreshLocalPtyShellReady, followingsrc/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
📒 Files selected for processing (66)
src/main/daemon/daemon-bash-shell-ready-rcfile.tssrc/main/daemon/daemon-zsh-shell-ready-wrapper-spec.tssrc/main/daemon/pty-subprocess-managed-agent-env.test.tssrc/main/daemon/pty-subprocess.tssrc/main/daemon/shell-ready.test.tssrc/main/daemon/shell-ready.tssrc/main/ipc/pty-ipc-mock-registry.tssrc/main/ipc/pty-ipc-spawn-drivers.tssrc/main/ipc/pty-ipc-suite-environment.tssrc/main/ipc/pty-listener-teardown-and-orphans.test.tssrc/main/ipc/pty-login-shell-startup-commands.test.tssrc/main/ipc/pty-wsl-cwd-validation.test.tssrc/main/providers/__tests__/shell-ready-framework/shell-script-test.tssrc/main/providers/local-pty-provider-foreground-process.test.tssrc/main/providers/local-pty-provider-io-events.test.tssrc/main/providers/local-pty-provider-session-inventory.test.tssrc/main/providers/local-pty-provider-shell-readiness.test.tssrc/main/providers/local-pty-provider-shutdown.test.tssrc/main/providers/local-pty-provider-spawn-cwd-safety.test.tssrc/main/providers/local-pty-provider-spawn-env.test.tssrc/main/providers/local-pty-provider-spawn-session.test.tssrc/main/providers/local-pty-provider-test-harness.tssrc/main/providers/local-pty-provider-windows-shell-launch.test.tssrc/main/providers/local-pty-provider.tssrc/main/providers/local-pty-shell-ready-bash-rcfile.tssrc/main/providers/local-pty-shell-ready-test-harness.tssrc/main/providers/local-pty-shell-ready-wrapper-generation.test.tssrc/main/providers/local-pty-shell-ready-wrapper-generation.tssrc/main/providers/local-pty-shell-ready-wrapper-root.tssrc/main/providers/local-pty-shell-ready-zsh-launch-environment.test.tssrc/main/providers/local-pty-shell-ready.tssrc/main/providers/windows-shell-args.test.tssrc/main/providers/windows-shell-args.tssrc/main/shell-startup-feature-channel.test.tssrc/main/shell-startup-features.tssrc/main/shell-startup-launch-intent-fixtures.tssrc/main/shell-templates.tssrc/main/shell-wrapper-file-writer.tssrc/main/shell-wrapper-generated-file-snapshot.test.tssrc/main/shell-wrapper-snapshots/daemon-bash-rcfile.txtsrc/main/shell-wrapper-snapshots/daemon-fish-init.txtsrc/main/shell-wrapper-snapshots/daemon-zsh-zlogin.txtsrc/main/shell-wrapper-snapshots/daemon-zsh-zprofile.txtsrc/main/shell-wrapper-snapshots/daemon-zsh-zshenv.txtsrc/main/shell-wrapper-snapshots/daemon-zsh-zshrc.txtsrc/main/shell-wrapper-snapshots/local-bash-rcfile.txtsrc/main/shell-wrapper-snapshots/local-fish-init.txtsrc/main/shell-wrapper-snapshots/local-zsh-zlogin.txtsrc/main/shell-wrapper-snapshots/local-zsh-zprofile.txtsrc/main/shell-wrapper-snapshots/local-zsh-zshenv.txtsrc/main/shell-wrapper-snapshots/local-zsh-zshrc.txtsrc/main/shell-wrapper-snapshots/relay-bash-rcfile.txtsrc/main/shell-wrapper-snapshots/relay-zsh-zlogin.txtsrc/main/shell-wrapper-snapshots/relay-zsh-zprofile.txtsrc/main/shell-wrapper-snapshots/relay-zsh-zshenv.txtsrc/main/shell-wrapper-snapshots/relay-zsh-zshrc.txtsrc/main/zsh-scoped-histfile.live-shell.test.tssrc/main/zsh-startup-wrapper-builder.tssrc/main/zsh-user-config-dir-fixture.tssrc/main/zsh-wrapper-dir-ownership.tssrc/relay/pty-handler-revive.test.tssrc/relay/pty-handler-startup-command-delivery.test.tssrc/relay/pty-handler.tssrc/relay/pty-shell-launch.test.tssrc/relay/pty-shell-launch.tssrc/relay/pty-shell-overlay-wrappers.ts
Included review availability: Your plan includes up to 10 reviews per rolling hour; 0 remain after this review.
| 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'] |
There was a problem hiding this comment.
🩺 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.tsRepository: 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.tsRepository: 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.tsRepository: 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.tsRepository: 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)))
PYRepository: 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.
| ORCA_ORIG_ZDOTDIR: resolveInheritedZdotdir(process.env), | ||
| ORCA_ZSHENV_SOURCE_DIR: resolveInheritedZshenvSourceDir(process.env), |
There was a problem hiding this comment.
🗄️ 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=tsRepository: 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 typescriptRepository: 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))
PYRepository: 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.tsRepository: 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.
| export const renameSyncMock: Mock = vi.fn() | ||
| export const rmSyncMock: Mock = vi.fn() |
There was a problem hiding this comment.
🩺 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
| 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(','), |
There was a problem hiding this comment.
🎯 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.
| 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(','), |
| 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 |
There was a problem hiding this comment.
🎯 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.
| if __orca_has_feature history; then | ||
| if [[ -n "${ORCA_HISTFILE:-}" ]]; then | ||
| HISTFILE="$ORCA_HISTFILE" | ||
| builtin unset ORCA_HISTFILE |
There was a problem hiding this comment.
🎯 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: captureORCA_HISTFILEin an internal variable and unset it before sourcing user.zshenv; restoreHISTFILEfrom the internal value in the epilogue.src/main/shell-wrapper-snapshots/relay-zsh-zshenv.txt#L69-L72: capture and unsetORCA_HISTFILEbefore sourcing the user.zshenv; use the captured value in the epilogue.src/main/shell-wrapper-snapshots/relay-bash-rcfile.txt#L57-L59: capture and unsetORCA_HISTFILEbefore sourcing profile files; restoreHISTFILEfrom 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-L72src/main/shell-wrapper-snapshots/relay-bash-rcfile.txt#L57-L59
| // 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 |
There was a problem hiding this comment.
🩺 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.
| // 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.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/relay/pty-shell-launch.ts (1)
57-73: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReduce 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
📒 Files selected for processing (10)
src/main/providers/local-pty-utils.test.tssrc/main/providers/local-pty-utils.tssrc/main/shell-startup-feature-channel.test.tssrc/main/shell-wrapper-snapshots/daemon-zsh-zshenv.txtsrc/main/shell-wrapper-snapshots/local-zsh-zshenv.txtsrc/main/shell-wrapper-snapshots/relay-zsh-zshenv.txtsrc/main/zsh-scoped-histfile.live-shell.test.tssrc/main/zsh-startup-wrapper-builder.tssrc/relay/pty-shell-launch.test.tssrc/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.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/shell-templates.ts (1)
48-79: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winShorten 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
📒 Files selected for processing (23)
.github/workflows/pr.ymlconfig/scripts/pr-workflow-parallelism.test.mjssrc/main/daemon/bash-prompt-command-composition.test.tssrc/main/daemon/pty-subprocess.test.tssrc/main/ipc/pty-hidden-at-spawn-mark.test.tssrc/main/providers/__tests__/shell-ready-framework/README.mdsrc/main/providers/local-pty-shell-ready-wrapper-generation.test.tssrc/main/pty/codex-preflight-profile-path-rewrite.test.tssrc/main/shell-startup-feature-channel.test.tssrc/main/shell-templates.tssrc/main/shell-wrapper-snapshots/daemon-zsh-zlogin.txtsrc/main/shell-wrapper-snapshots/daemon-zsh-zprofile.txtsrc/main/shell-wrapper-snapshots/daemon-zsh-zshrc.txtsrc/main/shell-wrapper-snapshots/local-zsh-zlogin.txtsrc/main/shell-wrapper-snapshots/local-zsh-zprofile.txtsrc/main/shell-wrapper-snapshots/local-zsh-zshrc.txtsrc/main/shell-wrapper-snapshots/relay-zsh-zlogin.txtsrc/main/shell-wrapper-snapshots/relay-zsh-zprofile.txtsrc/main/shell-wrapper-snapshots/relay-zsh-zshrc.txtsrc/main/terminal-history.test.tssrc/main/worktree-history-file-path.tssrc/main/zsh-startup-wrapper-builder.tssrc/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`.
…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.
…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.
…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.
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.
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.
… 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.
…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`.
…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.
… 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.
…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`.
…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.
… 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.
…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`.
…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.
… 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.
ELI5
Every Orca worktree is supposed to get its own shell history. On macOS the system's
/etc/zshrcoverwritesHISTFILEon 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
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_MARKERandORCA_SHELL_STARTUP_IDENTITYare gone, including the: '0'pins insrc/relay/pty-handler.ts..zshenvconsumes it in its first executable lines, before the user's.zshenvis sourced:_orca_shell_featuresis a plain, non-exported shell variable: it survives.zshenv -> .zprofile -> .zshrc -> .zloginin 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 theif test "$ORCA_SHELL_READY_MARKER" = 1gate is gone from the init text.ORCA_HISTFILEis consume-and-destroy too: the epilogue doesHISTFILE=$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 TypeScriptdelete env.ORCA_HISTFILEcalls stay as belt-and-braces but are no longer load-bearing.HISTFILEitself stays exported.HISTFILEstays exported, a wrapped pane now hands the worktree history path to everything it launches — including another Orca.src/main/worktree-history-file-path.tsdrops an inheritedHISTFILEthat 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-suppliedHISTFILEstill 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 forfish_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_epiloguedefined in the wrapper.zshenvand invoked exactly once — from the end of.zshrcfor a non-login shell, from the end of.zloginfor 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 toprecmd_functions/preexec_functions),ready(thezle-line-initOSC 777 widget with its existing prior-widget chaining).identitystays early in.zshenv, gated on the snapshotted array. The epilogue ends by restoring the user's realZDOTDIR, unsetting_orca_shell_features, andunfunction-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_unsetmadeprecmd_functions=(… ${precmd_functions[@]})a fatal parameter not set, andsetopt ksh_arrays(also implied byemulate sh/emulate ksh) made the 1-based[(Ie)…]feature subscript return0for whichever feature is listed first.emulate -L zshrestores zsh-native option state for the body andLOCAL_OPTIONSputs the user's options back on return.The
/etc/zshrcHISTFILE repair is not behind a feature guard. It undoes damage the wrapper's ownZDOTDIRcaused, 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'sZDOTDIR) but never the epilogue that restores it. Itseliffires only whenHISTFILEis byte-identical to$ZDOTDIR/.zsh_historywith$ZDOTDIRbeing Orca's own wrapper dir, so that branch never touches aHISTFILEthe user set deliberately. Theifbranch is not so narrow, and the earlier claim that "aHISTFILEthe user set deliberately is never touched" was only true of theelif: whenever Orca injected anORCA_HISTFILEit assigns it unconditionally, which overrides aHISTFILEthe user set inside their own.zshrc. AHISTFILEalready present in the spawn env cannot collide with it —injectHistoryEnv's check-before-set means Orca never mintsORCA_HISTFILEin that case. For every pane Orca actually launches this is equivalent to the guarded form (features.length > 0⟺history ∈ featuresfor zsh).One launch config
getShellReadyLaunchConfig/getMarkerlessShellLaunchConfigcollapse intogetShellLaunchConfig(shellPath, features)(local and daemon) plusgetRelayShellLaunchConfig. Selection isselectShellStartupFeatures(...)— a pure function of spawn env + launch intent, insrc/main/shell-startup-features.ts:overlayhistoryORCA_HISTFILE, or the pane was already wrappedmarkersreadyidentityEmpty token set ⇒ do not wrap at all and do not set the variable.
historyis zsh-only because the unguarded HISTFILE assignment lives in the system zshrc; bash has no equivalent, and wrapping bash via--rcfilefor history alone would swap its login startup-file chain for Orca's approximation of one.Fail-closed generation
writeShellWrapperFileswrites each file to a temp name and renames, and generation returns a boolean.ZDOTDIRis 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 pointedZDOTDIRat an empty dir and the user silently lost their entire zsh config, on every pane, until it was noticed. The relay'sensureOverlayRestoreWrappers(which can throwEACCESstraight throughgetRelayShellLaunchConfigon 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 hijackedZDOTDIR, 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-wrappermarker file Orca writes into its wrapper dirs, or Orca's own*/shell-ready/zshshape for wrappers written by older builds. Additionally, an inheritedZDOTDIRcontaining no readable.zshenv/.zshrc/.zprofile/.zloginis 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
HISTFILEinto the spawn env. On macOS,/etc/zshrccontains an unguardedHISTFILE=${ZDOTDIR:-$HOME}/.zsh_historythat 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:
Why not #15197
#15197 introduced a new regression in each of three review rounds, twice by the same mechanism:
env.ORCA_HISTFILEbut 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.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_HISTFILEreaching a pane it was not meant for) rather than patching the symptom.Also closes the
HISTFILEhalf of the same inheritance class (a wrapped pane exporting its worktree history path to a nested Orca), the sibling of thefish_historyfix 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/zshrcpresent. The clobber-premised assertions are probed, not hardcoded to a platform (systemZshrcClobbersHistfilelaunches a real login zsh with an injectedHISTFILEand checks whether it survives). On this machine the probe returned true, so both clobber-premised assertions inzsh-scoped-histfile.live-shell.test.tsran 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:selectShellStartupFeaturesgivenenv.ORCA_SHELL_FEATURES = 'overlay,markers,ready,identity,history'and nothing else returns[]— an inherited value is not an input and cannot enable anything.ORCA_SHELL_FEATURES: ''plus an injectedORCA_HISTFILEstill returns['history']— there is no value of the variable that disables anything.getShellLaunchConfig('/bin/zsh', ['history'])with a staleprocess.env.ORCA_SHELL_FEATURES = 'overlay,markers,ready,identity'publishes exactlyhistory.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.tsseedsprocess.env.ORCA_SHELL_FEATURES = 'ready,identity,markers,overlay'before a revive and asserts the spawned pane gets neitherreadynoridentity— the case the deleted: '0'pins used to cover.src/main/zsh-scoped-histfile.live-shell.test.tsassertsORCA_HISTFILEis empty in the launched shell after the epilogue consumed it.Behaviour parity
src/main/shell-startup-feature-channel.test.tsbuilds a temp$HOMEwhose.zshenv/.zprofile/.zshrc/.zlogineach announce that they ran, then launches the same command through (a) the real history-only launch config and (b) a plainzsh -l, and compares the full output: startup-file order,precmd_functions,preexec_functions,widgets[zle-line-init]. They are identical,precmd_functionsis 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 withZDOTDIRexplicitly 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_unsetin the user's.zshrc:Because everything now lives in one function, that error returned from the epilogue and skipped the
readywidget and the finalZDOTDIRrestore — before this PR the same error only truncated the wrapper.zshrc, and.zloginstill did both. Withsetopt ksh_arraysthe feature lookup silently dropped the first token (overlayfor an agent pane, soOPENCODE_CONFIG_DIR/CODEX_HOMEwere not restored).emulate -L zshas the epilogue's first line fixes both, plussh_word_splitandemulate shfor 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'soverlay-user-zdotdir.zshenvwould lose a relocated userZDOTDIR. The premise about which panes were newly wrapped was wrong:origin/main'shasOverlayRestoreEnvalready includedORCA_REMOTE_CLI_BIN_DIR(src/relay/pty-shell-launch.ts:53).src/main/providers/ssh-pty-spawn-env.tssetsORCA_REMOTE_CLI_BIN_DIRon every SSH pane whenever the CLI bridge exists, andssh-relay-session.tspopulatesremoteCliBridgeEnvfor every relay session whose host reports its platform.So ordinary remote zsh panes were already wrapped on
main, the relocated-ZDOTDIRdefect 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,remoteCliBridgeEnvisnull, no overlay key is set, and the gate kept that pane unwrapped — silently losing its worktree history, whichfeatures.length > 0repairs. 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 noORCA_REMOTE_CLI_BIN_DIR— a configuration production never produces — is replaced by three tests built from the realbuildSshPtySpawnEnvoutput.3 — the HISTFILE repair lost its self-healing property (P2). Putting the
/etc/zshrcclobber repair behindif __orca_has_feature historymeant a zsh that re-enters the wrapper with Orca'sZDOTDIRinherited but the (deliberately destroyed) allowlist absent keptHISTFILE=<orca-wrapper-dir>/.zsh_history— silently reproducing #11044. The repair is now emitted ungated, as it was onmain.4 — the shell-fallback path leaked the previous attempt's launch env (P2).
spawnShellWithFallbackmerged the fallback's launch env into the same object without clearing the primary's, and an unwrapped fallback (/bin/bashwith no features) contributes{}. A bash pane therefore inheritedORCA_SHELL_FEATURES=historyandZDOTDIR=<userData>/shell-ready/zsh, which nothing in that pane consumes — so typingzshthere loaded Orca's wrapper via the staleZDOTDIRand 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 ownZDOTDIR/ORCA_SHELL_FEATURESinto the second. The key list is also passed in from the launch config the provider already computed, instead of re-invokinggetShellReadyConfig(shellPath)— for zsh/bash that call re-runsensureShellReadyWrappers()and rewrites six files purely to read back key names.5 — the PR widened the identical leak on
HISTFILEthat it closes onORCA_HISTFILE(P1).HISTFILEstays 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/zshrchad already overwritten it with$HOME/.zsh_history, so the worktree value never escaped the pane. Measured: a child seesHISTFILE=[/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 fromstripInheritedBuildModeEnv(process.env), andinjectHistoryEnv's check-before-set (src/main/terminal-history.ts) early-returns on anyHISTFILE, so every pane of the nested app, in every worktree, appended into worktree A's history file. Same bug class as the inheritedfish_historyfixed in #15195 (3d29a2604ed), and the same shape of fix:src/main/worktree-history-file-path.tsrecognises a path Orca itself minted (desktopterminal-history/<hash>/<file>, desktop-WSLterminal-history-wsl/<distro>/<hash>/<file>, relay.orca-remote/terminal-history/<hash>-<file>) and drops only that, before the check-before-set. AHISTFILEthe user set themselves still wins. Applied on the desktop injection path, the desktop history-disabled branch, the daemon subprocess spawn,injectRelayHistoryEnv, and the relay'sbuildSpawnEnv(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 vsmain). zsh'ssourcehome()ignoresZDOTDIRonce the shell is inEMULATE_SH/EMULATE_KSH, so a user.zshrcending inemulate shmakes a login shell read$HOME/.zlogininstead of the wrapper's — the epilogue never ran. Measured on zsh 5.9:mainstill registered the OSC 133 hooks (its.zshrccarried them inline), this branch registered nothing, the ready widget never registered (so startup-command delivery waited out the pre-ready timeout), andHISTFILEwas left at<wrapper dir>/.zsh_history— #11044 itself. The wrapper.zshrcnow runs the epilogue when[[ ! -o login || "$(emulate 2>/dev/null)" != zsh ]]. Ordering is preserved for every normal login shell (the.zlogininvocation still runs after the user's own.zlogin); only in the emulation case does the epilogue run earlier, where the user's.zlogincan undo its overlay restores — which beats not running it at all. An old zsh with no query form ofemulateprints nothing, fails the comparison and runs the epilogue from.zshrctoo; the once-flag makes the later.zlogincall 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,.zshrcand.zlogineach begin with__orca_resolve_user_config_dir "${ORCA_ORIG_ZDOTDIR:-$HOME}", a function only.zshenvdefined. Measured on zsh 5.9 / macOS 15 with this branch's three files beside an older.zshenv:So the cost was not "the epilogue's features":
$REPLYwas 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_BLOCKis 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;.zshenvis 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_IDENTITYare 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") assertedORCA_SHELL_READY_MARKER: '0'inside anobjectContainingon the spawn env and failed in CI. Repo-wide sweep and disposition:src/main/ipc/pty-hidden-at-spawn-mark.test.ts:415ORCA_SHELL_FEATURES: 'overlay,history,markers'(the real selection for that pane: overlay env, worktree history, no startup command ⇒ noready)src/main/daemon/pty-subprocess.test.ts(×6)toBeUndefined()retargeted toORCA_SHELL_FEATURES; the old assertion had become vacuoussrc/main/daemon/bash-prompt-command-composition.test.ts:32ORCA_SHELL_FEATURES: 'ready'(live bash, same intent)src/main/providers/local-pty-shell-ready-wrapper-generation.test.ts:54ORCA_SHELL_FEATURES: 'ready'(live bash, same intent)src/main/pty/codex-preflight-profile-path-rewrite.test.ts:75-76ORCA_SHELL_FEATURESalready means no markers, so both keys were deadsrc/main/providers/__tests__/shell-ready-framework/README.md:42getShellLaunchConfig()+selectShellStartupFeatures()src/main/shell-startup-features.ts:6-7No harness scrub was needed for hermeticity: production now
deletesORCA_SHELL_FEATURESandORCA_HISTFILEfrom the spawn env on every path beforeselectShellStartupFeaturesruns, so a developer's own exported values cannot reach the selection. That is what made the oldORCA_SHELL_READY_MARKERpins fragile (they read straight offprocess.env) and is structurally gone.9 — the
HISTFILEscrub matched a shape with no Orca token (nit, tightened + justified).isOrcaMintedHistFilenow 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 underterminal-historyholding a file named exactlyzsh_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 (ElectronuserData), the daemon subprocess (no Electron), and the relay on a remote host.10 — the config-dir resolver collided on zsh's shared
REPLYglobal (P0, regression vsmain).__orca_resolve_user_config_dirusedREPLYas its out-parameter, and this PR emits that block at the top of all four wrapper files, on every zsh pane.REPLYis 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:.zshrcends intypeset -r REPLY__orca_resolve_user_config_dir:1: read-only variable: REPLYprinted into the pane; the assignment is fatal, so the wrapper file aborts at its first executable line, the epilogue never runs,ZDOTDIRstays at<wrapper>/zsh,HISTFILE=<wrapper>/zsh/.zsh_history,ORCA_HISTFILEleaks to every childHISTFILE=<worktree>/zsh_history,ZDOTDIR=$HOME,ORCA_HISTFILEconsumed, nothing printedtypeset -i REPLY0; same wrongHISTFILE, ZDOTDIR exported empty, epilogue skippedmainnever touchedREPLY(its snapshots use_orca_homeonly), 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 withtypeset -g— a plain assignment would have traded theREPLYcollision for awarn_create_globalwarning on every call, since.zshrc/.zlogincall 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.
REPLYwas 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 orexportwhose 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 withexpected { 'zsh/.zshenv': [ 'REPLY' ] } to deeply equal { 'zsh/.zshenv': [] }.11 — the daemon and the relay dropped an inherited
HISTFILEbut never an inheritedORCA_HISTFILE(P1). Follow-up #5 addeddropInheritedOrcaHistFileon five paths;ORCA_HISTFILE— which is also exported into every pane, and which the bash wrapper never consumes — was only cleared whereinjectHistoryEnv/injectRelayHistoryEnvran.createPtySubprocessbuilds{...stripInheritedBuildModeEnv(process.env), ...opts.env}and deleted neither; the relay'sbuildSpawnEnvdeleted it only viainjectRelayHistoryEnv, i.e. never on the isolation-off or revive paths. This PR is what makes that bite:selectShellStartupFeaturesselectshistoryonBoolean(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"). Onmainthe 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 shin a user.zshenvor.zprofileskipped the wrapper entirely (P1, regression vsmain) — the pane now degrades to unwrapped. Follow-up #6 handled emulation entered from the user's.zshrc. Entered earlier, it is worse: zsh'ssourcehome()ignoresZDOTDIRfrom 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$HOMEstartup files load normally. Reproduced on zsh 5.9, plain pane,features=history:ZDOTDIR=[<wrapper>/zsh],HISTFILE=[<wrapper>/zsh/.zsh_history],ORCA_HISTFILEstill exported, epilogue never ran — the shell looks completely normal while history goes somewhere the user will never find and~/.zsh_historystops growing. Onmainthat pane was unwrapped and correctly gotHISTFILE=$HOME/.zsh_history, so widening wrapping turned "isolation off" into "history written somewhere invisible".Nothing can repair
HISTFILEfrom there —/etc/zshrcassigns it after both.zshenvand.zprofile, so running the epilogue early (the.zshrcfix from #6) repairs nothing. The wrapper therefore does the only other thing worth doing: after sourcing the user's file it checkscase "$(emulate 2>/dev/null)" in sh|ksh), and if so restoresZDOTDIRto the user's own config dir, consumesORCA_HISTFILE, drops its own variables and functions, andreturns. The pane is then exactly the unwrapped pane it was before this PR rather than something worse. Measured after the fix, both trigger files:HISTFILEequal to an unwrapped run's,ZDOTDIR=$HOME,ORCA_HISTFILEunset.Two details worth stating. The match is positive (
sh|ksh), not!= zsh, so a zsh too old for the query form ofemulate— 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 throughZDOTDIR, so anything that had already entered emulation (a system/etc/zshenvor/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_globalnoise above every command (nit, fixed).__orca_in_command=1in__orca_osc133_preexeccreates a global inside a function, whichsetopt warn_create_globalreports on every command line. Not a regression (identical onmain, andmarkersis gated onwrappedBeforeso newly wrapped plain panes never had it), buttypeset -gremoves it, and the same reasoning is why the new resolver out-parameter usestypeset -gtoo.Every new test fails without its fix
Verified by reverting each fix in place and re-running:
builtin unset ORCA_SHELL_FEATURESin the zsh channelmarkersgate → always select markershistorygate → only when already wrappedemulate -L zshin the epiloguehistoryguardspawnShellWithFallbackdropInheritedOrcaHistFileremoved from all five call sitesbuildSpawnEnv×2.zshrcepilogue call back to[[ -o login ]] || …emulate shlogin shell (1), on real zsh.zprofile/.zshrc/.zlogincommand not foundand the skipped-user-config assertionsisOrcaMintedHistFileanchor back to(?:^|/)REPLYtypeset -r REPLY+typeset -i REPLYpanes (2) on real zsh, plus the three namespace-rule cases and all three wrapper byte snapshots.zshenv/.zprofileemulate sh/emulate kshdegrade cases (3), on real zshdelete env.ORCA_HISTFILEincreatePtySubprocessORCA_HISTFILEcase (1)delete result.ORCA_HISTFILEin the relay'sbuildSpawnEnvORCA_HISTFILEcases (4)Suites
All run with
ORCA_SHELL_FEATURES,ORCA_HISTFILEandORCA_SHELL_READY_MARKERexplicitly unset, so no assertion can pass on a value inherited from the developer's own Orca pane.npx oxlintandnpx oxfmt --checkon every changed file — clean. Nomax-linesdisable 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 onorigin/mainin the same checkout, verified by detaching toorigin/mainand re-running them: the 8 collection failures areError: Cannot find package 'psl'(a dependency this checkout's sharednode_modulespredates, reached viasrc/main/browser/browser-cookie-import-policy.ts), and the 10 are xterm snapshot/emulator-fidelity assertions interminal-snapshot-osc8-roundtrip,terminal-snapshot-color-parityandheadless-emulator-fidelity.fuzz. None of those files is touched by this PR.src/main/zsh-scoped-histfile.live-shell.test.tsagainst real zsh 5.9 / macOS: 12/12, none skipped (7 pre-existing + 5 new: twoREPLYdeclarations,emulate shandemulate kshin.zshenv,emulate shin.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 withsrc/renderer/src/components/tab-bar/TabBarCreateEntry.tab-results.test.tsx(51,9): Property 'occupantAgent' is missing, a pre-existingorigin/mainbreakage since fixed onmainby 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 specsande2e / 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 fromverify'sneedsbecause it is red onmain. 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 32tests nodeshards.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:
.zshenvgains the feature channel + config-dir resolver + the epilogue. The channel is 4 lines; the resolver replaces the repeatedcase "${x%/}" in */shell-ready/zsh)pattern; the epilogue is the code that moved out of.zshrc/.zlogin..zshrcand.zloginshrink to "source the user's file, then call the epilogue.".zloginends with(( ${+functions[__orca_shell_epilogue]} )) && __orca_shell_epilogue;.zshrcwraps the same call inif [[ ! -o login || "$(emulate 2>/dev/null)" != zsh ]](a login shell normally has.zloginto load — unless sh/ksh emulation sent it to$HOME/.zlogin; follow-up Fix MaxListenersExceededWarning with singleton PTY dispatcher #6). The${+functions[…]}guard is braced becauseKSH_ARRAYSrejects 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/.zloginalso each carry the 7-line__orca_resolve_user_config_dirdefinition (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.zshenvmade a mixed-build wrapper dir fail loudly and skip the user's config.ORCA_SHELL_STARTUP_IDENTITYgate →__orca_has_feature identity, andORCA_SHELL_READY_MARKERgate → thereadyguard (zsh) /__orca_ready_marker(bash). Same emission, different channel.ORCA_HISTFILEbranch gainsbuiltin unset ORCA_HISTFILE. The consume-and-destroy step.fish init loses its
if test "$ORCA_SHELL_READY_MARKER" = 1wrapper. The command is only passed whenreadyis selected, so the gate was dead weight; this also removes the last reader of that variable.Relay
.zloginready-marker ordering. The pre-existingreadyMarkerOrderdrift field is deleted: local/daemon registered the widget before the finalZDOTDIRrestore, relay after. The widget registration does not readZDOTDIR, so the order was immaterial; unifying it removes a spec field whose only job was to preserve cosmetic drift. Same for thelegacyFormattingindent/comment drift, which became meaningless once the restores were re-indented into a function body.The resolver's out-parameter is
_orca_resolved_config_dir, declaredtypeset -g, instead ofREPLY. Pure rename plus the declaration; the resolver's logic is unchanged (follow-up Add card gap and quick-create in worktree dialog #10)..zshenvand.zprofilegain 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 gainstypeset -g(follow-up Add Orca logo and polish README header #13).No generated line changed for any reason outside those eight.
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):
main/etc/zshrcHISTFILE repairssh-pty-spawn-env.tsalways setsORCA_REMOTE_CLI_BIN_DIRremoteCliBridgeEnv === null), worktree history onZDOTDIRwith the allowlist already consumedfish_history, notHISTFILE)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/zshrcHISTFILE 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
markerstoken is gated on "was this pane wrapped before"), no readiness marker, no identity marker, and no overlay restores. They run.zshenv,.zprofile,.zshrc,.zloginfrom the user's real config dir in the normal order, with the same prompt hooks and the samezle-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:
HISTFILEnow reaches the pane's children with the worktree path in it, where before/etc/zshrchad 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, andHISTFILEis 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/.zprofilethat 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/.zprofileexists, against ≈8.5 ms/run unwrapped. The rest is a handful of[[ ]]tests and, in the guard, up to four-rstats 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/zshshape 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_FEATURESonly 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.zshenvwith the local/daemondiscover-user-zdotdirone. 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'sZDOTDIRis discovered from and deserves its own PR. Disclosed defect: the overlay body neverunset ZDOTDIRbefore sourcing the user's.zshenv, so for a wrapped relay pane whose user keeps their zsh config in a relocatedZDOTDIR,ORCA_USER_ZDOTDIRcollapses to$HOMEand that config is not loaded. This is present onorigin/maintoday 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 isunset ZDOTDIR+ re-resolve insidegetZshOverlayEnvBody, which changes remote startup for every already-wrapped relay pane and belongs in the reconciliation PR.emulate sh/emulate kshis now handled everywhere it can be, not scoped out. zsh does not "skip$ZDOTDIR/.zlogin" as an earlier revision of this note claimed — itssourcehome()ignoresZDOTDIRunder those emulations and reads the$HOMEfile 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.zshenvor.zprofile, no wrapper file after it is read at all andHISTFILEcannot be repaired from there, so the pane is handed back unwrapped instead (follow-up Add application screenshot to README #12) — the same shellmainproduced 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 onmainfor 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
ZDOTDIRunset 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/.zshrccall 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.zshenvand 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 ofsrc/main/shell-startup-features.ts, next to the code that owns it.Agent skill upstream boundary
Notes
ORCA_SHELL_READY_MARKER) is gone, and the new one is destroyed before user code runs.process.platform !== 'win32'; Windows PowerShell/cmd and the Git Bash and WSL launch paths are unchanged apart fromgetBashWrapperLaunchArgs()now returningnull(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.EACCES$HOME.ORCA_HISTFILEfrom the spawn env and does not care how the workspace was created.$(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).