Skip to content

fix(worktree): block removal when the archive hook fails - #20153

Merged
nwparker merged 3 commits into
mainfrom
fix/archive-hook-gate
Sep 15, 2026
Merged

nwparker merged 3 commits into
mainfrom
fix/archive-hook-gate

Conversation

@nwparker

@nwparker nwparker commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 22 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1068 $\color{#cf222e}{\Huge{\mathbf{−}}}$​249 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​819
Prod 32 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1196 $\color{#cf222e}{\Huge{\mathbf{−}}}$​167 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1029

Stacked on #20559. That PR makes a timed-out
hook report honestly; merge it first, or a hook that traps SIGTERM and exits 0 defeats this gate.
This PR's diff is the gate only — no hook-termination code.

In plain terms

Some teams tell Orca to run a "save my work somewhere safe" step right before a workspace gets
deleted — copying files to a backup, pushing a branch, exporting notes. If that save step failed,
Orca went ahead and deleted the workspace anyway, and in some cases still reported the delete as
successful. The work the save step was supposed to rescue was simply gone.

Now a failed save step stops the deletion. Nothing is removed, and you get told what failed and
why, so you can fix it and try again. If you decide you don't care and want the workspace gone
regardless, there's an explicit opt-out flag that deletes it anyway and tells you afterwards that
the save step had failed. Deliberately, the ordinary "force" option does not do this on your
behalf — throwing away a failed backup has to be something you asked for by name.

Fixes #19334

A repo's archive hook is the user's last chance to save work off a checkout Orca is about to
delete. A failed hook was logged as an advisory and stepped over, so the destructive removal went
ahead with nothing archived — and the caller could still receive success. This makes the hook a
blocking precondition.

The ordering invariant

The gate is evaluated while the checkout, its Git registration, its agents and Orca's ownership
evidence are all still intact
. On failure it throws, and no caller has yet stopped a PTY or
deleted a file. In both orchestrators it sits ahead of the registration re-read, the dirty
preflight, stopPtys() and removeWorktree:

  • src/main/runtime/runtime-registered-local-worktree-removal.ts:78
  • src/main/ipc/worktrees/removal/execute-worktree-removal.ts:152 — where the SSH archive hook runs

gateWorktreeRemovalOnArchiveHook (src/main/worktree-archive-hook-gate.ts) is the single
precondition both call; its doc comment states the contract so a future caller cannot quietly move
it below a mutation.

One stated exception, added by the rebase onto #20617. That PR introduced a
registration-cleanup branch in execute-worktree-removal.ts that returns before the gate. The
ordering is right and I left it: both of its arms describe a registration with no checkout behind it
— a row whose path is itself a .git file, or a tree already gone from disk — so there is nothing
to archive, and running the hook would fail on the missing cwd and block a cleanup that has no user
data to lose. Since the invariant is documented, the exception now is too, in a comment at the
branch.

Affected vs. unaffected paths

Path Runs an archive hook? Gated
Runtime, registered local worktree yes (--run-hooks) yes
IPC, registered local worktree yes yes
IPC, registered remote/SSH worktree yes (runRemoteArchiveHook) yes
Runtime, registered remote/SSH worktree no — it cannot refuses, waivable (see below)
Folder workspace removal (IPC + runtime) no unchanged
Unregistered / orphan removal no unchanged
Windows stale-registration recovery no (pre-existing — the checkout is already gone from disk) unchanged

The untouched rows are untouched because they run no hook at all, not because they were judged
safe. The runtime remote/SSH row is the exception and is spelled out below: it cannot run a hook, so
rather than delete with the archive step silently skipped it refuses — and, like every other refusal
here, that refusal is waivable and the waiver is recorded. Scenario 6 below exercises the folder-workspace boundary end to end to prove it.

The override, and why it is not --force

--force already carries a different waiver: since #11960 it means "waive the proof that every PTY
stopped", and the desktop sets it for an ordinary confirmed delete. Folding the archive waiver into
it would mean every routine confirmed delete silently waives a failed archive step — exactly the
bug. So the waiver travels on its own field at every layer:

  • CLI: orca worktree rm --allow-failed-archive-hook
  • RPC: allowFailedArchiveHook on WorktreeRemove
  • IPC / preload: allowFailedArchiveHook on RemoveWorktreeArgs

It is also distinct from skipArchive / runHooks, which decide whether the hook runs at all — the
waiver applies only to a hook that ran and failed. When used, the failure is reported back on
result.archiveHookOverride rather than being swallowed, and the CLI prints it to stderr.

Both in-flight dedupe keys carry it (getWorktreeRemovalOptionsKey,
getRuntimeWorktreeRemovalOptionsKey), for the same reason the PTY waiver already did: a waived
retry must not coalesce onto the in-flight attempt that is about to refuse.

unverifiable is not exited

Per docs/reference/ssh-execution-boundary.md, loss of contact is never evidence of an outcome.
ArchiveHookRunResult.exitCode is withheld whenever no exit was observed — spawn error, hook
timeout, a lost SSH channel — and the gate classifies that unverifiable rather than folding it
into exited. Both block; neither is ever read as "the hook passed".

Getting that right on the local path needed more than withholding a code, and that work is
#20559 — this PR is stacked on it. Node's
exec({ timeout }) only SIGTERMs, so a hook that traps SIGTERM and exits 0 was reported as a PASS;
without that fix a trapping hook would walk straight through this gate. The classification table and
its real-shell evidence live there.

Caller contract change

removeManagedWorktree gained the waiver and, with it, a fourth boolean. Rather than a sixth
positional argument — removeManagedWorktree(id, false, true, false, undefined, true) — the options
now travel as a named object:

runtime.removeManagedWorktree(params.worktree, {
  force, runHooks, allowUnverifiedPtyStop, allowFailedArchiveHook, hostId
})

Three of the four are interchangeable "waive a different safety check" booleans on a call that
deletes a user's checkout, so a transposition is a data-loss bug that reads fine. The shape now
matches the IPC coordinator's getWorktreeRemovalOptionsKey(args: Pick<RemoveWorktreeArgs, …>).
Every call site is converted and the compiler verifies it; the second commit is that refactor on
its own so the behaviour change stays reviewable separately.

Real-repo verification

Beyond unit tests, the gate was driven end to end against the built CLI talking to the built
headless runtime
(out/main/index.js --serve), over real git repositories and worktrees on
disk
. The harness is committed as config/scripts/archive-hook-removal-repro.mjs so this is
reproducible rather than a claim about a script you cannot see: build the CLI and the electron
bundle, then run it. 38/38 checks pass.
The hook is a real orca.yaml script whose behaviour is switched by a control file.

1 — hook exits 23: removal refused, nothing deleted

The worktree also holds an untracked PRECIOUS.txt, standing in for unarchived work.

$ orca worktree rm --worktree <id> --run-hooks
  exit code: 1
  Archive hook failed for worktree: …/gate-fail-a3b333 — exited 23. Nothing was stopped, deleted or
  deregistered. Fix the hook and retry, or delete anyway with `orca worktree rm --allow-failed-archive-hook`.
  [archive-hook] running in …/gate-fail-a3b333
  [archive-hook] backup target unreachable

$ orca worktree rm --worktree <id> --force --run-hooks --json      # --force must NOT waive
  exit code: 1
  {"ok":false,"error":{"code":"worktree_archive_hook_failed",
   "data":{"worktreePath":"…/gate-fail-a3b333","outcome":"exited","exitCode":23,
           "output":"…backup target unreachable…"}}}

Filesystem and Git afterwards — read directly, not through Orca:

$ ls -la <worktree>
  drwxr-xr-x@ 6 nwparker  staff  192 .
  -rw-r--r--@ 1 nwparker  staff  120 .git
  -rw-r--r--@ 1 nwparker  staff  542 orca.yaml
  -rw-r--r--@ 1 nwparker  staff   37 PRECIOUS.txt      <-- unarchived work, intact
  -rw-r--r--@ 1 nwparker  staff    9 README.md

$ git worktree list                                     # in the repo
  /private/var/folders/…/agh-repo-hooked-QLKIyl          d8e26dc [main]
  /Users/nwparker/orca/workspaces/…/gate-fail-a3b333     d8e26dc [gate-fail-a3b333]   <-- still registered

orca worktree show still resolves it, and the hook is confirmed to have actually run (twice —
plain, then --force). The checkout was also dirty, and the plain run reported the archive
failure rather than the dirty-preflight failure: direct evidence that the gate precedes that
preflight.

2 — --allow-failed-archive-hook: proceeds, waiver recorded

  exit code: 0
  {"ok":true,"result":{"removed":true,
   "archiveHookOverride":{"worktreePath":"…","outcome":"exited","exitCode":23,
                          "output":"…","overridden":true}}}

Checkout gone from disk, gone from git worktree list, and the waived failure is on the result.

3 / 4 — hook exits 0, and no hook configured

Both remove normally (exit 0, checkout deleted, registration gone), and neither returns an
archiveHookOverride. With no hook configured the hook is confirmed never to have been invoked.

5 — the unverifiable path

The hook is killed (kill -KILL $$), so the host never reports an exit:

  exit code: 1
  {"ok":false,"error":{"code":"worktree_archive_hook_failed",
   "data":{"worktreePath":"…/gate-unver-…","outcome":"unverifiable",
           "output":"…losing the execution host now…"}}}

outcome: "unverifiable", no exitCode field at all — it is withheld rather than reported as a
pass — and the checkout and its Git registration both survive.

6 — folder workspace removal, unchanged

A real folder project (kind: folder), imported with project setup-existing-folder:

  • its project root still refuses for its own pre-existing reason (Cannot delete the project root workspace), not the archive gate;
  • a child folder workspace removes cleanly (exit 0, deregistered, selector_not_found afterwards);
  • no archive hook ran on that path;
  • the folder's contents are left on disk — a forget, not a delete.

Desktop surface

The refusal is reachable from the desktop app, not just the CLI — and the desktop needs its own way
out, because the confirm dialog already passes force (DeleteWorktreeDialog.tsx:86,
forceOnConfirm defaults to true) and force deliberately does not waive the archive hook. Without
an in-app waiver, a user whose hook was failing could not delete any workspace from the app.

So the failure toast now offers Delete Anyway, alongside the existing Force Delete slot. It is
an informed choice made after reading the refusal — not a checkbox ticked in advance, which would
be pre-authorising the loss of a backup nobody knew would fail yet.

Driven through the real UI (right-click workspace → Delete → confirm → Run hooks) against a real
project whose orca.yaml archive step exits 23, with an uncommitted CHANGELOG-draft.md standing
in for unsaved work:

desktop refusal toast with Delete Anyway

Verified end to end against that running app:

Step Result
Confirm delete (passes force: true) refused; workspace still in the sidebar
Toast buttons ["View", "Delete Anyway"]
Toast lifetime Infinity — a destructive choice must not expire while being read
Checkout on disk present, with CHANGELOG-draft.md intact
git worktree list still registered
Click Delete Anyway gone from sidebar, gone from disk, gone from git worktree list, no error

Entry-point coverage: sidebar context menu, batch delete and lineage delete-all all route through
runWorktreeDeleteWithToast and get the button. The status-bar Workspace Space panel renders its
own error and does not — tracked in #20196.

A defect this screenshot caught

The first capture of that toast read:

Failed to delete workspace release-notes
Error invoking remote method 'worktrees:remove': WorktreeArchiveHookFailedError: Archive hook
failed for worktree: … — exited 23. Nothing was stopped, deleted or deregistered. …

Electron's IPC wrapper and the error class name pushed the sentence that matters onto the second
line, so the third commit strips both.

Reviewer note — this is wider than the archive fix needs. The strip is applied at the single
point where any worktree-removal failure becomes a string, so every removal error now displays
unwrapped, not just archive ones. That was a deliberate choice: the wrapper is equally useless on
a dirty-preflight or SSH-provider failure. It is safe for behaviour —
classifyWorktreeForceDeleteReason and isLockedWorktreeRemovalError match substrings, and a
prefix strip cannot change a substring match — but it is a real presentational change beyond this
PR's stated scope. Six tests in store-worktree-removal-cascade.test.ts that deliberately assert
the wrapped string are updated to assert the stripped one; their actual subject (classification
still works on wrapped input) is unchanged. If a reviewer wants the strip narrowed to the archive
refusal only, that is a one-line change to the call site.

Three other components hand-roll the same regex privately; converging them would change
quick-open-file-list's behaviour, so it is left to #20196 rather than folded in here.

The capability integrations asked for

The reporter's acceptance list ended with a request this PR would otherwise have missed: "A
machine-readable capability indicating that archive failures block removal would also let
integrations distinguish 'supports --run-hooks' from 'safely propagates a failing hook.'"
They
had already coded Harbour against worktree.archive-failure-blocking.v1. CodeRabbit independently
flagged the same hole from the wire side.

It matters because the two states are otherwise indistinguishable: a fixed and an unfixed host both
accept --run-hooks and behave identically whenever the hook succeeds. The only way to tell them
apart was to fail a hook deliberately and see whether the checkout survived — i.e. to risk the exact
data loss this issue is about. Lifecycle tools keep their teardown evidence inside the checkout,
so they cannot take that risk.

worktree.archive-failure-blocking.v1 is now in RUNTIME_CAPABILITIES, advertised unconditionally
because the gate is not configurable — no build ships the constant without the behaviour. The
reporter's id is adopted verbatim (it already matches house convention, alongside
worktree.create-idempotency.v1), so their integration needs no change.

Not adopted: CodeRabbit also suggested refusing the removal when the host lacks the capability.
That would break worktree removal against every pre-gate host for every user, including the majority
with no scripts.archive hook at all — a broader regression than the bug. An old host is not newly
broken here; it has the behaviour it always had, and it is fixed when it updates. What was missing
was any way to know, which the capability supplies.

Interaction with #18563

#18563 (@junited31, fixes #18558) makes the runtime registered remote/SSH path run the archive
hook, which today it does not — that is why this PR's table lists that path as "runs no hook at all,
unchanged". The two PRs are complementary and touch four files in common
(execute-worktree-removal.ts, worktree-archive-hook.ts, orca-runtime-remove-managed-worktree.ts,
ssh-worktree-lifecycle-part-02.spec.ts).

Because that path runs no hook, this PR makes it refuse a hooks-requested removal rather than
delete with the archive step silently skipped — otherwise worktree.archive-failure-blocking.v1
would be advertising a guarantee that one path does not keep.

That refusal is temporary, and #18563 is what retires it. Once that path actually runs the hook,
gateRemovalWhereArchiveHookCannotRun should be deleted from it and
gateWorktreeRemovalOnArchiveHook called on the hook's result instead — the same gate the local and
IPC paths use, so a failing hook blocks rather than the path itself blocking. It is modelled as
outcome: 'unverifiable' precisely because nothing ran; once something runs, real
exited/unverifiable verdicts take over.

Whoever merges second should expect conflicts. removeRuntimeRegisteredRemoteWorktree already
gained the runHooks argument that change needs, threaded from removeManagedWorktree. This is
spelled out on #18563 as well, so it is a decision at review time rather than a surprise.

Rebased onto #20576 and #20617

Two findings, both from rerunning the real-repo harness after the rebase rather than from reading
the diff:

  1. The prunable-registration ordering exception above.
  2. A signalled hook reported Command failed with exit code null. — which reads as a reporting
    glitch rather than the unverifiable verdict the gate is about to give it. It now says the
    command was terminated without reporting an exit code. Introduced by fix(hooks): actually terminate a timed-out hook's process tree #20576 (the withheld
    exitCode itself was always right), and it is the exact string a user sees when this PR's gate
    blocks a removal, so it is fixed here.

