Skip to content

fix(worktree): detect remote home dirs from path shape, not client homedir - #18341

Closed
fettpl wants to merge 3 commits into
stablyai:mainfrom
fettpl:fix/remote-worktree-home-delete-guard
Closed

fettpl wants to merge 3 commits into
stablyai:mainfrom
fettpl:fix/remote-worktree-home-delete-guard

Conversation

@fettpl

@fettpl fettpl commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

ELI5

When Orca cleans up leftover worktrees over SSH, it used the desktop's home folder to decide whether a path is too dangerous to delete. That is the wrong machine. A Windows remote home like C:\Users\bob did not look like a home from a Mac/Linux client, so the extra guard was weaker than local. This change recognizes home directories from the shape of the path (/home/alice, /Users/alice, C:\Users\bob) and only uses os.homedir() when the path syntax matches the client OS.

What Changed

  • isDangerousWorktreeRemovalPath no longer calls os.homedir() when worktree/repo path ops do not match process.platform.
  • Added Windows user-profile detection from path syntax: {root}Users and {root}Users\<name> via pathOps.parse().root (no hardcoded C:).
  • POSIX /home/<user> and /Users/<user> detection is unchanged.
  • Linked worktrees under a home (/home/alice/wt/foo, C:\Users\bob\wt\foo) stay deletable — containsPath is still "worktree contains home", not the reverse.

Why

SSH orphan cleanup (runtime-unregistered-worktree-removal.ts) passes remote paths into the client-side guard. Client os.homedir() plus POSIX-only regexes cannot protect a Windows SSH profile from a POSIX desktop, and can also refuse a safe POSIX remote delete when the client home string coincidentally interacts with the remote path. Path-shape detection is the intended fix; no new RPC for the remote user's home.

Linked Issue

Fixes #18275

Visual Proof

N/A — no visual or interaction change. This is a path-safety guard used during unregistered/orphan worktree directory removal.

Testing

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

Verification (plan 008):

  • pnpm test src/main/worktree-removal-safety.test.ts — 33 passed (table cases + stubbed os.homedir() to /Users/ci on darwin still treats C:\Users\bob as dangerous)
  • pnpm tc:node — exit 0
  • pnpm run check:code-quality:changed — exit 0

Platforms actually exercised: macOS unit tests with POSIX and win32 path fixtures (no live SSH). Windows profile cases run under process.platform === 'darwin' via withProcessPlatform.

Review

  • Cross-platform: uses existing getPathOps / path.posix / path.win32; Windows profiles use pathOps.parse().root so D:\Users\bob is covered, not only C:.
  • SSH/remote: this is the SSH case. Guard now ignores client homedir when the path is the other OS's syntax. No wire/RPC change (docs/reference/remote-wire-compatibility.md); no execution-host substitution (docs/reference/ssh-execution-boundary.md).
  • Security: recursive delete of an Orca-tagged leftover on a remote Windows home is now blocked by path shape. Children of home remain deletable. Did not invert containsPath.
  • Performance: extra string/path ops on the delete-safety path only; no extra I/O or RPC.
  • GitLab: N/A (no provider-specific git/review behavior).

Agent skill upstream boundary

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

Notes

Ensure no issues in: Security, Cross-platoform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance

Checklist

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

Local: plan verification commands (pnpm test src/main/worktree-removal-safety.test.ts, pnpm tc:node, pnpm run check:code-quality:changed). Full pnpm lint / pnpm build left to CI per plan.

@coderabbitai

coderabbitai Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 69342523-c78d-4aeb-910e-83dc39bf543f

📥 Commits

Reviewing files that changed from the base of the PR and between 992b82d and 675c910.

📒 Files selected for processing (17)
  • src/main/ipc/ssh-active-relay-sessions.test.ts
  • src/main/ipc/ssh-active-relay-sessions.ts
  • src/main/ipc/worktrees/removal/execute-worktree-removal.ts
  • src/main/ipc/worktrees/removal/remove-registered-local-worktree.ts
  • src/main/ipc/worktrees/removal/remove-unregistered-worktree-host-home.test.ts
  • src/main/ipc/worktrees/removal/remove-unregistered-worktree.ts
  • src/main/runtime/orca-runtime-remove-managed-worktree.ts
  • src/main/runtime/runtime-registered-local-worktree-removal.ts
  • src/main/runtime/runtime-unregistered-worktree-removal-host-home.test.ts
  • src/main/runtime/runtime-unregistered-worktree-removal.ts
  • src/main/ssh/ssh-relay-session.ts
  • src/main/worktree-removal-execution-host-route.test.ts
  • src/main/worktree-removal-execution-host-route.ts
  • src/main/worktree-removal-home-guard.test.ts
  • src/main/worktree-removal-home-guard.ts
  • src/main/worktree-removal-safety.test.ts
  • src/main/worktree-removal-safety.ts

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


📝 Walkthrough

Walkthrough

