Skip to content

fix(worktrees): force-clean finished worktrees a leftover pid blocks - #22161

Open
SiinXu wants to merge 1 commit into
stablyai:mainfrom
SiinXu:SiinXu/issue-21954-force-cleanup
Open

SiinXu wants to merge 1 commit into
stablyai:mainfrom
SiinXu:SiinXu/issue-21954-force-cleanup

Conversation

@SiinXu

@SiinXu SiinXu commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

ELI5

Deleting a finished automation workspace could get stuck forever when a leftover process was still running in that folder. Orca now tells you which process is in the way and gives you Kill + Retry, which stops that process and deletes the workspace. If the folder cannot actually be removed, the workspace stays in the list so you can try again.

What Changed

Before: Deleting a workspace refused to continue until every terminal was proven dead. A finished automation workspace whose agent process survived a failed kill could not be deleted from the app, and a later cleanup that failed to remove the folder could forget the workspace record. The next attempt then failed because Orca no longer knew which workspace you meant.

After: A normal delete of a workspace you are still using, with a terminal you can see, still stops before deleting files. For an automation workspace, a workspace marked done, or one with no commits of its own ahead of the default branch, the failure says which process id is still running and offers Kill + Retry. That action stops the process tree (ask it to exit, then force-stop anything still there) and then removes the git worktree. If the folder is still on disk afterwards, Orca keeps the workspace record so the same delete can be retried.

Why

The old rule is right for a workspace you are actively using: do not delete it out from under a terminal you can see. It is the wrong dead end for a finished automation checkout whose process was supposed to be gone already. Killing through the existing process-tree stop, then removing the worktree, clears the leak without a second copy of that stop logic. Keeping the workspace record when the folder delete fails is safer than forgetting the record and leaving the files behind with no way to retry.

Linked Issue

Fixes #21954

Visual Proof

The delete-failure toast gains one sentence and a Kill + Retry button: "cannot delete because PID … still running in this worktree". This dispatch was not allowed to launch the desktop app, so there is no in-app screenshot. The rendered toast copy and button are covered by src/renderer/src/components/sidebar/delete-worktree-failure-toast.test.tsx.

Testing

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

pnpm run typecheck:node and pnpm run typecheck:web passed. Focused vitest covered:

  • an eligible explicit cleanup stops the session tree before git worktree remove --force
  • a user workspace with a visible session is not force-cleaned
  • metadata stays when the folder is still on disk, and the error is not selector_not_found
  • SIGTERM is followed by SIGKILL for a process that is still the same one
  • the toast shows the pid sentence and Kill + Retry

Tested on macOS only. The Windows stop still goes through the existing job and taskkill path inside the shared process-tree kill. SSH removals are unchanged.

AI Disclosure

Grok 4.7, via an Orca dispatched worker. GitHub account SiinXu.

Review

Agent skill upstream boundary

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

Notes

Security: the kill only targets process ids already recorded for that workspace, skips pid 0/1 and this process, and uses the existing identity-checked SIGKILL. It does not run for a user workspace that still has a visible session.

Cross-platform: POSIX uses the existing descendant snapshot. Windows uses the existing job object / taskkill path and does not add a raw child_process spawn.

Remote SSH: local desktop only. Remote removal is unchanged. Loss of contact is not treated as the process having exited.

Mobile: no mobile surface.

Backwards compatibility: the new failure sentence is an error string. The removal request does not add a required field.

Performance: the extra git ahead-count and process stop run only on an explicit force cleanup or on a delete that already failed because a process was still live.

Checklist

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

Author

@TODO_X_HANDLE

A finished automation, completed, or ahead-zero worktree can now stop the
session tree with SIGTERM then SIGKILL and remove the checkout. A user
worktree that still has a visible session stays fail-closed. If the folder
is still on disk, the workspace record is kept so a retry does not come
back as selector_not_found.

Fixes stablyai#21954

Signed-off-by: Siin Xu <[email protected]>
@coderabbitai

coderabbitai Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

📝 Walkthrough

Walkthrough