Harness after the rebase and the fix: 38/38, against the built CLI and the built headless
runtime.

Also in this PR

  • src/cli/handlers/worktree-removal-warnings.ts — the two worktree rm stderr printers lifted out
    of worktree.ts, so the waived-override warning has somewhere coherent to live.
  • worktree_archive_hook_failed added to STRUCTURED_RUNTIME_PASSTHROUGH_CODES, so callers can
    branch on the code instead of pattern-matching a flattened runtime_error string.
  • worktree.archive-failure-blocking.v1 in RUNTIME_CAPABILITIES (see above).
  • readIpcErrorDetail in src/renderer/src/lib/ipc-error.ts — strips Electron's IPC wrapper
    off the delete failure string (see the reviewer note above). It sits beside the incumbent
    extractIpcErrorMessage rather than replacing it: that one stops at the first newline, which
    would drop a failed hook's output. A test pins the difference.

Review findings addressed

An adversarial review traced the ordering, the options-object refactor, the force-doesn't-waive
chain, the dedupe keys and the prefix-strip safety, and found two blockers plus a set of smaller
issues. All are fixed in this branch:

Finding Resolution
Capability advertised where the runtime SSH path runs no hook That path now refuses a hooks-requested removal instead of deleting with the archive step skipped, so the capability is true on every path.
Waived CLI output claimed nothing was deleted Separate formatArchiveHookOverride; the waived path says it deleted anyway and archived nothing.
Stale root help text, stale comment, CLI-only hint Flag added to the help usage line; hint now names both the in-app button and the CLI flag.
--allow-failed-archive-hook without --run-hooks was a silent no-op Rejected as invalid_argument.

Two were assessed and deliberately not fixed here:

  • Unreadable orca.yaml on SSH fails open. Blocking needs "absent" to be distinguishable from
    "could not read", and the SSH read crosses an RPC boundary that does not preserve ENOENT.
    Failing closed on that signal would refuse removal for every SSH repo that simply has no
    orca.yaml — a far larger regression than the gap it closes. The fail-open now logs rather
    than surfacing anything to the caller, since a user-facing warning fired on every SSH repo that
    simply has none. The capability's doc comment scopes the claim accordingly: a hook that runs and
    fails cannot delete the checkout; it is not a promise the hook was found. The provider-contract
    change that would separate the two is tracked in Archive-hook waiver missing from the Space panel; converge the IPC error-message helpers #20196.
  • The waiver is not reachable from every removal surface (workspace-cleanup-removal.ts,
    ssh-host-remove-workspaces.ts, mobile, and older renderers against a new host). Every one of
    those still refuses — data is protected — they just lack the one-click waiver and fall back to
    the CLI flag. A convenience gap rather than a correctness one; tracked in Archive-hook waiver missing from the Space panel; converge the IPC error-message helpers #20196.

A disclosure

"Every path" means every path that runs a hook. The IPC removal path still routes purely on
repo.connectionId, while its host id comes from getRepoExecutionHostId, which prefers
repo.executionHostId. A row naming its owner only as executionHostId: 'ssh:<target>' with a null
connectionId would therefore be listed, hook-read and removed locally — the same mis-route the
runtime path was just fixed for, across every operation rather than just hooks. It is pre-existing
and well outside this change, and I have not touched it; stating it because a blanket reading of the
table above would otherwise over-claim. Tracked in #20196.

Do not "fix" that by passing a connectionId override to the IPC hook reader. It looks like the
same one-line change that fixed the runtime path, and it is not. That path resolves its provider,
git options, worktree listing and dispatch from repo.connectionId alone; handing the hook reader a
different owner would read one host's orca.yaml while running the other host's git — strictly
worse than today's consistency. The runtime path is the one that legitimately carries a route owner
separate from the row, which is why it is the one that passes it. There is a comment at the IPC call
site saying so.

Two more things a reviewer should know

The client now outlasts the hook. worktree.rm was dispatched with a 60s client budget while an
archive hook may run for 120s. A hook that took 90s and succeeded therefore timed the client out
at 60s and reported failure — while the host carried on and deleted the checkout. The user was
told the delete failed and their work was gone.
A 90s failure was equally bad: a generic client
timeout, unrecognisable as an archive refusal, so no Delete Anyway. The budget is now derived from
the hook's, and only when a hook can run: skipArchive ? 60s : ARCHIVE_HOOK_TIMEOUT_MS + 60s.
A consequence worth stating: a retry issued while a first archive hook is still running on the host
can overlap it, so hooks should stay idempotent.

"Delete Anyway" can become "skip the hook", and that is deliberate. The retry re-derives
skipArchive through ensureHooksConfirmed, which fails closed to 'skip' if the script cannot be
inspected or the trust modal is dismissed. The hook then does not run and the waiver goes unused —
the delete still proceeds, which is what the user asked for, but nothing was archived and nothing
was attempted
. Forcing the hook to run instead would mean executing a script the trust gate just
declined, turning a waiver about archive failure into consent to run unverified code. The trust
gate wins on purpose.

Follow-ups

Filed as #20196: the status-bar Space panel does not yet offer the waiver, three components still
hand-roll the IPC-wrapper regex, and the refusal toast reproduces the hook's full output including
the echoed script body.

Checks

pnpm tc · oxlint src · oxfmt --check (changed files) · check:max-lines-ratchet ·
check:ts-nocheck-ratchet · verify:rpc-params-catalog · check:code-quality:changed (0 new
findings) — all clean. All 21 static-analysis steps from pr.yml were run locally, including the
orcad terminal smoke and the Zustand selector fan-out budget.

Green where run. CI runs the shards, typecheck, static analysis, package and package (windows).
e2e, Git compatibility, cross-version-wire, shell contracts, managed-hooks-on-Node-18 and the
Linux/Windows native jobs are skipped for this change set, so they are not evidence either way.
No real SSH host, no WSL, and no packaged desktop build were exercised. Scoped suites: orca-runtime.test.ts (1268), src/main/ipc/worktrees,
src/shared/worktree, src/main/hooks (678), src/cli/index.test.ts, the two worktree-rm-* RPC
tests, and runtime-worktree-selection.test.ts. Plus a full sweep of src/renderer/src,
src/main/ipc/worktrees, src/shared/worktree, orca-runtime.test.ts and src/cli — 3903 files,
34262 tests, all passing
— and the four localization gates after regenerating the catalogs for the
new Delete Anyway string.

@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

  • Blocking archive-hook gate — gateWorktreeRemovalOnArchiveHook throws on a failed archive hook before any PTY stop or delete, wired into both the IPC (execute-worktree-removal.ts) and runtime-local (runtime-registered-local-worktree-removal.ts) orchestrators ahead of every preflight.
  • unverifiable is not exited — runHook and runRemoteArchiveHook now withhold exitCode unless the host actually reported one, so a spawn error, timeout, or lost SSH channel blocks removal instead of reading as success.
  • Explicit waiver, not --force — allowFailedArchiveHook travels on its own field across CLI/RPC/IPC/preload, is recorded back on result.archiveHookOverride, and is deliberately decoupled from force and skipArchive.
  • Dedupe-key extension — both in-flight options keys (getWorktreeRemovalOptionsKey, getRuntimeWorktreeRemovalOptionsKey) carry the waiver so a waived retry can't coalesce onto an in-flight refusal.
  • removeManagedWorktree named-options refactor — the four interchangeable waivers now travel as a named object instead of positional booleans, matching the IPC coordinator key shape and letting the compiler catch transpositions.

ℹ️ CLI→runtime SSH removal still skips the archive hook

The IPC path gates remote/SSH removal via runRemoteArchiveHook, but the runtime's SSH branch (removeRuntimeRegisteredRemoteWorktree) runs no hook at all, so orca worktree rm --run-hooks on a remote worktree is a silent no-op — the hook neither runs nor blocks there. This is pre-existing and marked "unchanged" in the PR, but since --run-hooks is advertised globally on worktree rm, it's worth confirming whether that path is intended to stay hook-less or is just out of scope for now.

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

@coderabbitai

coderabbitai Bot commented Sep 11, 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

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: c5a8e5d9-13d4-40c3-9f7e-98aa961448b5

📥 Commits

Reviewing files that changed from the base of the PR and between 449992a and a1a0150.

📒 Files selected for processing (4)
  • src/renderer/src/components/sidebar/delete-worktree-flow.test.ts
  • src/renderer/src/components/sidebar/run-worktree-delete-with-toast.ts
  • src/shared/protocol-version.ts
  • src/shared/worktree/archive-failure-blocking-capability.test.ts

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


📝 Walkthrough

Walkthrough

The worktree removal flow now blocks deletion when an archive hook fails or cannot be verified. An explicit allowFailedArchiveHook waiver permits removal and records override metadata. The waiver propagates through CLI, RPC, runtime, preload, and renderer paths. The desktop UI offers a “Delete Anyway” retry. Hook exit metadata, structured errors, warning output, IPC error formatting, concurrency keys, runtime capability advertisement, and regression tests were updated.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🟡 Moderate · up to a1a01

