Skip to content

fix(worktree): ask the execution host whose home a remote delete would take - #19865

Merged
nwparker merged 11 commits into
mainfrom
fix/remote-worktree-home-delete-guard
Sep 17, 2026
Merged

nwparker merged 11 commits into
mainfrom
fix/remote-worktree-home-delete-guard

Conversation

@nwparker

@nwparker nwparker commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​993 $\color{#cf222e}{\Huge{\mathbf{−}}}$​21 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​972
Prod 14 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​469 $\color{#cf222e}{\Huge{\mathbf{−}}}$​69 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​400

Fixes #18275

ELI5

Before Orca recursively deletes a leftover worktree folder, it checks "wait, is
that somebody's home directory?" The check asked this computer — the one
running the Orca window — even when the folder lives on a remote SSH machine.

Two ways that goes wrong:

  • The remote is Windows and you're on a Mac. C:\Users\bob matched none of the
    POSIX rules (/home/x, /Users/x), and your Mac home /Users/nwparker has
    nothing to say about it. The guard answered "safe to delete" for the host's
    entire home directory.
  • The remote's home isn't in a standard place (/srv/homes/alice). Nothing
    protected it, because only your home was ever consulted.

Now the guard is told whose home it is allowed to think about, and it can't
guess wrong because the type won't let you leave it out.

What changed

The removal route already resolves one execution host for the whole removal.
It now resolves one home authority the same way:

export type WorktreeRemovalHomeAuthority =
  | { kind: 'client' }
  | { kind: 'executionHost'; homePath: string | null }

It is a required argument on every guard entry point
(isDangerousWorktreeRemovalPath, canSafelyRemoveOrphanedWorktreeDirectory,
findRegisteredDeletableWorktree, canCleanupUnregisteredOrcaLeftoverDirectory),
so a remote removal cannot silently fall through to os.homedir() — that read
is reachable only via { kind: 'client' }, and only for paths written in this
platform's syntax.

The host's answer is the $HOME the SSH session already read on the host
during relay deploy (readRemoteHomeCommand → normalizeRemoteHome). No new
probe, no new RPC. null means unknown, never "same as this client's".

Path-shape rules — which travel, because a Windows profile is a Windows profile
no matter which desktop is looking — now also cover:

  • C:\Users, C:\Users\<name>, any drive or UNC root, case-insensitively
    (drive letter comes from parse().root, not a hardcoded C:)
  • /Users alongside the existing /home, /root, /home/<x>, /Users/<x>
  • WSL UNC aliases (\\wsl.localhost\Ubuntu\home\alice), which front a Linux
    filesystem and so take the POSIX shapes rather than <root>\Users

A linked worktree under a home (/home/alice/wt/foo, C:\Users\bob\wt\foo)
stays deletable — that direction is a regression too, and it is tested.

Repro

On this macOS client, against origin/main @ 2bf298d:

client platform: darwin  client homedir: /Users/nwparker

× treats the Windows SSH host's home directory as dangerous
  expected false to be true    isDangerousWorktreeRemovalPath('C:\Users\bob', 'C:\src\repo')
× treats the Windows SSH host profile root as dangerous
  expected false to be true    isDangerousWorktreeRemovalPath('C:\Users', 'C:\src\repo')
✓ still allows a real Windows worktree under the profile

runtime-unregistered-worktree-removal.ts feeds exactly these remote paths into
that guard on the SSH branch and then calls fsProvider.deletePath(path, true).

Tests

  • worktree-removal-home-guard.test.ts — the shape table (POSIX, Windows, WSL
    UNC) plus "whose home": the client home is not consulted for a foreign-syntax
    path (asserted with a spy), is still consulted for a matching one, and a
    host-reported non-standard home is honoured.
  • worktree-removal-safety.test.ts — the issue's table through the public
    guard, and canSafelyRemoveOrphanedWorktreeDirectory refusing the host's home
    with a fully proven orphan .git, i.e. in the state that otherwise
    unlocks the recursive delete.
  • runtime-unregistered-worktree-removal-host-home.test.ts — the real removal
    entry point refuses the host home and never calls deletePath, while still
    deleting a proven orphan beneath it.
  • ssh-active-relay-sessions.test.ts — pins the module-scope wiring, so the
    route cannot quietly answer homePath: null forever.

Mutation results (9/9 killed)

mutation killed by
SAFETY — remove the home check from isDangerousWorktreeRemovalPath 10 assertions, incl. refuses the Windows host's home directory from a POSIX client and … even when the host reported nothing
drop the Windows user-profile rule (the reported bug) 9, incl. all C:\Users… rows
let os.homedir() answer for every syntax again never lets the client homedir answer for a foreign-syntax path
ignore the home the host reported protects a non-standard home the execution host reported + 2
drop the WSL UNC rule the 4 WSL rows
flip containment (block legitimate deletes) keeps a linked worktree under the execution host home deletable + 2
route answers with the client home takes the home from the SSH host that will run the delete + 2
never install the host-home resolver is wired into worktree removal, so an SSH delete asks the host
SSH removal branch uses the client home refuses to recursively delete the host's own home directory

The last one survived the first pass — nothing pinned the call site — which
is why runtime-unregistered-worktree-removal-host-home.test.ts exists.

Second mutation pass (review)

A second pass with different mutations found four more survivors, now killed:

mutation survived because now killed by
IPC remove-unregistered-worktree.ts uses the client home instead of repo.connectionId only the runtime call site was pinned; the IPC route is the desktop delete path ipc/worktrees/removal/remove-unregistered-worktree-host-home.test.ts
executionHost with homePath: null falls back to os.homedir() no test pinned homedir() to the probed path, so the fallback and the refusal were indistinguishable never lets an unknown execution-host home fall back to the client homedir
compare an execution-host home across path syntaxes no row resolved a win32 home under POSIX ops; path.resolve manufactures <cwd>/C:/Users/bob, which every ancestor of the cwd "contains" third assertion in ignores an execution-host home written in the other platform s syntax
drop the bare /Users rule no /Users row at the isDangerousWorktreeRemovalPath level /Users under /opt/src -> dangerous=true

Also added: the forward-slash C:/Users/bob form normalizeRemoteHome actually
reports for a Windows host (no existing row used it; getPathOps classifies it
as win32 and win32.resolve normalises it, so it already worked).

Note

ipc/ssh-active-relay-sessions.ts is injected into the route module via a
setter rather than imported by it, matching the existing
setSshActiveMultiplexerResolver pattern: importing the session table directly
runs its module-scope registration inside the ~30 suites that partially mock the
SSH registry, which fails them all.

Gates

pnpm tc, pnpm test src/main/runtime src/main/ipc … (11 395 passed),
oxlint, pnpm run check:code-quality:changed, pnpm run check:max-lines-ratchet,
pnpm format.

Rebase record (2026-09-11)

Rebased onto main at 5fa62feda7c264c6eda99ba4788ffebab9aae26c. No conflicts.

SHA
old head 98efec6118d5caf4733a54b2d79843c7df579fcf
new head bb5a35e0f433cee25f1eae027fe177868bf6d8df

#20051 stacks on this branch and was replayed onto the new head.


Rebased onto main @ 231e805b1e1e49c765e96b9409f88e09d117346a (2026-09-15).

  • Old head: bb5a35e0f433cee25f1eae027fe177868bf6d8df
  • New head: 097ccecde0e3ecdadd06fbde2e8d0bc41fc5ba66

Conflict in src/main/ipc/worktrees/removal/execute-worktree-removal.ts resolved by taking main's renamed removeStaleLocalWorktreeRegistration plus this PR's resolveWorktreeRemovalHomeForConnection import. Two added commits satisfy gates main has tightened since: the casting gate, and the 300-line ceiling that the added home lookup pushed orca-runtime-remove-managed-worktree.ts past (the route's git-options-and-listing step is now its own module). Verified with git range-diff; prior CI results predate this rebase.

@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 — a single commit that re-roots the worktree-removal home guard onto the execution host whose filesystem actually gets deleted.

  • WorktreeRemovalHomeAuthority threading — a new required home argument ({ kind: 'client' } vs { kind: 'executionHost'; homePath }) on every guard entry point, so os.homedir() is reachable only through { kind: 'client' } and a remote removal can no longer silently consult the wrong machine's home.
  • Path-shape detection expansion — POSIX, Windows drive/UNC Users profiles (case-insensitive, drive letter from parse().root), and WSL UNC aliases, moved into worktree-removal-home-guard.ts so a Windows profile is dangerous regardless of which desktop is looking.
  • Host home sourced from existing deploy data — getRemoteHomeDirectory() returns remoteCliBridgeEnv.remoteHome (already read on the host via readRemoteHomeCommand/normalizeRemoteHome), wired through a setWorktreeRemovalSshHostHomeResolver setter matching the existing setSshActiveMultiplexerResolver pattern; no new RPC.
  • Call-site and test updates — IPC and runtime removal paths threaded with CLIENT_REMOVAL_HOME for local removals and the resolved host home for SSH, backed by a shape table, the real removal entry point, and module-wiring tests.

The core logic is sound: resolveGuardHomePath only lets a home answer for paths in its own syntax (so a POSIX home can't be win32.resolved against a C:\… path), the containment check correctly distinguishes "removing the home" from "removing a worktree under it", and the WSL UNC branch deliberately routes Linux-shaped paths to POSIX rules. Tests assert exact verdicts rather than truthiness and pin the previously-uncovered SSH removal branch.

Pullfrog  | 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 — one new commit since the prior review (a0be358).

  • Import dedup — merges the two ../worktree-removal-execution-host-route imports in orca-runtime-remove-managed-worktree.ts into a single, alphabetized { resolveWorktreeRemovalHome, resolveWorktreeRemovalRoute } block. Purely mechanical; no behavioral change.

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

@coderabbitai

coderabbitai Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview 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
📝 Walkthrough

Walkthrough

The change adds explicit client and execution-host home authorities for worktree removal safety. It detects protected POSIX, Windows, and WSL home paths by path syntax and reported SSH host home. SSH relay sessions expose the remote home and register a resolver. Registered, unregistered, managed, local, and SSH removal flows pass the resolved authority into safety checks. Tests cover routing, path detection, host-home protection, and valid orphan cleanup.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🟠 High · up to 15055

An SSH cleanup with an unresolved custom host home can recursively delete the remote user’s home directory and unrelated files; cleanup should fail closed before merging.

🚥 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
Linked Issues check ✅ Passed The changes satisfy the coding requirements in #18275. worktree-removal-home-guard.ts uses explicit WorktreeRemovalHomeAuthority values, detects POSIX, Windows, UNC, and WSL home shapes from path …
Out of Scope Changes check ✅ Passed The changed files support #18275. The SSH session accessor, route resolver, removal call-site updates, and focused tests provide the required home authority and safety coverage. The summary shows no p…
Title check ✅ Passed The title clearly identifies the main change: using the execution host's home directory for remote worktree deletion safety.
Description check ✅ Passed The description is detailed and covers the problem, implementation, linked issue, cross-platform behavior, tests, mutation results, and validation gates. It omits several template headings, including …
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🛠️ 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.

@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 — one test-only commit (4f145f6) that closes the remaining mutation-testing survivors in the home guard.

  • IPC call-site pin — a new remove-unregistered-worktree-host-home.test.ts drives the real removeUnregisteredWorktree over SSH and asserts it refuses the host's own home (never calling deletePath) while still deleting a proven orphan beneath it; mutation testing had shown that substituting the client's home at this call site passed every other suite while a remote delete could still reach the host's home.
  • Guard regression cases — four additions to worktree-removal-home-guard.test.ts plus the bare /Users row in worktree-removal-safety.test.ts: no os.homedir() fallback when the host reports nothing (spy asserts homedir is untouched), the forward-slash C:/Users/bob form normalizeRemoteHome stores for a Windows host, a foreign-syntax host home under POSIX ops (process.cwd()), and the bare /Users shape.

Each new assertion is an exact verdict backed by a spy where a fallback must stay off, not a truthiness check — and all four targeted suites pass. The delta introduces no behavioral surface of its own.

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

@fettpl

fettpl commented Sep 13, 2026

Copy link
Copy Markdown
Contributor

Folded this work onto #18341 (same three commits, rebased onto current main). Leaving this PR for you to close if you want a single landing path.

…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 #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.
@nwparker
nwparker force-pushed the fix/remote-worktree-home-delete-guard branch from bb5a35e to 1505500 Compare September 15, 2026 09:33

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

Caution

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

⚠️ Outside diff range comments (1)

🟠 Major · Fail closed when the SSH host home is unresolved. · src/main/worktree-removal-home-guard.ts:56-92

56-92: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Fail closed when the SSH host home is unresolved. homePath: null makes /srv/homes/alice pass isHomeDirectoryRemovalPath because syntax-only checks do not recognize that home shape. With the orphan and force-removal preconditions met, the SSH path calls fsProvider.deletePath(worktreePath, true), whose recursive argument can delete the host home.

  if (home.kind === 'executionHost' && home.homePath === null) {
    return true
  }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 87fc8bc2-af3d-4bbf-b0ff-4270040f49e0

📥 Commits

Reviewing files that changed from the base of the PR and between bb5a35e and 1505500.

📒 Files selected for processing (4)
  • src/main/ipc/worktrees/removal/execute-worktree-removal.ts
  • src/main/runtime/orca-runtime-remove-managed-worktree.ts
  • src/main/runtime/runtime-registered-local-worktree-removal.ts
  • src/main/ssh/ssh-relay-session.ts

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

Rebasing onto main brings two gates this branch predates:
typescript/consistent-type-assertions at assertionStyle: never, and the
300-line ceiling that the added home lookup pushed
orca-runtime-remove-managed-worktree.ts past. The fixture casts carry
per-site SAFETY rationales; the route's git-options-and-listing step
moves into its own module, which also stops the local/SSH branch being
spelled twice in one expression.
main enabled anti-slop/no-shape-in-symbol-names (#20785) after this
branch was written. The predicate answers whether a path IS a home root,
not whether it resembles one.
Review of the home guard found three ways it still let a delete proceed on
evidence about the wrong machine, or on no evidence at all.

`getPathOps` switches to win32 as soon as EITHER the worktree path or the repo
path looks Windows-absolute, and `//nas/share/repo` does. A POSIX worktree path
was then judged by Windows-only shape rules, which recognise `<root>\Users\<name>`
and nothing else, so `/home/alice` — and any client home outside `\Users` —
stopped matching and the last guard in front of a recursive delete went quiet.
The home question involves the worktree path and a home, never the repo path, so
the predicate now reads the path in its own syntax as well and refuses if either
reading names a home. A union of refusals can only ever refuse more.

An execution host that never reported its `$HOME` is `unverifiable`, and
`unverifiable` does not authorise a delete. `isRemovalHomeAuthorityResolved`
gates the two paths that recursively delete a directory —
`canSafelyRemoveOrphanedWorktreeDirectory` and
`canCleanupUnregisteredOrcaLeftoverDirectory` — because the orphan proof they
accept, a `.git` file at the top of a directory, is also what a bare-repo
dotfiles `$HOME` looks like, and there the guard is the only evidence there is.
`git worktree remove` is deliberately not gated: the host's own Git registry
already established that the path is a linked worktree of that repo, and a
missing second opinion does not retract a first one. An empty `$HOME` is
normalised to unanswered rather than read as a resolved home.

The IPC entry point spelled its host two ways. The metadata prune, the
archive-hook route and now the home authority came from
`getRepoExecutionHostId(repo)`, while the `git worktree list` and every delete
came from raw `repo.connectionId`. A row carrying only
`executionHostId: 'ssh:<target>'` therefore listed a remote checkout on this
client and deleted a same-named local path while the guards vouched for the
remote one; the mirror row did the reverse (#11163, previously fixed on the
runtime path only). Neither spelling is evidence about the other, so a row that
carries two host names is refused before anything is listed or deleted. Both
sides are spelled by `getRepoExecutionHostId`, so they can differ on content but
never on normalisation.

A `runtime:<env>` row refuses here for the same reason. It is not reachable
through this handler today — the renderer sends environment targets to
`worktree.rm`, and the host-qualified catalog refuses to list a runtime host —
so that arm closes a door rather than changing a flow.

Fixtures that register an SSH provider now report a host home, because a
connected relay session always has one: `remoteCliBridgeEnv` is assigned before
`registerSshGitProvider`, is never cleared, and providers are unregistered
before the session leaves `activeSessions`. The wiring lives in its own module
called from the harness rather than in `worktrees-test-module-mocks`, which
`vi.mock` factories import: reaching the production route module from there
pulls in `providers/ssh-git-dispatch` while it is being mocked, and the module
runner deadlocks.

@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 — one commit since the prior Pullfrog review (097ccec), 6a6727c "refuse a removal the execution host cannot vouch for", with the tests that pin it.

  • Recursive deletes now fail closed — canSafelyRemoveOrphanedWorktreeDirectory and canCleanupUnregisteredOrcaLeftoverDirectory return false unless isRemovalHomeAuthorityResolved(home), so an SSH host that never reported $HOME leaves a proven-orphan directory in place rather than recursively deleting it; executionHostRemovalHome('') normalises an empty answer to unknown. This is exactly the failure git worktree remove deliberately does not adopt, and the JSDoc explains why.
  • Home route keyed on the execution host id — resolveWorktreeRemovalHomeForHost(hostId) replaces the connectionId-keyed resolver, parsing the ExecutionHostId so an ssh:<target>-only row asks the right host, while runtime: and unparseable ids stay unknown instead of borrowing this client's home.
  • Repo-row host disambiguation (#11163) — assertRemovalHostMatchesRepoRow refuses a repo whose executionHostId and connectionId name different machines before any listing or delete, closing the "listed remote, deleted local" path.
  • Mixed-syntax path ops — isHomeDirectoryRemovalPath re-reads the worktree path under its own syntax when the worktree/repo pair dragged getPathOps into the other platform, so a POSIX home stays recognised when the repo path is //-rooted or Windows-shaped. The check is additive (OR), so it only widens protection.
  • Test coverage — new handler/disambiguation suite, unknown-host-home refusal at both the IPC and runtime entry points, isRemovalHomeAuthorityResolved/empty-home cases, the mixed-syntax pair table, and a shared harness fixture that makes IPC SSH suites model a connected session's $HOME.

I verified the fail-closed gate is unreachable for a live session — remoteCliBridgeEnv is only assigned when remoteHome is truthy, validateRemoteHome throws on an invalid home, and a removal needs a registered provider — so the unverifiable refusal is a backstop, not a regression. I also confirmed the new repo-row assert cannot fire on a normal SSH row: target ids are ssh-<timestamp>-<base36> (no encode/decode variance) and renderer stamping uses toSshExecutionHostId(connectionId).

ℹ️ The PR now ships a separate #11163 fix under a #18275 description

The latest commit folds assertRemovalHostMatchesRepoRow into a PR whose description advertises only #18275. Both changes are sound and tested, but the disambiguation adds a new hard-refusal path with a blast radius independent of the home guard, and #11163 is not mentioned in the body. Worth a line in the description (and the changelog) so reviewers can treat the two as separately revertible.

Technical details
# The #11163 refusal is its own change

## Affected sites
- `src/main/ipc/worktrees/removal/execute-worktree-removal.ts:47-63` — `assertRemovalHostMatchesRepoRow` throws when `removalHostId !== getRepoExecutionHostId({ connectionId: repo.connectionId, executionHostId: null })`.
- PR body — "Fixes #18275"; no mention of #11163 or the new refusal.

## Required outcome
- No code change required if the bundling is intentional. The ask is a description/changelog line naming #11163 and the fact that a contradictorily-spelled repo row is now refused (worktree left in place) rather than deleted.

## Open questions for the human
- Is a `runtime:<env>` row with a nested SSH `connectionId` reachable through the desktop `worktrees:remove` IPC at all? If so, the new assert refuses it (runtime spelling vs `ssh:` connection id) — safe, but a distinct behaviour change from the #18275 guard. Runtime removals appear to route through `removeManagedWorktree`, so this is likely theoretical.

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

…ed text

`getRepoExecutionHostId` returns a row's `executionHostId` as stored, while the
same row's `connectionId` is re-spelled through `toSshExecutionHostId`, which
percent-encodes. A byte compare of the two would refuse a perfectly consistent
row over a `%20`, so the two host ids are now compared after `parseExecutionHostId`
has decoded the target id out of each.

`runtime:<env>` and an unparseable id decode to no machine at all and match
nothing, including each other — a runtime-owned row has a null `connectionId`
and would otherwise read as local, which is a delete on this client.

@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 comment-accuracy nit inline.

Reviewed changes — one commit since the prior Pullfrog review (6a6727c548): 865083bd63 "compare removal host names after decoding, not as stored text".

  • Decoded host comparison — assertRemovalHostMatchesRepoRow now compares removalHostName(hostId) (the parsed local / ssh:<targetId>) instead of the stored text, so a repo row whose executionHostId and re-encoded connectionId differ only by a percent-escape is accepted rather than refused. This is the right direction: the two spellings name the same target id, and the route/provider lookups already key on it.
  • New handler tests — a runtime:<env> row with a null connectionId is refused before any listing or delete, and a %20-escaped-but-consistent SSH row is driven through the real worktrees:remove handler; the previous byte-compare would have refused the latter.

The comparison change is narrow and correct — target ids are what the route and guards actually key on, so normalising the escape spelling only removes a false refusal.

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

The type-aware audit rejects a `default` arm on a discriminated switch, so the
host-kind switch names `runtime` and `undefined` outright — which also makes a
host kind added later a compile error here rather than a silent fallthrough.

The two test casts the changed-code gate flagged are gone: the leftover-cleanup
meta is typed instead of asserted, and the unparseable-host-id case narrows to
`ExecutionHostId` with the SAFETY rationale the gate asks for.
…ain compare

The comparison refuses `runtime:<env>` because only the left operand can name
no machine — `repoRowHostId` comes from `connectionId` and is always `local` or
an `ssh:` id. That invariant was doing the work silently; an explicit null test
in its place was a branch no input can reach, so the reason is written down
instead.
I argued `git worktree remove --force` did not need the host's home answer,
because the host's own Git registry had already established that the path is a
linked worktree of that repo. That is true and it is not enough: `git worktree
add` accepts a pre-existing empty directory, and that directory can afterwards
be somebody's `$HOME` — a build account's home, a container's `HOME=/workspace`.
Being a linked worktree proves provenance, not that the path is not a home, and
the remove deletes the checkout either way.

With the host's answer that case is already caught by containment. Without it
only the path shapes remain, and a home at a non-standard location
(`/var/home/<u>`, `/export/home/<u>`, `D:\\Profiles\\<u>`) has no shape to match.
So `findRegisteredDeletableWorktree` now requires the answer as well, and every
gate that authorises a delete is on the same rule.

The fixture that models a connected relay session moves out of `ipc/` and is
shared: four runtime specs register an SSH provider without one, and a live
provider implies a reported home in production.

@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 — one commit since the prior Pullfrog review (94a80e1d94): 13a306974f "gate the registered removal on the host home answer too".

  • Registered removals now fail closed on an unknown host home — findRegisteredDeletableWorktree refuses unless isRemovalHomeAuthorityResolved(home), so git worktree remove no longer leans on the host's Git registry as proof that a path is not a $HOME. Every delete-authorising gate in worktree-removal-safety.ts is now on the same rule, and the JSDoc on isRemovalHomeAuthorityResolved was rewritten to say why the registry does not help (a linked worktree of a repo can afterwards be a build account's home or a HOME=/workspace).
  • SSH-home fixture moved and shared — ipc/worktrees-test-ssh-host-home.ts relocated to src/main/worktree-removal-test-ssh-host-home.ts and installed via beforeEach in the four runtime specs that register an SSH provider but supplied no home answer; ipc/worktrees-test-harness.ts follows the new path.
  • Test for the new gate — a findRegisteredDeletableWorktree case asserting the unanswered-home and matching-home refusals plus a non-matching-home delete, with exact-verdict assertions (not truthiness).

I checked the one thing that could make this a regression rather than a backstop: an SSH removal resolves its route only when a git provider is registered, and that provider is installed after establish() has read remoteHome into remoteCliBridgeEnv (validateRemoteHome throws otherwise) — so an unanswered home cannot co-exist with a usable SSH route. Local call sites pass CLIENT_REMOVAL_HOME. Focused suites pass: worktree-removal-*, the worktree IPC removal suites, and the full src/main/ipc run (3965 tests). The .spec.ts runtime specs are not collected by config/vitest.config.ts, so I also confirmed the fixture change is the only reason those four needed updating.

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

@nwparker
nwparker merged commit a46b5b1 into main Sep 17, 2026
34 checks passed
@nwparker
nwparker deleted the fix/remote-worktree-home-delete-guard branch September 17, 2026 05:24
@nwparker
nwparker restored the fix/remote-worktree-home-delete-guard branch September 17, 2026 05:25
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
…d take (stablyai#19865)

* fix(worktree): ask the execution host whose home a remote delete would 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

* fix(worktree): merge the duplicated removal-route import

The focused code-quality plugins deny `import/no-duplicates`.

* test(worktree): pin the IPC removal call site and the unknown-host-home 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.

* ci: re-run after an unrelated Electron probe startup timeout

* fix(lint): clear the casting and max-lines gates on the home guard

Rebasing onto main brings two gates this branch predates:
typescript/consistent-type-assertions at assertionStyle: never, and the
300-line ceiling that the added home lookup pushed
orca-runtime-remove-managed-worktree.ts past. The fixture casts carry
per-site SAFETY rationales; the route's git-options-and-listing step
moves into its own module, which also stops the local/SSH branch being
spelled twice in one expression.

* fix(lint): name the home predicate for what it matches

main enabled anti-slop/no-shape-in-symbol-names (stablyai#20785) after this
branch was written. The predicate answers whether a path IS a home root,
not whether it resembles one.

* fix(worktree): refuse a removal the execution host cannot vouch for

Review of the home guard found three ways it still let a delete proceed on
evidence about the wrong machine, or on no evidence at all.

`getPathOps` switches to win32 as soon as EITHER the worktree path or the repo
path looks Windows-absolute, and `//nas/share/repo` does. A POSIX worktree path
was then judged by Windows-only shape rules, which recognise `<root>\Users\<name>`
and nothing else, so `/home/alice` — and any client home outside `\Users` —
stopped matching and the last guard in front of a recursive delete went quiet.
The home question involves the worktree path and a home, never the repo path, so
the predicate now reads the path in its own syntax as well and refuses if either
reading names a home. A union of refusals can only ever refuse more.

An execution host that never reported its `$HOME` is `unverifiable`, and
`unverifiable` does not authorise a delete. `isRemovalHomeAuthorityResolved`
gates the two paths that recursively delete a directory —
`canSafelyRemoveOrphanedWorktreeDirectory` and
`canCleanupUnregisteredOrcaLeftoverDirectory` — because the orphan proof they
accept, a `.git` file at the top of a directory, is also what a bare-repo
dotfiles `$HOME` looks like, and there the guard is the only evidence there is.
`git worktree remove` is deliberately not gated: the host's own Git registry
already established that the path is a linked worktree of that repo, and a
missing second opinion does not retract a first one. An empty `$HOME` is
normalised to unanswered rather than read as a resolved home.

The IPC entry point spelled its host two ways. The metadata prune, the
archive-hook route and now the home authority came from
`getRepoExecutionHostId(repo)`, while the `git worktree list` and every delete
came from raw `repo.connectionId`. A row carrying only
`executionHostId: 'ssh:<target>'` therefore listed a remote checkout on this
client and deleted a same-named local path while the guards vouched for the
remote one; the mirror row did the reverse (stablyai#11163, previously fixed on the
runtime path only). Neither spelling is evidence about the other, so a row that
carries two host names is refused before anything is listed or deleted. Both
sides are spelled by `getRepoExecutionHostId`, so they can differ on content but
never on normalisation.

A `runtime:<env>` row refuses here for the same reason. It is not reachable
through this handler today — the renderer sends environment targets to
`worktree.rm`, and the host-qualified catalog refuses to list a runtime host —
so that arm closes a door rather than changing a flow.

Fixtures that register an SSH provider now report a host home, because a
connected relay session always has one: `remoteCliBridgeEnv` is assigned before
`registerSshGitProvider`, is never cleared, and providers are unregistered
before the session leaves `activeSessions`. The wiring lives in its own module
called from the harness rather than in `worktrees-test-module-mocks`, which
`vi.mock` factories import: reaching the production route module from there
pulls in `providers/ssh-git-dispatch` while it is being mocked, and the module
runner deadlocks.

* fix(worktree): compare removal host names after decoding, not as stored text

`getRepoExecutionHostId` returns a row's `executionHostId` as stored, while the
same row's `connectionId` is re-spelled through `toSshExecutionHostId`, which
percent-encodes. A byte compare of the two would refuse a perfectly consistent
row over a `%20`, so the two host ids are now compared after `parseExecutionHostId`
has decoded the target id out of each.

`runtime:<env>` and an unparseable id decode to no machine at all and match
nothing, including each other — a runtime-owned row has a null `connectionId`
and would otherwise read as local, which is a delete on this client.

* fix(lint): clear the static-analysis gates on the removal home authority

The type-aware audit rejects a `default` arm on a discriminated switch, so the
host-kind switch names `runtime` and `undefined` outright — which also makes a
host kind added later a compile error here rather than a silent fallthrough.

The two test casts the changed-code gate flagged are gone: the leftover-cleanup
meta is typed instead of asserted, and the unparseable-host-id case narrows to
`ExecutionHostId` with the SAFETY rationale the gate asks for.

* docs(worktree): say why an unroutable removal host is refused by a plain compare

The comparison refuses `runtime:<env>` because only the left operand can name
no machine — `repoRowHostId` comes from `connectionId` and is always `local` or
an `ssh:` id. That invariant was doing the work silently; an explicit null test
in its place was a branch no input can reach, so the reason is written down
instead.

* fix(worktree): gate the registered removal on the host home answer too

I argued `git worktree remove --force` did not need the host's home answer,
because the host's own Git registry had already established that the path is a
linked worktree of that repo. That is true and it is not enough: `git worktree
add` accepts a pre-existing empty directory, and that directory can afterwards
be somebody's `$HOME` — a build account's home, a container's `HOME=/workspace`.
Being a linked worktree proves provenance, not that the path is not a home, and
the remove deletes the checkout either way.

With the host's answer that case is already caught by containment. Without it
only the path shapes remain, and a home at a non-standard location
(`/var/home/<u>`, `/export/home/<u>`, `D:\\Profiles\\<u>`) has no shape to match.
So `findRegisteredDeletableWorktree` now requires the answer as well, and every
gate that authorises a delete is on the same rule.

The fixture that models a connected relay session moves out of `ipc/` and is
shared: four runtime specs register an SSH provider without one, and a live
provider implies a reported home in production.
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