Removal safety now uses an explicit client or execution-host home authority. SSH routes resolve the host home from the active relay session. Local and remote removal flows pass this authority to registered-worktree, orphan, and leftover cleanup checks. The guard detects POSIX, Windows, and WSL home paths without cross-syntax client-home comparisons. Tests cover host-home protection and orphan removal.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to 675c9

No verified merge-blocking issue remains in the supplied change set.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 31.58% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 38 functions across 17 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the primary change: detecting remote home directories from path shape instead of the client home directory.
Description check ✅ Passed The description is complete and follows the repository template. It explains the change, rationale, linked issue, testing, cross-platform and SSH impact, and checklist status. The AI Disclosure headin…
Linked Issues check ✅ Passed The changes satisfy the coding requirements in [#18275]. worktree-removal-home-guard.ts selects path operations from path syntax, avoids client homedir() for foreign syntax, detects POSIX, Windows…
Out of Scope Changes check ✅ Passed The changed files remain within [#18275]. The home resolver, SSH session access, IPC wiring, runtime wiring, and related tests directly implement or verify execution-host home protection. No unrelated…
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • 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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: d04d79ee-6380-4afd-a895-d0242ffab5d9

📥 Commits

Reviewing files that changed from the base of the PR and between 720c329 and bc6b8d9.

📒 Files selected for processing (2)
  • src/main/worktree-removal-safety.test.ts
  • src/main/worktree-removal-safety.ts

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

@pullfrog pullfrog 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.

ℹ️ No critical issues — one minor suggestion inline.

Reviewed changes

  • Home-dir guard gated on path syntax — isDangerousWorktreeRemovalPath now consults os.homedir() only when the path syntax matches process.platform ((process.platform === 'win32') === (pathOps === win32)), so a POSIX client no longer applies its own homedir to a Windows remote path and vice versa.
  • Windows user-profile shape detection — new isLikelyWindowsUserProfileDirectory flags {root}Users and {root}Users\<name> using pathOps.parse().root, leaving children of a profile (e.g. C:\Users\bob\wt\foo) deletable. POSIX /home/<user> and /Users/<user> detection is unchanged.
  • Tests — a new isDangerousWorktreeRemovalPath describe block with table cases plus a withProcessPlatform('darwin') + os.homedir spy regression test that would fail under the old homedir behavior.

The fix is sound: the XNOR gating drops os.homedir() only in the two cross-syntax cases where it was previously meaningless, so no protection is lost and remote home directories (Windows or POSIX) gain coverage via path shape. The containsPath direction is preserved, keeping linked worktrees under a home deletable, and the new tests genuinely pin the behavior rather than passing trivially.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

Since the prior review (bc6b8d9), the author added one test commit (992b82d) that addresses the raised nit and strengthens the regression test:

  • Pinned non-C: drive profiles — added D:\Users\bob (dangerous) and D:\Users\bob\wt\foo (safe) table cases, closing the coverage gap the implementation's parse().root behavior implied.
  • Made the homedir-unused assertion real — replaced the os.homedir spy with a node:os module mock (via vi.hoisted), so the regression test now asserts homedir is never called on a cross-syntax path rather than relying on a spy that could not wrap the named export.

The mock is scoped to this file, delegates to the real homedir in its implementation, and mirrors the node:os mock pattern already used in the bitbucket and codex-accounts suites. The D: cases are correctly handled by isLikelyWindowsUserProfileDirectory (parse().root → D:\), and the test suite passes (35 tests, run locally).

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker

Copy link
Copy Markdown
Contributor

Reviewed this against the issue and against a repro on this client. The core of it is right and it is the low-risk shape of this fix: gating the homedir() read on (process.platform === 'win32') === (pathOps === win32) is exactly the correct condition, and isLikelyWindowsUserProfileDirectory deriving the drive from parse().root handles non-C: volumes and UNC roots. I reproduced the reported failure on origin/main (macOS client, isDangerousWorktreeRemovalPath('C:\Users\bob', 'C:\src\repo') → false) and this branch fixes it.

I had built an overlapping fix at #19865 before triage pointed me here. It covers three cases this one leaves open, which I'd rather hand over than duplicate:

1. A remote host whose home is not in a standard place gets no protection at all.

After this change the client home is (correctly) not consulted for a remote path, and path shape only recognises /home/<x>, /root, /Users/<x>, C:\Users\<x>. A host with $HOME=/srv/homes/alice — Synology, NixOS, LDAP setups, anything with a non-FHS home — matches none of those, so the guard passes and the recursive delete proceeds. The client home used to accidentally cover some of these; now nothing does.

The host already tells us its home: ssh-relay-deploy.ts:245 resolves remoteHome by running readRemoteHomeCommand on the host during relay deploy, and SshRelaySession holds it. Threading that into the guard as an explicit "whose home is this" argument closes the case without a new probe.

2. WSL UNC paths are unprotected. \\wsl.localhost\Ubuntu\home\alice takes win32 path ops, so isLikelyPosixHomeDirectory returns false, and the Windows rule looks for \\wsl.localhost\Ubuntu\Users — which never matches a Linux home. These alias a Linux filesystem, so the POSIX shapes should apply to the linuxPath from parseWslUncPath.

3. Nothing pins the call site. The guard is right, but runtime-unregistered-worktree-removal.ts could stop passing the host's answer and no test would notice. When I mutated that call site to use the client home, my whole suite stayed green until I added a test driving removeRuntimeUnregisteredWorktree directly and asserting fsProvider.deletePath is never called for the host's home.

Also worth adding regardless: /Users on its own is not in isLikelyPosixHomeDirectory (only /Users/<name>), so deleting the directory containing every macOS home is currently allowed. One line.

Happy either way on sequencing — this PR is small and correct and could land now with the host-reported home layered on after, or the pieces above could come across into it. I don't want to duplicate the work.

@nwparker

Copy link
Copy Markdown
Contributor

One framing point on my first gap, because it changes what a reviewer should do with this PR rather than just adding a to-do.

Removing the homedir() read for foreign-syntax paths is correct, but the client home was incidentally protecting remote hosts whose home isn't in one of the four recognised shapes. $HOME=/srv/homes/alice — Synology, NixOS, LDAP homes — matches none of /home/<x>, /root, /Users/<x>, C:\Users\<x>, so after this change nothing stands in front of the recursive delete for that host, where before the client home sometimes did by accident.

So this is a fix that narrows coverage in one dimension while widening it in another — a hole the reported bug didn't have. That's not an argument against merging it; the Windows case it fixes is real and the shape of the fix is right. It's an argument for merging it as step one rather than as complete, with the host-reported home (readRemoteHomeCommand at ssh-relay-deploy.ts:245, already resolved on the host during relay deploy) as step two.

Happy to bring that follow-up myself on top of this once it lands — I have it written and mutation-tested, and rebasing it onto this reduces it to the additive parts.

…d take

`isDangerousWorktreeRemovalPath` read `os.homedir()` — the machine running
Orca — and then applied POSIX-only shape rules. SSH orphan cleanup feeds it
remote paths, so a Windows host profile (`C:\Users\bob`) was unrecognised from
a macOS/Linux desktop and the recursive delete lost its last guard, while a
coincidental client-home prefix could refuse a legitimate remote delete.

The removal route already resolves one execution host for the whole removal;
it now resolves one home authority the same way. `WorktreeRemovalHomeAuthority`
is `{ kind: 'client' }` or `{ kind: 'executionHost'; homePath }`, required at
every guard entry point, so the ambient read is unreachable from a remote
removal. The host's answer is the `$HOME` the SSH session already read on the
host during relay deploy — no new probe. Unresolved stays `null`, meaning
unknown, never "same as this client's".

Path-shape rules now cover Windows profiles (`C:\Users`, `C:\Users\<name>`,
any drive or UNC root, case-insensitively) and WSL UNC aliases, which front a
Linux filesystem and so take the POSIX shapes.

Fixes stablyai#18275
The focused code-quality plugins deny `import/no-duplicates`.
…me refusal

Mutation testing found four survivors in the home guard:

- Swapping the IPC unregistered-removal call site to the client's home passed
  every suite while the remote delete could reach the host's own home. Only
  the runtime call site was pinned. Add the mirror test for the IPC path.
- Falling back to os.homedir() when the execution host reported nothing was
  indistinguishable from refusing; the client home never coincided with the
  probed path. Assert the fallback stays off with homedir pinned to the path.
- Comparing an execution-host home across path syntaxes survived because no
  row exercised the win32 home under POSIX ops: path.resolve manufactures
  <cwd>/C:/Users/bob, which every ancestor of the cwd contains.
- Dropping the bare /Users rule survived; add the row.

Also cover the forward-slash C:/Users/bob form normalizeRemoteHome reports
for a Windows host, which no existing row used.
@fettpl
fettpl force-pushed the fix/remote-worktree-home-delete-guard branch from 992b82d to 675c910 Compare September 13, 2026 08:46
@fettpl

fettpl commented Sep 13, 2026

Copy link
Copy Markdown
Contributor Author

Folded #19865 onto this branch (rebased on current main).

The guard now takes an explicit home authority from the execution host (readRemoteHomeCommand / relay remoteHome) instead of os.homedir() for remote deletes. Path-shape detection still covers /Users, WSL UNC Linux homes, and non-C: Windows profiles. Unknown host homes fail closed rather than falling back to the client homedir. IPC and runtime unregistered-removal call sites are pinned.

@fettpl

fettpl commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

Closing as superseded by #19865, which merged and closed #18275.

This branch had folded the host-home authority work onto the path-shape guard, but #19865 landed first and this PR is now conflicting. No further follow-up from this side.

@fettpl fettpl closed this Sep 17, 2026
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.

Do not use the client homedir as the remote worktree home-delete guard

2 participants