Some removal paths may still bypass the archive-hook refusal contract or mutate registration state before the required hook check. Resolve these paths before merge so failed archive hooks reliably preserve worktree lifecycle state.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 30 functions across 49 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 PR satisfies the coding requirements in [#19334]. The archive hook runs before registration refresh, preflight checks, PTY stop, and worktree deletion in both the runtime and IPC removal paths. A …
Out of Scope Changes check ✅ Passed The changes remain within [#19334]. CLI, RPC, IPC, runtime, and desktop changes propagate the archive-hook precondition and provide an informed explicit override. Structured errors, warning handlers, …
Title check ✅ Passed The title clearly and concisely states the primary change: archive-hook failures now block worktree removal.
Description check ✅ Passed The description is complete and directly addresses the template. It explains the change and rationale, links issue #19334, includes visual proof, documents testing and limitations, and covers compatib…
✨ 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.

Caution

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

⚠️ Outside diff range comments (2)
src/main/runtime/orca-runtime-remove-managed-worktree.ts (1)

202-212: 🗄️ Data Integrity & Integration | 🔴 Critical | 🏗️ Heavy lift

Propagate archive-hook gating to registered SSH removals.

This branch calls removeRuntimeRegisteredRemoteWorktree without runHooks or allowFailedArchiveHook. No archive-hook gate runs earlier in this method.

A runtime or RPC request with runHooks: true can therefore delete a registered SSH worktree without evaluating its archive hook. The runtime also cannot record an explicit failed-hook waiver.

Pass both options to the remote removal path. Run the remote archive-hook gate before PTY shutdown, registration changes, or deletion.

src/main/ipc/worktrees/removal/execute-worktree-removal.ts (1)

88-126: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Run the archive-hook gate before this stale-registration shortcut.

When force is true on Windows or WSL and isAlreadyRemovedWorktreePath returns true, this branch removes the Git registration and metadata before lines 129-159 evaluate the archive hook. A configured archive hook can therefore fail or be unverifiable without returning worktree_archive_hook_failed, and the user cannot fix the hook and retry because the registration is already removed.

Evaluate the archive-hook precondition before this branch. Preserve this shortcut only after a successful hook or an explicit allowFailedArchiveHook waiver.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 84b728a3-e604-413d-aea9-8f29d0105314

📥 Commits

Reviewing files that changed from the base of the PR and between 7294915 and 8dded47.

📒 Files selected for processing (32)
  • src/cli/handlers/worktree-removal-warnings.ts
  • src/cli/handlers/worktree.ts
  • src/cli/index.test.ts
  • src/cli/specs/core.ts
  • src/main/hooks.ts
  • src/main/ipc/worktrees-remove-archive-hooks.test.ts
  • src/main/ipc/worktrees/ipc-context-schemas.ts
  • src/main/ipc/worktrees/removal/execute-worktree-removal.ts
  • src/main/ipc/worktrees/removal/worktree-archive-hook.ts
  • src/main/ipc/worktrees/removal/worktree-removal-coordinator.ts
  • src/main/runtime/orca-runtime-remove-managed-worktree.ts
  • src/main/runtime/orca-runtime-tests/ssh-worktree-lifecycle-part-02.spec.ts
  • src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts
  • src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts
  • src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts
  • src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation.spec.ts
  • src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts
  • src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/rpc/errors.ts
  • src/main/runtime/rpc/methods/worktree-rm-host-qualification.test.ts
  • src/main/runtime/rpc/methods/worktree-rm-pty-waiver.test.ts
  • src/main/runtime/rpc/methods/worktree.ts
  • src/main/runtime/runtime-registered-local-worktree-removal.ts
  • src/main/runtime/runtime-worktree-selection.test.ts
  • src/main/runtime/runtime-worktree-selection.ts
  • src/main/worktree-archive-hook-gate.ts
  • src/preload/api/worktree-api.ts
  • src/shared/cli-argument-boundary.ts
  • src/shared/rpc-contract/worktree-params.ts
  • src/shared/worktree/archive-hook-removal-gate.ts
  • src/shared/worktree/create-types.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 0 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.

Important

The new IPC-wrapper stripping changes the renderer delete-error string, but six existing store tests still assert the pre-strip value — the renderer suite is red on this commit.

Reviewed changes

  • Added readableIpcErrorMessage (src/renderer/src/lib/ipc-error-message.ts) with unit tests that strip Electron's Error invoking remote method '<channel>': wrapper and one \w*Error: class prefix, while leaving unwrapped and local messages (e.g. a renderer-local TypeError:) untouched.
  • Routed the renderer worktree-delete failure through it in remove-worktree.ts, so the refusal toast and deleteStateByWorktreeId[*].error now carry the unwrapped message.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using openrouter/deepseek/deepseek-v4.1-flash (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.

Important

The new desktop Delete Anyway path completes a removal but skips the late-completion notification that Force Delete uses, so batch / lineage / Space deletes don't record the waived deletion.

Reviewed changes

  • Desktop waiver button — delete-worktree-failure-toast.tsx gains canWaiveArchiveHook and renders a persistent Delete Anyway button; run-worktree-delete-with-toast.ts wires onDeleteAnyway to re-run removeWorktree with { allowFailedArchiveHook: true }.
  • Renderer waiver plumbing — remove-worktree.ts sets canWaiveArchiveHook from isArchiveHookRemovalError on the unwrapped message; the option travels through worktree-delete-state-types.ts, worktree-removal-options.ts, and dispatch-worktree-removal.ts (sent unconditionally over IPC, only-when-set across the runtime version boundary).
  • Prior review resolved — the six store-worktree-removal-cascade.test.ts cases now assert the unwrapped strings; the four affected suites pass (56 tests), tc:web and oxlint are clean.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using openrouter/deepseek/deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@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: Advanced

Run ID: 9ce909c4-f915-4bd1-96d2-46ae4409851b

📥 Commits

Reviewing files that changed from the base of the PR and between 85d540a and 89e4c59.

📒 Files selected for processing (12)
  • src/renderer/src/components/settings/DevToolsPane.tsx
  • src/renderer/src/components/sidebar/delete-worktree-failure-toast.test.tsx
  • src/renderer/src/components/sidebar/delete-worktree-failure-toast.tsx
  • src/renderer/src/components/sidebar/run-worktree-delete-with-toast.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/store/slices/store-worktree-removal-cascade.test.ts
  • src/renderer/src/store/slices/worktree-delete-state-types.ts
  • src/renderer/src/store/slices/worktree-removal-options.ts
  • src/renderer/src/store/slices/worktrees-remote-runtime-removal.test.ts
  • src/renderer/src/store/slices/worktrees/teardown/dispatch-worktree-removal.ts
  • src/renderer/src/store/slices/worktrees/teardown/remove-worktree.ts
  • src/shared/worktree/archive-hook-removal-gate.ts

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

Comment on lines +54 to +56
// Why only when set, unlike the IPC branch: this crosses a version boundary, and a host
// that predates the gate drops unknown params silently. Send it when it means something.
...(options?.allowFailedArchiveHook === true ? { allowFailedArchiveHook: true } : {}),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -eu
file='src/renderer/src/store/slices/worktrees/teardown/dispatch-worktree-removal.ts'
printf '%s\n' '--- cited file ---'
cat -n "$file"
printf '%s\n' '--- directly bound symbols and callers ---'
rg -n -S --glob '!node_modules' \
  'allowFailedArchiveHook|dispatchWorktreeRemoval|runHooks|archive hook|archiveHook|worktree.*remov' \
  src

Repository: stablyai/orca

Length of output: 50372


🤖 get_repo_knowledge executed:

get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings

Length of output: 31942


🏁 Script executed:

printf '%s\n' 'requesting bounded repository inspection'; cat -n src/renderer/src/store/slices/worktrees/teardown/dispatch-worktree-removal.ts; rg -n -S 'allowFailedArchiveHook|dispatchWorktreeRemoval|runHooks|archiveHook|runtime.*version|version.*runtime|capabilit' src/renderer src/main src/shared 2>/dev/null | head -300

Repository: stablyai/orca

Length of output: 39786


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- exact worktree.rm and waiver bindings ---'
rg -n -S --glob '!src/cli/bundled-skill-guides.ts' \
  'worktree\.rm|allowFailedArchiveHook|archiveHook|archive hook|runHooks' src shared
printf '%s\n' '--- runtime RPC client capability contract ---'
cat -n src/renderer/src/runtime/runtime-rpc-client.ts | sed -n '1,360p'
printf '%s\n' '--- likely removal implementations ---'
rg -l -S --glob '!src/cli/bundled-skill-guides.ts' \
  'worktree\.rm|allowFailedArchiveHook|runHooks' src shared | while IFS= read -r f; do
  printf '\n--- %s ---\n' "$f"
  rg -n -C 12 -S 'worktree\.rm|allowFailedArchiveHook|runHooks' "$f"
done

Repository: stablyai/orca

Length of output: 31976


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- RPC worktree removal handler ---'
cat -n src/main/runtime/rpc/methods/worktree.ts | sed -n '190,255p'
printf '%s\n' '--- runtime removal gate ---'
cat -n src/main/runtime/runtime-registered-local-worktree-removal.ts | sed -n '35,100p'
printf '%s\n' '--- runtime RPC parameter contract ---'
cat -n src/shared/rpc-contract/worktree-params.ts | sed -n '145,190p'
printf '%s\n' '--- runtime status/capability helpers ---'
cat -n src/renderer/src/runtime/runtime-rpc-client.ts | sed -n '230,345p'
printf '%s\n' '--- protocol capability declarations around runtime status ---'
cat -n src/shared/protocol-version.ts | sed -n '1,230p'

Repository: stablyai/orca

Length of output: 30307


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- generic runtime RPC dispatch ---'
rg -n -C 18 -S 'export async function callRuntimeRpc|function callRuntimeRpc|callRuntimeRpc<' src/renderer/src/runtime/runtime-rpc-client.ts
printf '%s\n' '--- archive-hook pre-gate behavior ---'
cat -n src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts | sed -n '1,80p'
printf '%s\n' '--- runtime capability type and status compatibility ---'
rg -n -C 8 -S 'type RuntimeCapability|export type RuntimeCapability|assertRuntimeStatusCompatible|RUNTIME_PROTOCOL_VERSION' src/renderer/src/runtime src/shared | head -220

Repository: stablyai/orca

Length of output: 24472


Gate worktree.rm before running archive hooks on older runtimes.

When skipArchive is false, dispatchWorktreeRemoval sends runHooks: true but omits allowFailedArchiveHook for an ordinary delete. A pre-gate runtime can then use its old behavior and remove the worktree after a non-zero archive hook. The protocol compatibility rules do not reject this because optional fields do not require a version bump.

Require an archive-hook capability before this worktree.rm call and reject the removal when the runtime lacks it, or require a runtime upgrade. Add an integration test with a pre-gate runtime and a failing archive hook.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@/tmp/agh-reply-cr.md

@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

  • Waived delete now reports completion — onDeleteAnyway invokes options.onForceDeleted?.(target) after a successful allowFailedArchiveHook retry, so batch, lineage delete-all, and Space callers run their onDeleted bookkeeping. This resolves the prior review's ⚠️.
  • Flow-level coverage — a new delete-worktree-flow.test.ts case asserts the retry carries { allowFailedArchiveHook: true } with force left unchanged and that onDeleted fires on success (verified locally: 24 tests pass).
  • Archive-failure-blocking capability — WORKTREE_ARCHIVE_FAILURE_BLOCKING_RUNTIME_CAPABILITY (worktree.archive-failure-blocking.v1) joins RUNTIME_CAPABILITIES, with a test pinning the id and list membership, so integrations can distinguish a host that blocks on a failed hook from one that merely accepts --run-hooks.

Pullfrog  | View workflow run | Using openrouter/deepseek/deepseek-v4.1-flash (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

  • Exit-observation coverage — src/main/hooks-archive-exit-observation.test.ts pins how runHook reports an archive hook's exit: a numeric code becomes exitCode, while a signal/timeout (code: null) and a spawn failure (code: 'ENOENT', a string) leave it absent so the gate classifies them unverifiable. Test-only; verified locally (5 tests pass) and the assertion fails under a looser != null guard, so it is real coverage rather than a tautology.

Pullfrog  | View workflow run | Using openrouter/deepseek/deepseek-v4.1-flash (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.

Important

The new runtime SSH archive gate reads the runtime's local filesystem for a hook that lives on the SSH host, so it cannot refuse the removal it was added to refuse, and it can false-refuse on a coincidental local orca.yaml.

Reviewed changes

Two commits landed since the prior pullfrog review (1bea256):

  • Hook deadline owns the verdict — hook-script-deadline.ts replaces Node's exec({ timeout }), settles at the deadline, escalates SIGTERM→SIGKILL across the process group, and withholds exitCode on timeout, so a SIGTERM-trapping hook can no longer report a false pass.
  • Runtime SSH removal now gates — gateRemovalWhereArchiveHookCannotRun refuses a hooks-requested removal, and an unreadable orca.yaml on the IPC path warns instead of failing open.
  • Waiver UX and guard — --allow-failed-archive-hook without --run-hooks is rejected, the CLI prints a dedicated waived-delete message (formatArchiveHookOverride), and the refusal hint now names the in-app button too.
  • Real-repo repro committed — config/scripts/archive-hook-removal-repro.mjs drives the built CLI against the built headless runtime over real git worktrees.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using openrouter/deepseek/deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

Comment thread src/main/worktree-archive-hook-gate.ts Resolved
@nwparker
nwparker force-pushed the fix/archive-hook-gate branch from 2ca6170 to 2b28146 Compare September 13, 2026 05:03

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

Important

The runtime SSH gate now sources hooks from getArchiveHooksForRemoval, but that reader still keys on repo.connectionId — null for executionHostId: 'ssh:<target>'-only rows — so a runHooks: true removal on such a row silently skips the remote hook instead of refusing.

Reviewed changes

  • Runtime SSH gate reads the execution host — gateRemovalWhereArchiveHookCannotRun is now async and sources hooks via getArchiveHooksForRemoval (SSH-aware) instead of the local getEffectiveHooks, with the doc comment explaining why the local read was wrong.
  • Gate test rewired to the host-aware reader — worktree-archive-hook-cannot-run.test.ts now mocks getArchiveHooksForRemoval and pins that the gate calls it rather than getEffectiveHooks.
  • Repro content assertion restored — archive-hook-removal-repro.mjs scenario 1 now checks PRECIOUS.txt's body, not just its existence; the previous (A && B) || A reduced to A and never ran the assertion.

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

Comment thread src/main/worktree-archive-hook-gate.ts Resolved

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

Reviewed changes

Changes since the prior pullfrog review (faa7eed21b) fold the hook deadline back into hooks.ts behind a single classifier and reorganize the surrounding tests; removal behavior is unchanged.

  • One hook-result classifier — src/main/hook-script-deadline.ts is deleted and its deadline/termination logic moves into hooks.ts; classifyHookProcessResult still decides timedOut before code, so a timeout withholds exitCode and a SIGTERM-trapping hook cannot report a pass.
  • Timeout coverage moved to a real shell — the new hook-archive-timeout-observation.test.ts drives runHook with a short deadline against real shells and signals, while hooks-archive-exit-observation.test.ts keeps the mocked exit-code classification.
  • RPC waiver tests consolidated — the PTY and archive-hook waiver cases merge into one table in worktree-rm-pty-waiver.test.ts, and asArchiveHookRefusal centralizes narrowing the typed refusal.
  • Toast retry paths deduplicated — run-worktree-delete-with-toast.ts routes Force Delete and Delete Anyway through one retryFromToast helper, preserving each button's waiver and failure copy.
  • Renderer classification table — store-worktree-removal-cascade.test.ts tables the wrapped/unwrapped cases.
  • Allowlist cleanup — src/main/hook-script-deadline.ts is removed from the child-process allowlists; src/main/hooks.ts keeps its existing entry.

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

Comment thread src/main/hooks.ts Resolved

@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

Changes since the prior pullfrog review (3ee6bc0a) resolve that review's outstanding findings; no new issues.

  • Archive hook resolves against the route's owner — getArchiveHooksForRemoval gained an optional connectionId override (owner = connectionId ?? repo.connectionId), and gateRemovalWhereArchiveHookCannotRun now takes the resolved removal route's connectionId. An executionHostId: 'ssh:*'-only row therefore reads its hook on the execution host rather than this machine's disk, so a runHooks: true runtime SSH removal either sees the hook and refuses or reads no hook on the right host.
  • Timeout deadline arm is synchronous-safe — runHook only arms its deadline when exec has not already settled, closing the window where the mocked synchronous callback left a timer pointed at a finished process group.
  • Coverage added at both seams — worktree-archive-hook.test.ts pins the reader's owner resolution (execution host over the row, then the row, then local), and worktree-archive-hook-cannot-run.test.ts pins that the gate forwards the route connection.

Pullfrog  | View workflow run | Using DeepSeek Flash (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 critical issues — one termination-path trade-off inline.

Reviewed changes

Changes since the prior pullfrog review (6359737) are the self-audit of the hook termination path:

  • Liveness guard on hook termination — terminateHookTree now takes exitCode/signalCode on its child type and returns without signalling once the child has exited, so the 2s SIGKILL escalation cannot land on a process group whose pid the OS may have recycled.
  • Real-shell regression test — hook-archive-termination-safety.test.ts drives runHook against a real shell and asserts no negative-pid SIGKILL is sent to a hook that stopped on its own; it lives in its own file so a sibling's pending escalation cannot pollute the signal traffic it measures.
  • IPC override rationale documented — a comment on execute-worktree-removal.ts:129 records why that path deliberately passes no connectionId override to getArchiveHooksForRemoval.

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

Comment thread src/main/hooks.ts Resolved

@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 — the delta is clean; one description-level note below.

Reviewed changes

Changes since the prior pullfrog review (6cebc00) give the runtime SSH refusal an explicit waiver and simplify the hook reader; removal behavior is otherwise unchanged.

  • The SSH refusal is now waivable and recorded — gateRemovalWhereArchiveHookCannotRun takes allowFailedArchiveHook, returns { warning?, override? }, and produces the same archiveHookOverride shape the local/IPC paths return; removeRuntimeRegisteredRemoteWorktree accepts and forwards the waiver and spreads archiveHookOverride into its result. The one path that previously threw with no reachable exit now honours --allow-failed-archive-hook (printed by printHookWarning) and the desktop Delete Anyway (whose retry re-derives runHooks via ensureHooksConfirmed, so the gate sees runHooks: true).
  • Hook reader simplified to OrcaHooks | null — ArchiveHooksForRemoval/hookConfigUnreadable and the IPC warning it fed are removed; a failed SSH read answers "no hook" uniformly. The warning fired for every SSH repo without orca.yaml (the relay rewrites ENOENT to -32000, so "missing" was never distinguishable), and the limitation is now pinned by a test rather than surfaced as noise.
  • Tests — the cannot-run gate suite adds the waive-and-record case and passes the newly required argument; the reader suite pins the "no hook" answer for an unreadable/unreachable host.

ℹ️ PR description still says an unreadable orca.yaml "emits a warning"

The body's "Unreadable orca.yaml on SSH fails open" disclosure was accurate before this commit, but 3710a5d removes that warning — hookConfigUnreadable is gone and the reader now answers "no hook" silently. A reader of the description is left with the pre-change behavior, which now contradicts both the code and the test that pins the limitation.

Technical details
# Update the unreadable-orca.yaml disclosure in the PR body

## Affected sites
- PR description, "Unreadable `orca.yaml` on SSH fails open": "...It now emits a warning, and the provider-contract change it really needs is tracked in #20196."

## Required outcome
- The sentence should say the failure is answered as "no hook" (silently) after `3710a5d`, keeping the #20196 provider-contract follow-up.

## Notes
- Code is unaffected; this is a description-accuracy edit only. The commit message and the new test comment already state the new behavior.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (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

Changes since the prior pullfrog review (3710a5d) fix the termination-path trade-off that review flagged.

  • Group probe replaces the child-liveness guard — terminateHookTree now tests the process group with process.kill(-pid, 0) and only returns on ESRCH, so a hook whose shell leader exits on the deadline SIGTERM still gets its surviving descendants SIGKILLed; an empty group receives neither signal. The comment records the residual pid-recycling window.
  • Tests pin both branches against interception — hook-archive-termination-safety.test.ts is rewritten to assert the SIGTERM→SIGKILL group escalation when members survive, that an empty group gets nothing, and that terminateHookTree still signals a group when the child's exitCode is already set (the regression the child-liveness guard caused).

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

@nwparker
nwparker force-pushed the fix/archive-hook-gate branch from 7719c73 to 6cce5bc Compare September 14, 2026 05:34
@nwparker
nwparker changed the base branch from main to fix/hook-process-termination September 14, 2026 05:34
nwparker added a commit that referenced this pull request Sep 14, 2026
… process tree (#20559)

## In plain terms

Orca lets a project define scripts that run at certain moments — one when a workspace is set up,
one just before it is deleted. Those scripts get a time limit. When the limit ran out, Orca asked
the script to stop and then believed whatever the script said on its way out — so a script written
to shut down politely could be cut off halfway through its work and still report that it had
finished. Anything relying on that answer was relying on a guess.

Now the verdict comes from the clock, not from the script: if it ran out of time, that is what is
reported, whatever exit code it managed on the way out. Orca also stops the script's *children*
rather than just the script, so a background process it started can no longer outlive it.

Split out of #20153 so the gate that consumes this answer is reviewed separately. `Refs #19334`
rather than `Fixes`, because it does not close the issue on its own.

## The bug

`exec({ timeout })` sends SIGTERM and then reports what the child did. A hook that traps SIGTERM
and exits 0 therefore comes back with a **null error** — success — despite having been cut off.

```js
exec("trap 'exit 0' TERM; sleep 5", { timeout: 200 }, (err) => …)  // err === null
```

That is not an `exited` vs `unverifiable` nicety: it is a failed hook reported as a passing one.
Realistic triggers are ordinary — a Node wrapper with a graceful `process.on('SIGTERM')`, an rsync
wrapper that cleans up on signal.

## What changed

**`runHook` owns the deadline.** The verdict comes from running out of time rather than from the
corpse's exit code, and it is settled *at* the deadline rather than whenever the child gets around
to dying — a hook that traps the signal and keeps running must not hold its caller open.

**A timeout withholds the exit code.** So does a spawn failure, where `exec` reports a *string*
code (`ENOENT`); the `typeof code === 'number'` guard is what keeps a hook that never ran out of the
"exited" verdict. Callers that distinguish "exited N" from "outcome never observed" can now trust
that distinction:

| failure mode | `error.code` | signal | verdict |
| --- | --- | --- | --- |
| non-zero exit | `23` | — | `exited 23` |
| command not found | `127` | — | `exited 127` |
| killed | `null` | SIGKILL | outcome not observed |
| deadline expired | *(the deadline, not the exit)* | SIGTERM→SIGKILL | outcome not observed |
| deadline expired, hook traps SIGTERM and exits 0 | `0` | — | outcome not observed |
| spawn failure | `"ENOENT"` *(string)* | — | outcome not observed |

**Termination reaches the process group.** The script is a shell and the work is its children, so
signalling only the shell leaves a `sleep` or an `rsync` alive holding the pipes open. SIGTERM
first, then SIGKILL after a grace.

**One `classifyHookProcessResult`** now serves the native and WSL branches, which had been mapping a
finished process to a hook verdict by hand, identically. That duplication predates this change.

## Terminating the tree, and a test that could not fail

The escalation went wrong once in review, in a way worth recording.

A first attempt skipped the SIGKILL when the *direct child* had already exited — a dead child needs
no signal. That is correct about the child and wrong about the group: a hook that backgrounds a
server typically loses its shell leader to the first SIGTERM while the server keeps running, so the
skip fired in exactly the case the escalation exists for. The escalation now probes the **group**
with signal 0: `ESRCH` means nothing is left to kill, anything else gets the signal.

**The residual trade-off, stated rather than implied.** Signalling by negative pid names whatever
group owns that pid *now*. Once the leader is reaped its pid can be recycled, and a probe cannot
distinguish a surviving descendant from a stranger that inherited the number. Killing a runaway hook
is both the likelier event and the one the deadline promises, so the group is signalled whenever it
answers; the remaining window is pid wraparound inside the grace.

**A test that cannot fail is worse than no test.** The first regression test drove `runHook` with
`process.kill` intercepted — and passed against *both* the broken and the fixed version, because
with signals intercepted nothing dies, so the child never reached the exited state the bad guard
keyed on. It was false assurance, not coverage. `terminateHookTree` is therefore exported and the
regression pinned directly against it: it fails on the old version
(`expected [] to deeply equal [[-4242, 'SIGKILL']]`) and passes on this one.

## Behaviour change for `setup` hooks

Both hook kinds share `runHook`, so this is not confined to archive hooks. **A setup hook that
backgrounds a long-running server now has that server SIGTERM'd — then SIGKILL'd — with the rest of
its process group when the deadline expires, where previously it was orphaned and survived.**
Arguably the better behaviour, since an orphaned server is a leak, but it is a real change and
should be a decision rather than a discovery.

## Evidence

Against real shells and real signals, because this bug is invisible to a mock
(`hook-archive-timeout-observation.test.ts`, through `runHook` itself rather than an extracted
helper):

```
✓ fails a hook that traps SIGTERM and exits zero, despite its zero exit
✓ settles at the deadline even when the hook refuses to die
✓ passes a hook that finishes inside its deadline
✓ reports an observed non-zero exit as the exit it is
```

Plus `hooks-archive-exit-observation.test.ts` for the wiring — including the string-`ENOENT` case —
and `hook-archive-termination-safety.test.ts` for the escalation branching.

## Checks

`pnpm tc` · `oxlint src` · `oxfmt --check` · 113 tests across `src/main/hooks*`. The classification
table above is measured against real `exec`, not reasoned.
@nwparker
nwparker force-pushed the fix/archive-hook-gate branch from 6cce5bc to 9eb04dd Compare September 14, 2026 05:37
@nwparker
nwparker changed the base branch from fix/hook-process-termination to main September 14, 2026 05:37
@pullfrog

pullfrog Bot commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

the model provider had a temporary upstream failure.

The provider refused or dropped the request mid-run — nothing in your repo or your credentials is at fault. Re-trigger Pullfrog; if it keeps happening, check the provider's status page.

provider error: {"code":502,"message":"Upstream error from Together: Stream error: h2 protocol error: error reading a body from connection","metadata":{"error_type":"provider_unavailable"}}

Pullfrog  | Rerun failed job ➔ | View workflow run | via Pullfrog | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

ghost 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 constant-coupling nit inline.

Reviewed changes

Changes since the prior pullfrog review (7719c73): the branch was rebased onto #20559 (the hook-deadline/termination work now lives there, so src/main/hooks.ts is out of this PR's diff) and its history squashed to two commits. 465034b is the only delta over 9eb04dd:

  • Retry failures re-open the actionable toast — run-worktree-delete-with-toast.ts factors the failure toast into showFailureToast; a retry that fails for a different reason (e.g. the dirty preflight after waiving the hook) now re-renders the full toast with its buttons rather than a bare toast.error with no exit.
  • Client budget outlasts the hook — ARCHIVE_HOOK_TIMEOUT_MS moves to the shared gate and dispatch-worktree-removal.ts derives the runtime RPC timeout (skipArchive ? 60s : ARCHIVE_HOOK_TIMEOUT_MS + 60s), so a slow-but-successful hook no longer times the client out while the host deletes anyway.
  • Reader signals instead of failing silently — getArchiveHooksForRemoval now logs when no SSH filesystem provider exists and when the orca.yaml read fails, rather than answering "no hook" with no signal.
  • Coverage tightened — the SSH-owner reader test asserts the returned script is the remote one (not just that the lookup key was passed), and runRemoteArchiveHook returns the shared ArchiveHookRunResult.

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

* running, and the host then completes the delete anyway — telling the user the opposite of what
* happened to their checkout (#19334).
*/
export const ARCHIVE_HOOK_TIMEOUT_MS = 120_000

ghost Sep 14, 2026

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.

ARCHIVE_HOOK_TIMEOUT_MS is documented as the archive hook's single deadline, but the two local orchestrators (execute-worktree-removal.ts:150, runtime-registered-local-worktree-removal.ts:71) call runHook with no timeout, so their hooks are bounded by HOOK_TIMEOUT in src/main/hooks.ts instead. The new renderer budget at dispatch-worktree-removal.ts:66 is premised on outlasting whichever deadline the host actually uses, so the two constants have to move together: raise HOOK_TIMEOUT past 120s on its own and the client gives up first again, which is the bug this commit fixed.

Technical details
# The shared archive-hook deadline is not actually shared with the local host path

## Affected sites
- `src/shared/worktree/archive-hook-removal-gate.ts:11` — `ARCHIVE_HOOK_TIMEOUT_MS = 120_000`, doc'd as the deadline a waiting client must outlast.
- `src/main/hooks.ts:19` — `HOOK_TIMEOUT = 120_000`, the default `runHook` timeout actually applied on the local/IPC and runtime-local paths (`execute-worktree-removal.ts:150`, `runtime-registered-local-worktree-removal.ts:71` pass no override).
- `src/renderer/src/store/slices/worktrees/teardown/dispatch-worktree-removal.ts:66` — `timeoutMs = skipArchive ? 60_000 : ARCHIVE_HOOK_TIMEOUT_MS + 60_000`; only the SSH runner (`worktree-archive-hook.ts:84`) consumes `ARCHIVE_HOOK_TIMEOUT_MS`.

## Required outcome
- The deadline the client budgets against and the deadline the host enforces must be the same value by construction (one derived from the other, or the archive `runHook` calls pass `ARCHIVE_HOOK_TIMEOUT_MS`), so editing either cannot silently desynchronise them.

## Open questions for the human
- If the archive deadline is deliberately allowed to differ from the general hook deadline, the constant's doc should say so instead of claiming it is shared.

@nwparker
nwparker force-pushed the fix/archive-hook-gate branch from 465034b to 47d3288 Compare September 14, 2026 21:59

ghost 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 in the delta — one reporting fix, one explanatory comment, and a new test.

Reviewed changes

Changes since the prior pullfrog review (465034b):

  • A signalled hook exit is named as one — classifyHookProcessResult now reports code === null as "Command was terminated without reporting an exit code." rather than "exit code null", so the string a user sees when the gate blocks matches the unverifiable verdict the gate assigns. A new case in hooks-archive-exit-observation.test.ts pins it, and the typeof code === 'number' guard still withholds exitCode.
  • The prunable-registration ordering exception is documented — the isPrunableGitFileWorktree / already-removed shortcut that runs ahead of the archive gate now carries a comment recording why (no checkout behind the registration, so nothing to archive and no cwd for the hook). Documentation only; the branch itself is base behavior from #20617.
  • Base-interaction import rename — removeStaleLocalWorktreeRegistrationAfterFilesystemRemoval → removeStaleLocalWorktreeRegistration, mechanical from the rebase onto main.

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

@nwparker
nwparker force-pushed the fix/archive-hook-gate branch from 47d3288 to c2edf50 Compare September 15, 2026 00:37

ghost 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

Changes since the prior pullfrog review (47d3288) are the rebase fold-in, not new gate behavior:

  • ipc-error.ts class-strip moved into the shared unwrapper — unwrapIpcErrorMessage (independently landed on main) now owns the wrapped-detection and ERROR_CLASS_PREFIX strip; readIpcErrorDetail, readIpcErrorMessage, and extractIpcErrorMessage behave exactly as they did at 47d3288, and main's new compactIpcErrorMessage inherits the same strip. Four new typed main-process errors cases pin the wrapped / plain / errno boundaries.
  • Delete-cascade cases consolidated — the three wrapped-message cases (dirty preflight, missing-registration, SSH provider) fold into one it.each table that threads the unwrapped displayed string while keeping each case's force-delete classification.

Verified locally: pnpm test src/renderer/src/lib/ipc-error.test.ts src/renderer/src/store/slices/store-worktree-removal-cascade.test.ts — 41 tests pass.

The prior review's open thread at archive-hook-removal-gate.ts:11 (the archive deadline constant vs HOOK_TIMEOUT) is untouched by this delta, so it stays open and this review is not an approval.

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

@nwparker
nwparker force-pushed the fix/archive-hook-gate branch 2 times, most recently from e47efd1 to 6249d7b Compare September 15, 2026 04:47
Neil added 3 commits September 15, 2026 01:10
A repo's orca.yaml archive hook is the user's last chance to save work off a
checkout Orca is about to delete. A failed hook was logged as advisory and
stepped over, so the removal went ahead with nothing archived — and the caller
could still be told it succeeded.

The hook is now a blocking precondition, evaluated while the checkout, its Git
registration, its agents and Orca's ownership evidence are all still intact: it
sits ahead of the registration re-read, the lock/dirty preflights, stopPtys()
and removeWorktree in every orchestrator that runs it.

Failure is typed (worktree_archive_hook_failed) and carries the worktree path,
outcome, exit code where one was observed, and the hook's output. unverifiable
stays distinct from exited, so loss of contact is never read as a pass. The
waiver rides its own field at every layer and is never implied by --force, which
already carries the PTY-stop waiver; when used, the waived failure comes back on
result.archiveHookOverride rather than being swallowed.

worktree.archive-failure-blocking.v1 is advertised so an integration can tell
"accepts --run-hooks" from "safely propagates a failing hook" without risking the
data loss to find out. The runtime's SSH path cannot run a hook at all, so rather
than delete with the archive step silently skipped it refuses — waivable like
every other refusal here. #18563 retires that gate by making the path run the
hook for real.

Stacked on #20559, which makes a timed-out hook report honestly; without it a
hook that traps SIGTERM and exits 0 would defeat this gate.

Fixes #19334
…meout gap

Four review findings on the gate.

A retry from the failure toast could fail for a DIFFERENT reason than the one
the user had just answered, and that second failure got a bare toast with no
buttons. With skipDeleteWorktreeConfirm set, the delete helpers pass no force, so
waiving a failed archive hook on a dirty checkout landed on the dirty preflight
and stopped there. Retry failures now re-enter the same failure toast, so every
retry stays as actionable as the first attempt. Third instance of this class.

The renderer gave worktree.rm a 60s budget while an archive hook may run for
120s. A hook that took 90s and succeeded timed the client out and reported
failure while the host went on to delete — telling the user their delete failed
and their checkout was gone. The budget is now derived from the hook's, and only
when a hook can run.

The SSH fail-open is logged rather than silent, and the capability's doc comment
scopes what it claims: a hook that RUNS and fails cannot delete the checkout; it
is not a promise the hook was found.

The SSH owner-resolution test now reads a real remote orca.yaml through a stubbed
provider and asserts the returned script is the remote one. It previously stopped
at the lookup key, which is the coverage that let this path break twice. It fails
against the row-only resolution.
…anup skips the gate

Two things the rebase onto #20617 and #20576 surfaced, both found by rerunning
the real-repo harness rather than by reading the diff.

- #20617 added a registration-cleanup branch that returns before the archive
  gate. That ordering is correct — both of its arms describe a row with no
  checkout behind it, so there is nothing to archive and running the hook would
  fail on the missing cwd — but the gate's ordering invariant is documented, so
  the exception should be too.
- A signalled hook reported `Command failed with exit code null.`, which reads
  as a reporting glitch rather than the `unverifiable` verdict it is about to
  produce. It now says the command was terminated without reporting an exit
  code. Introduced by #20576; the withheld `exitCode` itself was always right.

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

worktree rm --run-hooks deletes checkout after archive hook failure CLI worktree rm --run-hooks skips archive hooks for SSH repos

1 participant