The change adds finished-worktree force cleanup with eligibility checks, process-tree termination, PID reporting, and orphan-directory settlement. Removal now receives automation provenance and workspace status, preserves metadata when directories remain, and avoids selector_not_found errors. Shared removal classification identifies live-PID blockers. The renderer displays surviving PIDs and offers “Kill + Retry”. Tests cover cleanup, removal ordering, recovery, process termination, and UI behavior.

Priority: ➖ Normal

Merge Risk: 🟠 High · up to f8856

Active automation or user sessions could be terminated during cleanup. Make eligibility and process discovery fail closed before merging.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 4.17% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 24 functions across 16 files. (1 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: force-cleaning finished worktrees when a leftover process blocks removal.
Description check ✅ Passed The description is complete and covers the required change, rationale, linked issue, testing, platform impact, security, and checklist. The visual proof section explains why screenshots are unavailabl…
Linked Issues check ✅ Passed The changes satisfy the coding requirements in #21954. Shared eligibility logic keeps user worktrees with visible sessions fail-closed and permits explicit cleanup for automation, completed, or ahead-…
Out of Scope Changes check ✅ Passed The changed files support #21954 directly. They implement finished-worktree eligibility, session-tree cleanup, orphan recovery, removal integration, PID error classification, UI messaging, localizatio…
Full details: Docstring Coverage

Explanation

Docstring coverage is 4.17% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 24 functions across 16 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 8c3ef09f-b46c-44bd-9a01-abe9fb1cf8e9

📥 Commits

Reviewing files that changed from the base of the PR and between e47ef8c and f88566c.

📒 Files selected for processing (17)
  • src/main/ipc/worktrees-removal-recovery.test.ts
  • src/main/ipc/worktrees/removal/remove-registered-local-worktree.ts
  • src/main/runtime/orca-runtime-remove-managed-worktree.ts
  • src/main/runtime/runtime-finished-worktree-force-cleanup.test.ts
  • src/main/runtime/runtime-registered-local-worktree-removal.ts
  • src/main/worktree-finished-force-cleanup.test.ts
  • src/main/worktree-finished-force-cleanup.ts
  • src/main/worktree-finished-session-tree-kill.test.ts
  • src/main/worktree-finished-session-tree-kill.ts
  • 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/delete-worktree-toast.test.ts
  • src/renderer/src/components/sidebar/delete-worktree-toast.ts
  • src/renderer/src/i18n/locales/en.json
  • src/shared/worktree/finished-worktree-force-cleanup.test.ts
  • src/shared/worktree/finished-worktree-force-cleanup.ts
  • src/shared/worktree/removal.ts

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

Comment on lines +251 to +253
const pids = plan.livePids.length > 0 ? plan.livePids : plan.qualifies ? plan.rootPids : []
if (pids.length > 0) {
return new Error(formatLiveWorktreePidBlocker(pids))

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '185,270p' src/main/worktree-finished-force-cleanup.ts
rg -n "errorIfOrphanDirectoryRemains|WORKTREE_DIRECTORY_KEPT_METADATA_MESSAGE|live-worktree-pid" src/main src/renderer src/shared

Repository: stablyai/orca

Length of output: 5017


🏁 Script executed:

set -e
printf '%s\n' '--- plan and cleanup definitions ---'
sed -n '1,190p' src/main/worktree-finished-force-cleanup.ts
printf '%s\n' '--- cleanup call sites ---'
sed -n '110,235p' src/main/ipc/worktrees/removal/remove-registered-local-worktree.ts
sed -n '160,225p' src/main/runtime/runtime-registered-local-worktree-removal.ts
printf '%s\n' '--- retry/UI handling ---'
sed -n '1,125p' src/renderer/src/components/sidebar/delete-worktree-failure-toast.tsx
sed -n '1,110p' src/renderer/src/components/sidebar/delete-worktree-toast.ts
printf '%s\n' '--- focused tests ---'
sed -n '1,145p' src/main/worktree-finished-force-cleanup.test.ts

Repository: stablyai/orca

Length of output: 28024


🏁 Script executed:

sed -n '190,225p' src/main/ipc/worktrees/removal/remove-registered-local-worktree.ts; sed -n '185,210p' src/main/runtime/runtime-registered-local-worktree-removal.ts; sed -n '1,115p' src/renderer/src/components/sidebar/delete-worktree-failure-toast.tsx; sed -n '1,80p' src/renderer/src/components/sidebar/delete-worktree-toast.ts; sed -n '1,130p' src/main/worktree-finished-force-cleanup.test.ts

Repository: stablyai/orca

Length of output: 13657


🏁 Script executed:

rg -n -C 4 "onForceDelete|forceDeleteReason|showDeleteWorktreeFailureToast|Kill \+ Retry|killAndRetry" src/renderer src/main src/shared

Repository: stablyai/orca

Length of output: 42593


Track whether the kill was attempted before reporting root PIDs.

runLocalFinishedWorktreeForceCleanup returns empty livePids both when it skips killTree and when killTree removes all survivors. If directory settlement returns 'still-present', rootPids can contain only exited processes. The current fallback reports them as live and selects the “Kill + Retry” message instead of the retained-directory message.

The workspace record remains retained. “Kill + Retry” reruns removal with force and can succeed on a later attempt if the directory-removal failure clears, so this is a misleading diagnostic rather than a permanent deletion block. Track whether the kill was attempted. Use rootPids only before an attempt; afterward, use livePids, or return the retained-directory error when that list is empty.

Comment on lines +260 to +266
if (!provider || typeof provider.listProcesses !== 'function') {
return []
}
try {
return await provider.listProcesses()
} catch {
return []

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.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

sed -n '40,180p' src/main/worktree-finished-force-cleanup.ts
rg -n "WorktreeSessionPidSource|listLocalWorktreeSessions|pidRegistrations|listProcesses" src/main

Repository: stablyai/orca

Length of output: 41422


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- cleanup module outline ---'
ast-grep outline src/main/worktree-finished-force-cleanup.ts
printf '%s\n' '--- cleanup module ---'
cat -n src/main/worktree-finished-force-cleanup.ts
printf '%s\n' '--- exact symbols and imports ---'
rg -n -S "WorktreeSessionPidSource|listLocalWorktreeSessions|runLocalFinishedWorktreeForceCleanup|collectWorktreeSessionTree|qualifiesForFinishedWorktreeForceCleanup|forceCleanup|allowUnverifiedPtyStop" src/main --glob '*.{ts,tsx}'
printf '%s\n' '--- provider/session source declarations ---'
rg -n -S "export .*listLocalWorktreeSessions|function listLocalWorktreeSessions|const listLocalWorktreeSessions|WorktreeSessionPidSource|paneBound|rootProcessId" src/main --glob '*.{ts,tsx}'

Repository: stablyai/orca

Length of output: 25567


🤖 get_repo_knowledge executed:

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

Length of output: 27436


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- local provider binding ---'
rg -n -S "getLocalPtyProvider|setLocalPtyProvider|LocalPtyProvider|IPtyProvider" src/main/ipc src/main --glob '*.{ts,tsx}' | head -220
printf '%s\n' '--- qualification predicate ---'
rg -n -S "function qualifiesForFinishedWorktreeForceCleanup|export .*qualifiesForFinishedWorktreeForceCleanup|qualifiesForFinishedWorktreeForceCleanup" src/shared src/main --glob '*.{ts,tsx}'
printf '%s\n' '--- registered local caller ---'
cat -n src/main/runtime/runtime-registered-local-worktree-removal.ts | sed -n '110,180p'
printf '%s\n' '--- IPC local caller ---'
cat -n src/main/ipc/worktrees/removal/remove-registered-local-worktree.ts | sed -n '105,165p'
printf '%s\n' '--- provider implementations near listProcesses ---'
cat -n src/main/daemon/daemon-pty-session-inventory.ts | sed -n '1,145p'
cat -n src/main/daemon/daemon-pty-router.ts | sed -n '180,225p'
cat -n src/main/daemon/degraded-daemon-pty-provider.ts | sed -n '190,225p'

Repository: stablyai/orca

Length of output: 41824


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- qualification implementation ---'
cat -n src/shared/worktree/finished-worktree-force-cleanup.ts
printf '%s\n' '--- pty provider state/accessors ---'
rg -n -S "let localPtyProvider|const localPtyProvider|getLocalPtyProvider|setLocalPtyProvider|_resetLocalPtyProviderStateForTest|new LocalPtyProvider" src/main/ipc/pty.ts src/main/ipc/pty --glob '*.{ts,tsx}'
cat -n src/main/ipc/pty.ts | sed -n '1,150p'
printf '%s\n' '--- local provider inventory ---'
rg -n -S "class LocalPtyProvider|async listProcesses|listProcesses\\(" src/main/providers/local-pty-provider.ts src/main/providers --glob '*.ts'
cat -n src/main/providers/local-pty-provider.ts | sed -n '1,180p'
printf '%s\n' '--- focused cleanup tests ---'
cat -n src/main/worktree-finished-force-cleanup.test.ts | sed -n '1,240p'

Repository: stablyai/orca

Length of output: 21553


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- provider registry ---'
cat -n src/main/ipc/pty/provider/registry.ts | sed -n '1,155p'
printf '%s\n' '--- local list operation ---'
rg -n -S "function listLocalPtyProcesses|const listLocalPtyProcesses|export .*listLocalPtyProcesses" src/main/providers
cat -n src/main/providers/local-pty-session-operations.ts | sed -n '1,180p'

Repository: stablyai/orca

Length of output: 13671


Keep process enumeration failures fail-closed.

When provider.listProcesses() rejects, the helper returns []. Matching registration PIDs still populate rootPids, but hasLiveUiVisibleSession becomes false. A non-automation worktree with commitsAheadOfDefault === 0 can then qualify, and the allowUnverifiedPtyStop path can kill the visible session.

Track enumeration as unknown instead of treating failure as an empty inventory. Reject cleanup for non-automation worktrees when enumeration is unknown.

Comment on lines +23 to +68
function usableRootPid(pid: number): boolean {
return Number.isInteger(pid) && pid > 1 && pid !== process.pid
}

/**
* SIGTERM the session tree, then SIGKILL whatever is still the same process.
* POSIX proof goes through the existing snapshot verdict. Windows goes through
* killWithDescendantSweep, which already owns the job object and taskkill path.
*/
export async function forceKillFinishedWorktreeSessionTree(
rootPids: readonly number[],
deps: FinishedSessionTreeKillDeps = {}
): Promise<FinishedSessionTreeKillResult> {
const killTree = deps.killWithDescendantSweep ?? killWithDescendantSweep
const capture = deps.captureDescendantSnapshot ?? captureDescendantSnapshot
const terminate =
deps.terminateDescendantSnapshotWithVerdict ?? terminateDescendantSnapshotWithVerdict
const sendSignal = deps.sendSignal ?? sendDescendantSignal
const platform = deps.platform ?? process.platform
const livePids: number[] = []
const seen = new Set<number>()

for (const pid of rootPids) {
if (!usableRootPid(pid) || seen.has(pid)) {
continue
}
seen.add(pid)
const snapshot = await capture(pid, deps)
await killTree(pid, () => sendSignal(pid, 'SIGTERM'), {
...deps,
platform
})
if (!snapshot?.root || platform === 'win32') {
continue
}
const verdict = await terminate(snapshotWithRoot(snapshot, pid), {
...deps,
sendSignal
})
if (verdict === 'live') {
livePids.push(pid)
}
}

return { livePids }
}

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '1,110p' src/main/worktree-finished-session-tree-kill.ts
sed -n '210,270p' src/main/pty-descendant-termination.ts
sed -n '80,200p' src/main/pty-descendant-exit-verification.ts

Repository: stablyai/orca

Length of output: 9292


🏁 Script executed:

printf '%s\n' '--- sweep implementation ---'
sed -n '250,390p' src/main/pty-descendant-termination.ts
printf '%s\n' '--- callers and result handling ---'
rg -n -C 6 'forceKillFinishedWorktreeSessionTree|livePids|finished.worktree|finished worktree|force.*cleanup|remove.*worktree|worktree.*remove' src
printf '%s\n' '--- related tests ---'
rg -n -C 5 'forceKillFinishedWorktreeSessionTree|captureDescendantSnapshot|killWithDescendantSweep|SIGKILL|livePids' test tests src --glob '*test*' --glob '*spec*' 2>/dev/null

Repository: stablyai/orca

Length of output: 45532


🏁 Script executed:

printf '%s\n' '--- killWithDescendantSweep ---'
sed -n '270,380p' src/main/pty-descendant-termination.ts
printf '%s\n' '--- finished-worktree force-cleanup files ---'
rg -l 'forceKillFinishedWorktreeSessionTree|runLocalFinishedWorktreeForceCleanup|livePids' src/main --glob '*.ts' --glob '!*.test.ts'
printf '%s\n' '--- direct function callers ---'
rg -n -C 12 'forceKillFinishedWorktreeSessionTree' src/main --glob '*.ts'
printf '%s\n' '--- force-cleanup implementation ---'
rg -l 'runLocalFinishedWorktreeForceCleanup' src/main --glob '*.ts' --glob '!*.test.ts' | xargs -r -n1 sh -c 'echo "--- $0"; sed -n "1,260p" "$0"'

Repository: stablyai/orca

Length of output: 43857


🏁 Script executed:

printf '%s\n' '--- finished-session-tree-kill tests ---'
sed -n '1,240p' src/main/worktree-finished-session-tree-kill.test.ts
printf '%s\n' '--- remaining sweep implementation ---'
sed -n '380,490p' src/main/pty-descendant-termination.ts
printf '%s\n' '--- removal continuation and blocker handling ---'
sed -n '100,230p' src/main/ipc/worktrees/removal/remove-registered-local-worktree.ts
sed -n '230,330p' src/main/ipc/worktrees/removal/remove-registered-local-worktree.ts

Repository: stablyai/orca

Length of output: 10992


🏁 Script executed:

rg -n -C 12 'function stopPtysForDestructiveWorktreeRemoval|stopPtysForDestructiveWorktreeRemoval' src/main
rg -n -C 10 'allowUnverifiedStop|remainingCount|listProcesses|stopPtys' src/main/ipc/worktrees/removal/worktree-removal-ownership.ts src/main --glob '*.ts' | head -n 260

Repository: stablyai/orca

Length of output: 42210


🏁 Script executed:

nl -ba src/main/pty-descendant-termination.ts | sed -n '260,345p'
nl -ba src/main/worktree-finished-session-tree-kill.ts | sed -n '27,75p'
nl -ba src/main/worktree-finished-force-cleanup.ts | sed -n '155,175p'
nl -ba src/main/ipc/worktrees/removal/worktree-removal-ownership.ts | sed -n '1,75p'
nl -ba src/main/ipc/worktrees/removal/remove-registered-local-worktree.ts | sed -n '145,220p'

Repository: stablyai/orca

Length of output: 15575


Fail closed when POSIX snapshot capture is unavailable. When the POSIX snapshot remains null, killWithDescendantSweep skips descendant termination and invokes only the SIGTERM root callback. This path skips identity-aware verification, SIGKILL escalation, and livePids reporting. The cleanup plan can therefore remain empty, and removal can continue after the waived PTY stop. Propagate a null snapshot as an unverified blocker so finished-worktree removal fails closed. Do not synthesize identity data for SIGKILL.

Comment on lines +20 to +21
if (facts.hasAutomationProvenance) {
return 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.

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

rg -n "hasAutomationProvenance|automationProvenance|new-per-run|workspaceStatus|qualifiesForFinishedWorktreeForceCleanup" src/main src/shared
sed -n '1,220p' src/shared/worktree/finished-worktree-force-cleanup.ts
sed -n '120,180p' src/main/worktree-finished-force-cleanup.ts

Repository: stablyai/orca

Length of output: 35903


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- provenance definitions and lifecycle ---'
rg -n -C 5 "type AutomationWorkspaceProvenance|interface AutomationWorkspaceProvenance|AutomationWorkspaceProvenance|finishAutomationWorkspaceProvenanceRequest|resolveAutomationWorkspaceProvenance|releaseAutomationWorkspaceProvenanceRequest|automationProvenance" src/main/automations src/main/runtime src/shared/worktree src/shared 2>/dev/null | head -n 420

printf '%s\n' '--- local removal call path ---'
sed -n '1,230p' src/main/ipc/worktrees/removal/remove-registered-local-worktree.ts
sed -n '1,200p' src/main/runtime/runtime-registered-local-worktree-removal.ts
sed -n '220,285p' src/main/runtime/orca-runtime-remove-managed-worktree.ts

printf '%s\n' '--- automation lifecycle/status and retention analogues ---'
rg -n -C 5 "Kill|Retry|retry|finished|completed|status|retain|retention|cleanup|force-clean|new-per-run|visible session" src/main/automations src/main/runtime src/main/ipc src/shared/worktree 2>/dev/null | head -n 520

Repository: stablyai/orca

Length of output: 42740


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- provenance contract and resolver ---'
cat -n src/shared/worktree/types.ts | sed -n '140,190p'
cat -n src/shared/automation-workspace-provenance.ts | sed -n '1,180p'
cat -n src/main/automations/workspace-provenance.ts | sed -n '31,115p'

printf '%s\n' '--- headless creation and run lifecycle ---'
cat -n src/main/automations/headless-workspace-create.ts | sed -n '1,90p'
cat -n src/main/automations/headless-dispatch.ts | sed -n '1,180p'
rg -n -C 8 "runNow\\(|createManagedWorktree|headless|buildHeadless|completion" src/main/automations src/main/runtime | head -n 360

printf '%s\n' '--- completion/status contract ---'
rg -n -C 8 "type AutomationRun|status:.*dispatched|dispatched.*completed|status.*dispatching|dispatch_failed|completed" src/shared/automations-types.ts src/main/automations/run-completion-watcher.ts src/main/automations/retained-run-reconciliation.ts | head -n 360

printf '%s\n' '--- local removal and cleanup action ---'
cat -n src/main/ipc/worktrees/removal/remove-registered-local-worktree.ts | sed -n '110,175p'
cat -n src/main/runtime/runtime-registered-local-worktree-removal.ts | sed -n '1,175p'
cat -n src/shared/worktree/finished-worktree-force-cleanup.ts | sed -n '1,65p'
rg -n -C 10 "forceKillFinishedWorktreeSessionTree|Kill|Retry|runLocalFinishedWorktreeForceCleanup" src/main src/shared | head -n 360

Repository: stablyai/orca

Length of output: 43045


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- headless dispatch runner ---'
f=$(fd -t f 'headless-dispatch-runner.ts' src/main/automations | head -n 1)
test -n "$f"
cat -n "$f" | sed -n '1,240p'

printf '%s\n' '--- automation run status types ---'
cat -n src/shared/automations-types.ts | sed -n '1,180p'

printf '%s\n' '--- force cleanup execution ---'
cat -n src/main/worktree-finished-force-cleanup.ts | sed -n '150,180p'
rg -n -C 12 "function forceKillFinishedWorktreeSessionTree|forceKillFinishedWorktreeSessionTree|SIGTERM|SIGKILL" src/main src/shared | head -n 220

Repository: stablyai/orca

Length of output: 33204


Require proof that the automation is finished before force cleanup.

hasAutomationProvenance identifies a workspace created by an automation run. It does not contain or check a terminal run status. The provenance is created while the run is dispatching and remains in the workspace metadata after launch. An active automation with a visible session can therefore reach this branch, allowing Kill + Retry to terminate its session.

Require an explicit finished-automation fact in this eligibility check. Do not use provenance alone as completion evidence.

@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

This PR's own changed-code quality gate fails: pnpm run check:code-quality:changed (the CI step "Enforce changed-code quality", .github/workflows/pr.yml:153) reports six new typescript/consistent-type-assertions findings, all on lines this PR adds. pnpm lint / audit:code-quality:native passes because only the changed-code gate enforces assertionStyle: never, so this will show up as a red check rather than a local lint failure. Fix locations are inline.

Reviewed changes

  • New shared predicate — qualifiesForFinishedWorktreeForceCleanup plus the formatLiveWorktreePidBlocker / isLiveWorktreePidBlocker / readLiveWorktreePids helpers that carry the new "PID … still running" reason through the toast classifier.
  • Main-side force cleanup — worktree-finished-force-cleanup.ts collects the worktree's session pids, counts commits ahead of the default branch, kills the session tree on an explicit force cleanup, settles an orphaned directory, and rewrites a proven-live PTY error into the pid blocker.
  • Session-tree kill — worktree-finished-session-tree-kill.ts SIGTERMs the tree and escalates survivors to SIGKILL through the existing descendant verdict API; Windows keeps the job/taskkill path and records no live pids.
  • Removal wiring — the local IPC and runtime removal paths run the force cleanup inside the pty_sweep stage and now keep workspace metadata (instead of dropping it) when the orphan directory survives; managed-worktree removal forwards automationProvenance / workspaceStatus.
  • Renderer — delete-worktree-toast.ts / delete-worktree-failure-toast.tsx add the live-worktree-pid reason, the pid copy, and a "Kill + Retry" button, with two new en.json keys.

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

} catch (error) {
const code =
error && typeof error === 'object' && 'code' in error
? (error as { code?: unknown }).code

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.

This cast is one of six new typescript/consistent-type-assertions findings that fail pnpm run check:code-quality:changed (the PR CI step "Enforce changed-code quality"). 'code' in error already narrows the type, so error.code reads as unknown without the assertion — or, per AGENTS.md, an unavoidable cast needs a line-specific oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: ….


describe('finished worktree force cleanup', () => {
it('SIGTERM-then-SIGKILL is requested only for an eligible explicit force cleanup', async () => {
const killTree = vi.fn(async () => ({ livePids: [] as number[] }))

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.

[] as number[] here (also lines 43 and 72) is three of the six new consistent-type-assertions findings failing check:code-quality:changed. Dropping the cast infers never[], which is assignable to number[] at every use in this file.

const base = {
hasAutomationProvenance: false,
workspaceStatus: 'in-progress',
commitsAheadOfDefault: null as number | null,

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.

null as number | null is one of the six new consistent-type-assertions findings failing check:code-quality:changed; plain null is assignable to the number | null field wherever base is spread into qualifiesForFinishedWorktreeForceCleanup.

target: { id: 'repo-1::/repo-feature', repoId: 'repo-1', path: '/repo-feature' },
registeredWorktree: registered,
removedPushTarget: undefined,
store: { getWorktreeMeta: () => undefined } as never,

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.

as never is the sixth new consistent-type-assertions finding failing check:code-quality:changed. A typed stub (or the AGENTS.md SAFETY:-annotated disable) is needed here.

if (!ownsSession(session)) {
continue
}
if (session.paneBound === 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.

hasLiveUiVisibleSession can never be true on the local path this runs on: the only producer of paneBound is the relay handler (src/relay/pty-handler.ts:2898), and neither LocalPtyProvider.listProcesses() (src/main/providers/local-pty-session-operations.ts:118) nor the daemon inventory sets it (the daemon sets rootProcessId only). So for a user workspace the "visible terminal stays fail-closed" guard collapses to the commits-ahead / completed check, and the unit test asserting the guard injects a paneBound: true the real provider never emits. Either publish paneBound locally or drop the field from the local qualification.

This branch has not been deployed

No deployments
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.

[Bug]: Fail-closed worktree delete + failed PTY kill turns finished automation worktrees into undeletable disk leaks

1 participant