Skip to content

fix(shell): content-address shell-ready wrapper trees so builds stop clobbering each other - #15285

Merged
nwparker merged 5 commits into
mainfrom
nwparker/slow-worktree-create-2
Aug 18, 2026
Merged

nwparker merged 5 commits into
mainfrom
nwparker/slow-worktree-create-2

Conversation

@nwparker

@nwparker nwparker commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 17 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​572 $\color{#cf222e}{\Huge{\mathbf{−}}}$​236 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​336
Prod 18 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​363 $\color{#cf222e}{\Huge{\mathbf{−}}}$​112 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​251

Symptom

New terminals show a live shell prompt but ignore input for ~15s before the agent (or setup script) launches. It looks like a hung pane; it is actually a startup command sitting in a queue. Restarting Orca does not clear it, and neither does downgrading.

Root cause

Startup commands are held until the shell emits the OSC 777 ready marker. If the marker never arrives, delivery falls back to SHELL_READY_TIMEOUT_MS (15s). Only stdin is gated, so the prompt renders normally at ~0.7s -- which is why this reads as "unresponsive terminal" rather than "slow launch".

The marker goes missing because every writer sharing a userData dir writes one fixed shell-ready/ tree: main's local PTY path, the daemon fork, and the daemons of other builds, which outlive the app that spawned them. Last writer wins. And the guard only re-checks that the files exist, never that they are this build's:

if (didEnsureShellReadyWrappers && shellReadyWrappersExist()) return

So a daemon whose spawn env no longer agrees with the wrapper on disk keeps launching shells it cannot read -- permanently, with no log line.

This is not confined to machines running dev builds. The five live daemons on the machine this was found on spanned app versions 1.4.181-1.4.185, all from the same installed /Applications/Orca.app across auto-updates. Wrapper content changed 15 times in the last 12 months. Any release that changes it, with an older daemon still alive, reproduces this — and the user cannot recover by restarting, because the daemon is not restarted with the app.

Measured: 15.17s from terminal create to the command running, against 1.10s once the tree matched. 15.17s is the 15,000ms timeout.

Fix

Name each wrapper tree after a hash of its own contents: <userData>/shell-wrappers/<hash>/shell-ready/. Different bytes are a different directory, so no writer can overwrite another's contract, and the existence check becomes correct rather than a bug — a tree that is present is a tree this build wrote.

Two deliberate constraints:

  • The hash sits ABOVE the shell-ready leaf. ZDOTDIR self-reference guards — in TS, and as */shell-ready/zsh globs baked into the wrapper scripts — match that exact suffix; losing it makes a wrapper source itself until zsh dies with "recursion limit exceeded". <hash>/shell-ready/zsh keeps every one of them intact.
  • A separate shell-wrappers/ base dir. Older daemons still write shell-ready/ unconditionally, so this keeps these trees out of their reach — including during the upgrade that ships this.

Writing itself is unchanged: it stays in the existing shell-wrapper-file-writer.ts. This only decides placement.

Nothing collects old trees, deliberately. A tree is ~48KB and a new one appears only when the wrapper templates change, so an install accrues a couple of MB a year against a userData dir that runs to tens of GB. An earlier revision had a 30-day pruner; it reclaimed ~0.008% of userData and cost the only rm -rf in the change (on the terminal-spawn path), a utimes per launch, a liveness stamp, a symlink guard, a filename pattern, and a flag in both ensure paths — and it produced most of the defects review found. It is gone. If reclaiming trees is ever worth it, it belongs wherever userData is already garbage-collected.

Two things ride along because they are the same bug:

  • WSL. The in-guest login script rebuilds the root from ORCA_USER_DATA_PATH, which cannot carry a hash. Without a fix, every WSL pane falls through to an unwrapped exec "$shell" -l and silently loses the ready marker, OSC 133, the identity marker, the OMP wrapper, and the Codex preflight. The host now publishes the resolved root as ORCA_SHELL_READY_ROOT over WSLENV /p; the legacy branch stays as a fallback for an older host.
  • The barrier now reports readiness failures to the daemon's file log. It failed completely silently, which is what made this expensive to diagnose. Note the daemon runs detached with stdio ignore, so a console.warn there reaches nobody — an earlier revision of this PR made exactly that mistake and claimed the fix; the event is now threaded to the NDJSON logger, with the shell recorded as a basename.

Verification

  • 30,036 tests pass. The single failure is a pre-existing flake in worktree-base-directory-poller.test.ts (watcher-based, passes alone, file untouched by this PR).
  • Generated wrapper content is byte-identical to main — same sha256 on every file with generators bundled from separate refs; snapshots untouched. This moves trees without altering a line of shell script.
  • Verified by execution, not review: the suffix guards match under real zsh and bash (including with every ZDOTDIR variable forced at the wrapper dir, so only the in-script globs stand between zsh and recursion); the marker fires from the hashed path (zsh +0.12s, bash +0.82s); two contracts coexist in either write order; a warm tree is never rewritten; and running main's guest script against a hashed tree reproduces the WSL failure this fixes.

Four rounds of adversarial review against the readiness checklist informed the shape above; the largest single outcome was deleting the pruner.

Follow-ups (not in this PR)

  • SessionShellReadyBarrier's fallback probe is inert for this failure class: shell-prompt-readiness-probe.ts bails without a shell pid, and that pid only arrives via the identity marker the same mismatch suppresses, so both signals die together. Fixing it means sourcing the pid from the pty foreground process group.
  • The wrapper path has three independent consumers (local, daemon, in-guest WSL) plus suffix-matching guards embedded in shell-script text. That coupling is what made the WSL break possible and predates this change; untangling it is its own piece of work.
  • The relay keys its wrapper tree at a single fixed ~/.orca-relay/shell-ready with non-atomic writes. It validates content, so it lacks the existence-only bug — but after this ships, local terminals are protected from clobbering and relay ones are not.

@coderabbitai

coderabbitai Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

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

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 24c1a03f-dfbf-46d3-8c7e-848c6f94d915

📥 Commits

Reviewing files that changed from the base of the PR and between b0aa4d8 and 7a1d155.

📒 Files selected for processing (1)
  • src/main/providers/local-pty-shell-ready-wrapper-generation.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/providers/local-pty-shell-ready-wrapper-generation.test.ts

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


📝 Walkthrough

Walkthrough

Shell-ready wrapper generation now uses content-addressed roots under dedicated storage directories. Shared utilities resolve roots, verify generated files, write files atomically, and prune stale roots. Local and daemon builders generate Zsh and Bash wrapper files through these utilities. WSL setup publishes the resolved root through ORCA_SHELL_READY_ROOT. Tests now resolve wrapper paths dynamically. Session timeout handling logs shell and marker details before blind startup-command delivery.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.81% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description explains the symptom, root cause, fix, and verification, but omits the required issue link, visual proof or N/A, and several template sections. Add a linked issue, complete the required template sections, mark the visual proof requirement as N/A with a reason, and complete the testing and checklist items.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the main change: content-addressing shell-ready wrapper trees to prevent build conflicts.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (1)
src/main/providers/local-pty-shell-ready-wrapper-generation.ts (1)

24-26: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Construct the zsh directory with join.

Line 25 uses a literal /zsh path while buildLocalShellReadyWrapperFiles uses join(root, 'zsh'). Use the same path utility here.

Proposed fix
+import { join } from 'node:path'
+
 export function getZshShellReadyRcfileContent(): string {
-  return buildZshStartupWrapperFiles(getLocalZshWrapperSpec(`${getShellReadyWrapperRoot()}/zsh`))
+  return buildZshStartupWrapperFiles(getLocalZshWrapperSpec(join(getShellReadyWrapperRoot(), 'zsh')))
     .zshrc
 }

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8d705020-f514-4066-bd6a-7cf9fa8fdef7

📥 Commits

Reviewing files that changed from the base of the PR and between 96d88dd and c588470.

📒 Files selected for processing (20)
  • src/main/daemon/daemon-shell-ready-wrapper-fileset.ts
  • src/main/daemon/session-shell-ready-barrier.ts
  • src/main/daemon/shell-ready.test.ts
  • src/main/daemon/shell-ready.ts
  • src/main/ipc/pty-hidden-at-spawn-mark.test.ts
  • src/main/ipc/pty-listener-teardown-and-orphans.test.ts
  • src/main/ipc/pty-login-shell-startup-commands.test.ts
  • src/main/ipc/pty-wsl-cwd-validation.test.ts
  • src/main/providers/local-pty-shell-ready-bash-rcfile.ts
  • src/main/providers/local-pty-shell-ready-marker.ts
  • src/main/providers/local-pty-shell-ready-wrapper-fileset.ts
  • src/main/providers/local-pty-shell-ready-wrapper-generation.test.ts
  • src/main/providers/local-pty-shell-ready-wrapper-generation.ts
  • src/main/providers/local-pty-shell-ready-wrapper-root.ts
  • src/main/providers/local-pty-shell-ready-zsh-zdotdir-discovery.test.ts
  • src/main/providers/local-pty-shell-ready-zsh-zdotdir-normalization.test.ts
  • src/main/providers/windows-shell-args.test.ts
  • src/main/shell-ready-wrapper-store.test.ts
  • src/main/shell-ready-wrapper-store.ts
  • src/main/shell-wrapper-generated-file-snapshot.test.ts

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

Comment on lines +191 to +200
// Why log: this path costs every startup command the full timeout, and it
// used to fail silently -- a wrapper that never emits the marker looked
// identical to a slow shell. Name the wrapper so the next report can be
// diagnosed from the log alone.
console.warn(
`[Session] ${this.deps.sessionId}: shell-ready marker never arrived within ` +
`${this.deps.shellReadyTimeoutMs ?? SHELL_READY_TIMEOUT_MS}ms for shell ` +
`${this.deps.subprocess.shellPath ?? 'unknown'}; delivering the startup command blind. ` +
"The launched shell is not emitting Orca's ready marker."
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- target context ---'
sed -n '150,215p' src/main/daemon/session-shell-ready-barrier.ts

printf '%s\n' '--- logging policy and redaction references ---'
rg -n -i --glob '!node_modules' \
  'redact|sanitize|sensitive|privacy|logging policy|sessionId|shellPath|console\.(warn|error|log)' \
  src docs README.md .github 2>/dev/null | head -n 300

printf '%s\n' '--- session and shell-path definitions/usages ---'
rg -n --glob '*.{ts,tsx,js,jsx}' \
  'sessionId|shellPath|SHELL_READY_TIMEOUT_MS|SessionShellReadyBarrier' \
  src | head -n 300

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- target file outline and dependency shape ---'
ast-grep outline src/main/daemon/session-shell-ready-barrier.ts
rg -n -C 4 --glob '*.{ts,tsx,js,jsx}' \
  'new SessionShellReadyBarrier|session-shell-ready-barrier|interface .*Deps|shellPath:' \
  src/main/daemon src/main/providers | head -n 220

printf '%s\n' '--- session-id construction and path-bearing formats ---'
rg -n -C 3 --glob '*.{ts,tsx,js,jsx}' \
  '::.*(cwd|worktree|path)|sessionId\s*[:=].*(join|cwd|worktree|path)|parsePtySessionId|build.*Session.*Id|get.*Session.*Id' \
  src/main | head -n 240

printf '%s\n' '--- console/log capture, persistence, and telemetry sinks ---'
rg -n -C 3 --glob '*.{ts,tsx,js,jsx,json}' \
  'console\.(log|info|warn|error)|intercept.*console|console.*(capture|persist|upload)|write.*log|log.*(file|upload)|telemetry.*(log|console)|Sentry|electron-log|winston|pino' \
  src package.json | head -n 300

Repository: stablyai/orca

Length of output: 50369


🌐 Web query:

https://www.onorca.dev/docs/telemetry Orca telemetry logs console warnings session identifiers shell paths privacy

💡 Result:

Orca's telemetry system is designed to be anonymous and privacy-focused, operating on an opt-out basis [1]. The following details summarize its handling of telemetry, logs, and sensitive identifiers: Telemetry and Privacy Orca collects anonymous product-usage telemetry to help improve the application [1][2]. Key privacy safeguards include: - Anonymity: Events are keyed by a random identifier stored locally on your machine, rather than being linked to any account, email, IP address, or username [1]. - Exclusions: The application does not collect file contents, prompts, agent responses, terminal contents, repository names, branch names, URLs, file paths, or commit messages [1]. - Error Reporting: Raw error messages and stack frames are not transmitted; they remain in local diagnostic trace files and are only shared with the team if you explicitly provide a diagnostic bundle [1]. - Build Info: Telemetry includes basic build and platform metadata, such as the Orca version, OS (e.g., darwin, win32, linux), CPU architecture, and release channel [1]. Disabling Telemetry You can disable telemetry transmission using any of the following methods: - In-App Settings: Navigate to Settings → Privacy and toggle "Share anonymous usage data" to off [1]. - Environment Variables: Set either DO_NOT_TRACK=1 or ORCA_TELEMETRY_DISABLED=1 [1]. Any single method is sufficient to disable the service [1]. Terminal Sessions and Paths Orca’s terminal is based on xterm.js [3]. While the application handles session and shell information (such as the current working directory and shell path) for local functionality—like managing git worktrees and agent terminals—this specific sensitive data is explicitly excluded from the telemetry data that is transmitted to Orca [1]. System-level identifiers, such as the bundle identifier (com.stablyai.orca), are present in local environment variables for application identification but are not part of the telemetry collection process [1][3].

Citations:


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- daemon log lifecycle ---'
cat -n src/main/observability/logs-directory.ts
rg -n -C 5 --glob '*.{ts,tsx,js,jsx}' \
  'daemonLogFilePath|getDaemonLogFilePath|--log-file|daemon\.log|collectBundle|diagnostic bundle|diagnostic.*log' \
  src/main | head -n 260

printf '%s\n' '--- bundle filtering and redaction ---'
rg -n -C 5 --glob '*.{ts,tsx,js,jsx}' \
  'redact|sanitize|private path|file path|daemon.*log|trace.*redact|filter.*log|log.*filter|sensitive' \
  src/main/observability src/main | head -n 300

printf '%s\n' '--- PTY session identifier implementation ---'
cat -n src/main/daemon/pty-session-id.ts
sed -n '1,75p' src/main/daemon/session-shell-ready-barrier.ts

Repository: stablyai/orca

Length of output: 49021


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- daemon file logger ---'
fd -i 'daemon.*log|log.*daemon' src/main
rg -n -C 8 --glob '*.{ts,tsx,js,jsx}' \
  'log-file|DAEMON_LOG_MAX_FILES|appendFile|createWriteStream|process\.stdout|process\.stderr|console\.(warn|error)' \
  src/main/daemon src/main/observability | head -n 260

printf '%s\n' '--- bundle record transformation ---'
sed -n '1,180p' src/main/observability/bundle.ts
sed -n '180,280p' src/main/observability/bundle.ts

printf '%s\n' '--- daemon log privacy tests ---'
rg -n -C 5 --glob '*.{ts,tsx,js,jsx}' \
  'daemon.*(redact|privacy|path|session)|session.*(redact|privacy)|shell.*(redact|privacy)|private.*path' \
  src/main/observability src/main/daemon | head -n 220

Repository: stablyai/orca

Length of output: 48013


Redact session identifiers and shell paths in daemon warnings. The daemon log is persisted and included in diagnostic bundles. sessionId can contain an absolute worktree path, and shellPath can contain a user directory. The existing secret redactor does not remove these values. Log only a bounded session suffix and shell basename, or add explicit path and identifier redaction.

🧰 Tools
🪛 ast-grep (0.45.1)

[warning] 194-199: Avoid logging sensitive data
Context: console.warn(
[Session] ${this.deps.sessionId}: shell-ready marker never arrived within +
${this.deps.shellReadyTimeoutMs ?? SHELL_READY_TIMEOUT_MS}ms for shell +
${this.deps.subprocess.shellPath ?? 'unknown'}; delivering the startup command blind. +
"The launched shell is not emitting Orca's ready marker."
)
Note: [CWE-532] Insertion of Sensitive Information into Log File.

(log-sensitive-data-typescript)

Source: Linters/SAST tools

Comment thread src/main/daemon/shell-ready.ts Resolved
Comment thread src/main/shell-ready-wrapper-store.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

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

⚠️ Outside diff range comments (2)
src/main/shell-ready-wrapper-store.ts (2)

135-158: 🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

Make the base-directory traversal race-safe.

Line 137 checks baseDir before Lines 140 and 158 use it. A process that can modify the wrapper base can replace it with a symlink after lstatSync returns. readdirSync and rmSync then traverse the replacement target. A stale directory with a matching 16-character name can be deleted outside the wrapper store.

Keep deletion anchored to a non-following directory handle, or otherwise prevent replacement of baseDir for the full enumeration and deletion operation. A second path check does not close this race.


154-158: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Serialize pruning with wrapper liveness updates.

A pruner can read an aged mtimeMs at Line 155 while another process has already passed its cached wrapper-existence check. If the pruner removes the root before that process calls markShellReadyWrapperRootInUse, the stamp failure is swallowed and the process returns without regenerating wrappers. The shell then starts with a deleted wrapper tree.

Coordinate pruning with the existence-check and liveness-stamp path across processes. Retry wrapper generation when liveness marking cannot confirm the root still exists. The current test stamps before pruning, but it does not cover this interleaving. The cached paths in src/main/daemon/shell-ready.ts:101-111 and src/main/providers/local-pty-shell-ready-wrapper-generation.ts:34-43 are affected.

🧹 Nitpick comments (1)
src/main/shell-ready-wrapper-store.ts (1)

41-54: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Shorten the new implementation and test comments. The comments contain useful rationale, but they are multi-line explanations of control flow. Keep only the non-obvious invariant in one concise line.

  • src/main/shell-ready-wrapper-store.ts#L41-L54: reduce the suffix rationale to one line.
  • src/main/shell-ready-wrapper-store.ts#L73-L76: reduce the cache rationale to one line.
  • src/main/shell-ready-wrapper-store.ts#L105-L113: reduce the liveness rationale to one line.
  • src/main/shell-ready-wrapper-store.ts#L165-L177: retain the security invariant without the detailed flow description.
  • src/main/shell-ready-wrapper-store.ts#L190-L202: retain the atomic-write and Windows-retry rationale without implementation narration.
  • src/main/shell-ready-wrapper-store.test.ts#L77-L84: state the stranded-temp test condition briefly.
  • src/main/shell-ready-wrapper-store.test.ts#L140-L168: state the legacy-tree and foreign-directory invariants briefly.

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

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 0e82f9fc-cdc9-415b-b981-6ee47d97667c

📥 Commits

Reviewing files that changed from the base of the PR and between 7c678d0 and 729d16f.

📒 Files selected for processing (9)
  • src/main/daemon/shell-ready.ts
  • src/main/providers/__tests__/shell-ready-framework/shell-script-test.ts
  • src/main/providers/local-pty-shell-ready-wrapper-generation.ts
  • src/main/pty/wsl-orca-env.test.ts
  • src/main/pty/wsl-orca-env.ts
  • src/main/shell-ready-wrapper-store.test.ts
  • src/main/shell-ready-wrapper-store.ts
  • src/shared/wsl-login-shell-command.test.ts
  • src/shared/wsl-login-shell-command.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/daemon/shell-ready.ts
  • src/main/providers/local-pty-shell-ready-wrapper-generation.ts

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/main/providers/local-pty-shell-ready-wrapper-generation.test.ts (1)

22-25: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Shorten the test rationale comments. Both comments explain valid non-obvious behavior, but they are longer than the TypeScript comment guideline permits.

  • src/main/providers/local-pty-shell-ready-wrapper-generation.test.ts#L22-L25: Reduce this rationale to one concise line.
  • src/main/providers/local-pty-shell-ready-wrapper-generation.test.ts#L102-L103: Reduce this rationale to one concise line.

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

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8df140cc-1a16-476c-bbc6-77f4da4d1834

📥 Commits

Reviewing files that changed from the base of the PR and between 729d16f and b0aa4d8.

📒 Files selected for processing (5)
  • src/main/daemon/shell-ready.ts
  • src/main/providers/local-pty-shell-ready-wrapper-generation.test.ts
  • src/main/providers/local-pty-shell-ready-wrapper-generation.ts
  • src/main/providers/local-pty-shell-ready-wrapper-root.ts
  • src/main/shell-ready-wrapper-store.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/main/providers/local-pty-shell-ready-wrapper-root.ts
  • src/main/daemon/shell-ready.ts
  • src/main/providers/local-pty-shell-ready-wrapper-generation.ts
  • src/main/shell-ready-wrapper-store.ts

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

@nwparker
nwparker force-pushed the nwparker/slow-worktree-create-2 branch from 6060f8b to d84fbb3 Compare August 18, 2026 19:21
…ring each other

Every writer that shares a userData dir -- main's local PTY path, the daemon
fork, and the daemons of other builds that outlive the app that spawned them --
writes one fixed `shell-ready/` tree. Last writer wins, and the guard only
re-checks that the files are present, never that they are this build's. A daemon
whose spawn env no longer agrees with the wrapper on disk therefore keeps
launching shells it cannot read: the ready marker never fires and every startup
command waits out the full 15s SHELL_READY_TIMEOUT_MS, silently.

Measured: 15.17s from `terminal create` to the command running, against 1.10s
once the tree matched. Restarting the app does not clear it, because the daemon
outlives the app -- the five live daemons on the machine this was found on
spanned app versions 1.4.181 to 1.4.185, all from the same installed app across
auto-updates. Wrapper content changed fifteen times in the last twelve months,
so this recurs on ordinary installs, not just machines running dev builds.

Name each tree after a hash of its own contents, at
`<userData>/shell-wrappers/<hash>/shell-ready/`. Different bytes are a different
directory, so no writer can overwrite another's contract and "present" means
"written by this build" again. Writing itself stays in
shell-wrapper-file-writer.ts; this only decides placement.

The hash sits ABOVE the `shell-ready` leaf on purpose: ZDOTDIR self-reference
guards -- in TS and as `*/shell-ready/zsh` globs baked into the wrapper scripts
-- match that exact suffix, and losing it makes a wrapper source itself until
zsh hits its recursion limit. A separate base dir keeps these trees out of reach
of older daemons, which still write `shell-ready/` unconditionally.

Nothing collects old trees. A tree is ~48KB and a new one appears only when the
wrapper templates change, so an install accrues a couple of megabytes a year
against a userData directory that runs to tens of gigabytes. That is not worth
putting an `rm -rf` on the terminal-spawn path; if it ever is, it belongs
wherever userData is already garbage-collected.

Also:
- Publish the resolved root to WSL as ORCA_SHELL_READY_ROOT over WSLENV `/p`.
  The in-guest login script rebuilds the root from ORCA_USER_DATA_PATH, which
  cannot carry the hash, so without this every WSL pane launches unwrapped and
  silently loses the ready marker, OSC 133, and the launch preflight. The legacy
  branch stays as a fallback for an older host.
- Log when the readiness barrier times out. It failed completely silently, which
  is what made this expensive to diagnose.

Generated wrapper content is byte-identical; snapshots are unchanged. Tests that
hardcoded the old layout now resolve the root instead.
@nwparker
nwparker force-pushed the nwparker/slow-worktree-create-2 branch from f584053 to df5b695 Compare August 18, 2026 20:26
…the void

Review caught this series claiming a diagnostic it did not deliver. The barrier
used console.warn, but the daemon is spawned detached with stdio 'ignore' and a
stderr pipe that is released once startup settles, so console output from it
goes nowhere. Confirmed against a live 2.8MB daemon.log: it holds only
structured NDJSON from the file logger, and not one line of console output.
Nothing patches console in the daemon.

Thread the daemon's file logger down to the barrier and emit structured events
instead. The pre-existing wrapper-replaced warning next to it was equally lost,
so it goes through the same sink.

Log the shell basename rather than its path -- the path can carry a home dir and
the basename is all a diagnosis needs. The session id stays, because the daemon
already logs it on every session lifecycle event and it is what makes these
correlatable.

Also from the same review: two comments still named the module this change
renamed, and the placeholder-root hashing caveat now spells out the condition it
depends on -- that the root is the only path-dependent input to a wrapper.

Not taken: switching the local file set to path.join. Those paths are baked into
.zshenv as a shell literal and passed to bash as --rcfile, and the launch config
builds the matching values by `/` concatenation. path.join emits backslashes on
Windows, where a shell literal reads them as escapes, and would desync the
written path from the launched one. Documented in place so it is not re-flagged.
…on log sink

The barrier-level test proves the callback fires, which is exactly what the
console.warn version would also have passed. The failure that shipped was a
delivery failure: the diagnostic existed in code and reached nobody, because the
daemon runs detached with stdio 'ignore'.

Drive a real TerminalHost instead, so the event has to survive every hop out to
the sink. Verified it fails when any one hop stops forwarding.

Also from readiness review:
- Never let a throwing diagnostic sink strand the barrier. The report runs before
  the transition that releases held PTY bytes and flushes queued stdin, and the
  ready timer is already cleared by then, so a throw would leave the session
  stuck in `pending` with nothing left to wake it. Diagnostics must not be able
  to break a terminal.
- Resolve the wrapper dir in the shell-ready test framework instead of rebuilding
  the old layout. The placeholder had silently stopped substituting, so the next
  inline snapshot taken through it would have baked in a machine-specific,
  hash-bearing path.
- Drop a stale comment justifying a truthiness check by a pruner this series
  removed, and stop exporting the local base-dir helper, matching the daemon twin.
@nwparker
nwparker force-pushed the nwparker/slow-worktree-create-2 branch from b8233a2 to 631decd Compare August 18, 2026 22:35
Security review noted that the presence check is size-only, so a complete
wrapper tree pre-planted under the unseeded-env fallback would be trusted rather
than overwritten -- on Linux that fallback is a shared world-writable /tmp.

Not fixing it in code. Production never reaches the fallback: ORCA_USER_DATA_PATH
is seeded before anything spawns and the daemon fork inherits it. An ownership
check on the spawn path would be exactly the kind of machinery this series just
removed with the pruner -- syscalls and platform branching to defend a path that
cannot be reached. Record the boundary instead, so the next reader knows it was
considered rather than missed.
…est.ts

CI's static-analysis gate failed: shell-ready.test.ts counted 801 non-blank,
non-comment lines against a 800-line cap for tests. The file was already at the
cap on main; resolving the wrapper root instead of hardcoding it made a few
call sites longer, and the formatter wrapped them.

The repo forbids disabling or bumping max-lines, so split rather than silence.
The bash-wrapper tests -- OSC 133 lifecycle, PROMPT_COMMAND composition, the
live-bash rcfile runs -- are a self-contained group, and the live-shell harness
they share with the launch-config suite moves to a fixture module rather than
being duplicated, so the two copies cannot drift.

Same 29 tests before and after.
@nwparker
nwparker merged commit 1b5cc00 into main Aug 18, 2026
52 checks passed
nwparker added a commit that referenced this pull request Aug 19, 2026
…r trees

#15285 landed content-addressed wrapper roots and a per-transport fileset module
while this branch was in flight. The fileset modules are now the single place the
tree is described, so 'only .zshenv' is stated once per transport and the
required-paths check follows from it rather than repeating the list.
nwparker added a commit that referenced this pull request Aug 19, 2026
…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.
nwparker added a commit that referenced this pull request Aug 20, 2026
… hook (STA-4786) (#15391)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Every writer sharing a userData dir -- main's local PTY path, the daemon fork,
and the daemons of other builds that outlive the app that spawned them -- wrote
one fixed `shell-ready/` tree. Last writer won, and the guard only re-checked
that the files were present, never that they were this build's. A daemon whose
spawn env no longer agreed with the wrapper on disk kept launching shells it
could not read: the ready marker never fired and every startup command waited
out the full 15s timeout, silently, with restarting the app powerless to fix it
because the daemon outlives the app.

Measured 15.17s vs 1.10s once the tree matched. The five live daemons on the
machine this was found on spanned app versions 1.4.181-1.4.185, all from the
same installed app across auto-updates, so this reaches ordinary installs.

Name each tree after a hash of its contents, at
`<userData>/shell-wrappers/<hash>/shell-ready/`. Different bytes are a different
directory, so "present" means "written by this build" again. The hash sits above
the `shell-ready` leaf because ZDOTDIR self-reference guards match that exact
suffix. Nothing collects old trees: ~48KB each, a couple of MB a year against a
userData dir in the tens of GB, not worth an `rm -rf` on the spawn path.

Also publishes the resolved root to WSL over WSLENV `/p`, since the in-guest
script cannot derive a hash, and reports readiness failures to the daemon's
NDJSON log rather than a console the detached daemon discards.

Generated wrapper content is byte-identical; snapshots unchanged.
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 21, 2026
… hook (STA-4786) (stablyai#15391)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Every writer sharing a userData dir -- main's local PTY path, the daemon fork,
and the daemons of other builds that outlive the app that spawned them -- wrote
one fixed `shell-ready/` tree. Last writer won, and the guard only re-checked
that the files were present, never that they were this build's. A daemon whose
spawn env no longer agreed with the wrapper on disk kept launching shells it
could not read: the ready marker never fired and every startup command waited
out the full 15s timeout, silently, with restarting the app powerless to fix it
because the daemon outlives the app.

Measured 15.17s vs 1.10s once the tree matched. The five live daemons on the
machine this was found on spanned app versions 1.4.181-1.4.185, all from the
same installed app across auto-updates, so this reaches ordinary installs.

Name each tree after a hash of its contents, at
`<userData>/shell-wrappers/<hash>/shell-ready/`. Different bytes are a different
directory, so "present" means "written by this build" again. The hash sits above
the `shell-ready` leaf because ZDOTDIR self-reference guards match that exact
suffix. Nothing collects old trees: ~48KB each, a couple of MB a year against a
userData dir in the tens of GB, not worth an `rm -rf` on the spawn path.

Also publishes the resolved root to WSL over WSLENV `/p`, since the in-guest
script cannot derive a hash, and reports readiness failures to the daemon's
NDJSON log rather than a console the detached daemon discards.

Generated wrapper content is byte-identical; snapshots unchanged.
dallascrilley pushed a commit to dallascrilley/orca that referenced this pull request Aug 27, 2026
… hook (STA-4786) (stablyai#15391)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Every writer sharing a userData dir -- main's local PTY path, the daemon fork,
and the daemons of other builds that outlive the app that spawned them -- wrote
one fixed `shell-ready/` tree. Last writer won, and the guard only re-checked
that the files were present, never that they were this build's. A daemon whose
spawn env no longer agreed with the wrapper on disk kept launching shells it
could not read: the ready marker never fired and every startup command waited
out the full 15s timeout, silently, with restarting the app powerless to fix it
because the daemon outlives the app.

Measured 15.17s vs 1.10s once the tree matched. The five live daemons on the
machine this was found on spanned app versions 1.4.181-1.4.185, all from the
same installed app across auto-updates, so this reaches ordinary installs.

Name each tree after a hash of its contents, at
`<userData>/shell-wrappers/<hash>/shell-ready/`. Different bytes are a different
directory, so "present" means "written by this build" again. The hash sits above
the `shell-ready` leaf because ZDOTDIR self-reference guards match that exact
suffix. Nothing collects old trees: ~48KB each, a couple of MB a year against a
userData dir in the tens of GB, not worth an `rm -rf` on the spawn path.

Also publishes the resolved root to WSL over WSLENV `/p`, since the in-guest
script cannot derive a hash, and reports readiness failures to the daemon's
NDJSON log rather than a console the detached daemon discards.

Generated wrapper content is byte-identical; snapshots unchanged.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
… hook (STA-4786) (stablyai#15391)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant