Skip to content

fix(host-service): resolve teardown from config.json on v2 delete; only skip teardown on explicit retry - #5485

Closed
ivanvan93 wants to merge 2 commits into
ParadevAI:mainfrom
ivanvan93:fix/v2-delete-teardown-resolution
Closed

ivanvan93 wants to merge 2 commits into
ParadevAI:mainfrom
ivanvan93:fix/v2-delete-teardown-resolution

Conversation

@ivanvan93

@ivanvan93 ivanvan93 commented Jul 7, 2026 •

Copy link
Copy Markdown

Problem

Deleting a workspace on the v2 delete path silently skips the project's teardown scripts in the two most common configurations:

  1. teardown command arrays in .superset/config.json are never executed. The v2 destroy path only looks for a literal file at <worktree>/.superset/teardown.sh and never reads config.json — even though the v2 project-settings Scripts editor writes config.json arrays, and the docs (setup-teardown-scripts.mdx: "Delete workspace → teardown commands run") promise they run. This is a regression: feat(desktop): add teardown script support for workspace deletion #178 added config-array teardown to the original delete path; the v2 unification in feat(v2): unify workspace delete through host-service #3443 dropped it, and feat(desktop): setup/teardown scripts editor for v2 projects #4090 upgraded only setup to read config while shipping the editor that writes teardown arrays nothing executes.
  2. Any delete with force: true skipped teardown entirely — every "Delete anyway" on a workspace with uncommitted/unpushed changes (run(hasWarnings)), and every CLI/SDK/MCP delete (workspace.delete hard-codes force: true). force conflated "delete despite dirty files" with "skip the teardown script".

Both skips were silent: no log line, no warning, no result field.

Repro: a project with "teardown": ["./scripts/worktree/teardown.sh"] in .superset/config.json (no .superset/teardown.sh file). Create a workspace, keep it clean, delete it → teardown never runs. Setup runs fine on creation.

Fix

Teardown now resolves exactly like setup (resolveInitialCommand in setup-terminal.ts):

  1. teardown commands from .superset/config.json (+ ~/.superset/projects/<id>/config.json override + config.local.json overlay), joined with &&, run as exec bash -c '…' (same fish-safe exec trick as the existing script path)
  2. <worktree>/.superset/teardown.sh (unchanged behavior)
  3. <mainRepo>/.superset/teardown.sh — main repo is authoritative; worktrees skip gitignored files (parity with setup)

force no longer skips teardown. A new skipTeardown destroy input (default false) is the only bypass, and the renderer sets it only on the TeardownFailedPane "Delete anyway" retry — where re-running the script that just failed/timed out would only stall the user again. Under force, a teardown failure downgrades to a warnings entry instead of blocking; the non-force TEARDOWN_FAILED typed-error contract is unchanged.

Observability: skips are logged ([teardown] Nothing to run …, [workspaceCleanup.destroy] teardown <status> …) and the destroy result gains teardownStatus: "ok" | "skipped" | "failed" | "not-run".

The legacy external workspace.delete surface keeps force: true and therefore now runs teardown best-effort (failures don't block SDK/CLI deletes).

Testing

  • New unit tests for resolveTeardownCommand (config wins over worktree script; worktree → main-repo fallback; null when unconfigured; whitespace-only commands ignored; quoting) — bun test src/runtime/teardown: 8 pass
  • Existing integration suites (teardown, workspace-cleanup, workspace-create-delete): 27 pass; the create-delete run now visibly logs teardown skipped … (force=true, skipTeardown=false), showing forced deletes go through resolution
  • bun run typecheck (28/28 packages), bun run lint clean

ExecPlan with the full investigation and decision log: plans/done/20260707-1351-v2-delete-teardown-resolution.md.


Open in Stage

Summary by cubic

Ensure v2 workspace deletes run project teardown and only skip it on an explicit retry after a teardown failure. Teardown now resolves from .superset/config.json and runs in the user's shell (like setup), with clear logs and a teardownStatus in the result.

  • Bug Fixes

    • Teardown resolution mirrors setup: read teardown from .superset/config.json (incl. user overrides), else <worktree>/.superset/teardown.sh, else <repo>/.superset/teardown.sh.
    • Config teardown commands run in the user's shell with && and a trailing exit for parity and correct exit codes across bash/zsh/fish.
    • force no longer skips teardown; new skipTeardown input controls bypass and is only set on the TeardownFailedPane "Delete anyway" retry.
    • On force, teardown failures become warnings; non-force still throws the TEARDOWN_FAILED error.
    • Added logs for skips and outcomes; workspaceCleanup.destroy returns teardownStatus: "ok" | "skipped" | "failed" | "not-run".
  • Migration

    • No action required. CLI/SDK deletes (which set force: true) now run teardown best-effort and may take up to the timeout if teardown hangs.

Written for commit de1edcd. Summary will update on new commits.

Review in cubic

Summary by CodeRabbit

  • New Features

    • Workspace deletion now supports an independent option to skip teardown during specific retry flows.
    • Teardown commands are now resolved from configuration first, with automatic fallback to workspace/repository teardown scripts when not configured.
  • Bug Fixes

    • Workspace deletion now reports teardown outcomes more precisely (ok, skipped, failed, or not run).
    • Retry and force-delete behavior now preserves teardown unless teardown is explicitly skipped, improving consistency across dirty and conflict cases.

…ly skip teardown on explicit retry

The v2 destroy saga only ever executed a literal <worktree>/.superset/teardown.sh
and skipped teardown entirely whenever force was set, so:

- teardown command arrays in .superset/config.json (what the v2 Scripts editor
  writes, and what the docs promise runs on delete) were never executed —
  regression of PR ParadevAI#178 behavior introduced by the v2 unification in PR ParadevAI#3443
- any "Delete anyway" on a dirty workspace, and every CLI/SDK/MCP delete
  (force hard-coded), silently skipped teardown

Changes:
- runTeardown resolves like setup does: config.json teardown commands (incl.
  user override + config.local.json overlay) -> worktree teardown.sh -> main
  repo teardown.sh; skips are logged
- new skipTeardown destroy input replaces force as the teardown bypass; it is
  only set by the TeardownFailedPane retry. force still means "delete despite
  dirty files": teardown runs, failures downgrade to a warning
- destroy result gains teardownStatus for observability
@coderabbitai

coderabbitai Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds config-aware teardown command resolution in host-service, decouples a new skipTeardown destroy input from force, and introduces teardownStatus reporting across the destroy mutation, renderer hooks, and dialog wiring. Tests and a plan document accompany the change.

Changes

Config-aware teardown resolution and skipTeardown flow

Layer / File(s) Summary
Teardown command resolver in setup config
packages/host-service/src/runtime/setup/config.ts
Adds getResolvedTeardownCommands to resolve teardown command strings from setup config.
Core teardown resolution and execution logic
packages/host-service/src/runtime/teardown/teardown.ts, packages/host-service/src/runtime/teardown/teardown.test.ts, packages/host-service/test/integration/teardown.integration.test.ts
resolveTeardownCommand and runTeardown resolve commands from config first, then worktree/repo .superset/teardown.sh, building shell command strings; tests cover precedence, fallback, and command-string behavior.
Destroy mutation: skipTeardown input, teardownStatus output
packages/host-service/src/trpc/router/workspace-cleanup/workspace-cleanup.ts
Adds skipTeardown input, rewrites teardown-phase logic to track teardownStatus, downgrades teardown failure to warning under force, and returns teardownStatus in the result.
Renderer hook and dialog wiring
apps/desktop/src/renderer/hooks/host-service/useDestroyWorkspace/useDestroyWorkspace.ts, apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarDeleteDialog/...
Forwards skipTeardown in the mutation payload, exposes teardownStatus in success type, updates run callback signature to an options object, and updates dialog call sites for force-delete and confirm.
ExecPlan documentation
plans/done/20260707-1351-v2-delete-teardown-resolution.md
Adds a living plan document describing the teardown regression, decisions, milestones, and acceptance criteria.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant DashboardSidebarDeleteDialog
  participant useDestroyDialogState
  participant useDestroyWorkspace
  participant WorkspaceCleanupRouter
  participant runTeardown

  DashboardSidebarDeleteDialog->>useDestroyDialogState: run({ force, skipTeardown })
  useDestroyDialogState->>useDestroyWorkspace: destroy({ deleteBranch, force, skipTeardown })
  useDestroyWorkspace->>WorkspaceCleanupRouter: destroy mutation (skipTeardown)
  alt skipTeardown false
    WorkspaceCleanupRouter->>runTeardown: run teardown (repoPath, projectId, worktreePath)
    runTeardown-->>WorkspaceCleanupRouter: status (ok/failed/skipped)
  else skipTeardown true
    WorkspaceCleanupRouter-->>WorkspaceCleanupRouter: teardownStatus = "not-run"
  end
  WorkspaceCleanupRouter-->>useDestroyWorkspace: { teardownStatus, success, warnings }
  useDestroyWorkspace-->>useDestroyDialogState: result with teardownStatus
Loading

Possibly related PRs

  • superset-sh/superset#4478: Both PRs modify packages/host-service/src/runtime/teardown/teardown.ts to change how the teardown command is constructed and executed.
  • superset-sh/superset#4673: Both PRs touch the delete dialog retry/confirm handlers that drive the teardown-failed flow.
  • superset-sh/superset#4801: Both PRs modify the workspace-cleanup destroy flow in workspace-cleanup.ts, updating teardown semantics and the returned payload.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main change: teardown resolution from config.json and the new explicit skipTeardown behavior.
Description check ✅ Passed The description covers the problem, fix, and testing, but it doesn't follow the repository's template sections exactly.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@ghost

ghost commented Jul 7, 2026 •

Copy link
Copy Markdown

Ready to review this PR? Stage has broken it down into 5 individual chapters for you:

Title
1 Document the teardown resolution fix plan
2 Enable teardown command resolution from config
3 Test teardown resolution and integration
4 Decouple force delete from teardown skipping
5 Wire skipTeardown through the UI layer
Open in Stage

Chapters generated by Stage for commit de1edcd on Jul 7, 2026 5:01am UTC.

@greptile-apps

greptile-apps Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR updates workspace deletion so teardown scripts run on the v2 host-service path. The main changes are:

  • Added config-based teardown resolution with script fallbacks.
  • Split skipTeardown from force in the destroy API.
  • Changed forced deletes to run teardown best-effort.
  • Added teardown status reporting and renderer wiring.

Confidence Score: 4/5

The config-array teardown path needs a compatibility fix before merging.

  • Forced delete and retry state handling looks consistent.
  • Teardown status reporting is wired through the host-service result.
  • Config teardown commands now run through bash -c, which can break projects whose setup config works in the user's terminal shell.

packages/host-service/src/runtime/teardown/teardown.ts

Important Files Changed

Filename Overview
packages/host-service/src/runtime/teardown/teardown.ts Adds config-aware teardown resolution, but config commands are executed through bash instead of matching setup command shell behavior.
packages/host-service/src/trpc/router/workspace-cleanup/workspace-cleanup.ts Decouples teardown skipping from forced deletion and reports teardown status.
apps/desktop/src/renderer/hooks/host-service/useDestroyWorkspace/useDestroyWorkspace.ts Passes the optional skipTeardown flag through the renderer host-service hook.
apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarDeleteDialog/DashboardSidebarDeleteDialog.tsx Routes normal confirmation and teardown-failure retry to the correct destroy options.
apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarDeleteDialog/hooks/useDestroyDialogState/useDestroyDialogState.ts Forwards skipTeardown through the delete state machine while keeping dirty-conflict retries running teardown.
packages/host-service/src/runtime/setup/config.ts Adds a teardown command accessor that mirrors setup command filtering.
Prompt To Fix All With AI
Fix the following 1 code review issue. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 1
packages/host-service/src/runtime/teardown/teardown.ts:200
**Config Commands Use Wrong Shell**

When a project has config-array teardown commands, this wraps them in `bash -c` even though setup config commands run in the user's terminal shell. A workspace can create successfully with shell-specific setup/teardown config, then fail during delete because the teardown command is re-parsed by non-interactive bash instead of the same shell contract used for setup.

Reviews (1): Last reviewed commit: "fix(host-service): resolve teardown from..." | Re-trigger Greptile


/** Same `exec bash` trick as above, for config-declared command strings. */
export function buildTeardownCommandString(command: string): string {
return `exec bash -c ${singleQuote(command)}`;

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.

P1 Config Commands Use Wrong Shell

When a project has config-array teardown commands, this wraps them in bash -c even though setup config commands run in the user's terminal shell. A workspace can create successfully with shell-specific setup/teardown config, then fail during delete because the teardown command is re-parsed by non-interactive bash instead of the same shell contract used for setup.

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/host-service/src/runtime/teardown/teardown.ts
Line: 200

Comment:
**Config Commands Use Wrong Shell**

When a project has config-array teardown commands, this wraps them in `bash -c` even though setup config commands run in the user's terminal shell. A workspace can create successfully with shell-specific setup/teardown config, then fail during delete because the teardown command is re-parsed by non-interactive bash instead of the same shell contract used for setup.

How can I resolve this? If you propose a fix, please make it concise.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

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

⚠️ Outside diff range comments (2)
packages/host-service/src/trpc/router/workspace-cleanup/workspace-cleanup.ts (1)

137-159: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Stale phase-list doc line contradicts the new force semantics below it.

Line 137 still reads 1. Teardown — run .superset/teardown.sh (skip if force), but the updated Force semantics block right below (Lines 147-159) now explicitly states force no longer skips teardown (only skipTeardown does), and teardown resolution is config-aware rather than tied to the literal .superset/teardown.sh path. This leaves two contradictory statements in the same doc comment.

📝 Proposed fix
- *   1. Teardown      — run .superset/teardown.sh (skip if force)
+ *   1. Teardown      — resolve & run configured teardown (skip if skipTeardown)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/host-service/src/trpc/router/workspace-cleanup/workspace-cleanup.ts`
around lines 137 - 159, Update the phase-list doc in workspace-cleanup so it
matches the current force and teardown behavior. In the comment near the cleanup
flow summary, change the “Teardown” bullet to reflect that force does not skip
teardown and that teardown is controlled by `skipTeardown`, not the force flag;
also avoid hard-coding `.superset/teardown.sh` if the implementation uses
config-aware teardown resolution. Keep the wording consistent with the Force
semantics block and the `skipTeardown` description in the same comment.
apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarDeleteDialog/hooks/useDestroyDialogState/useDestroyDialogState.ts (1)

118-136: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Conflict retry should hard-code skipTeardown: false, not pass it through.

The retry after a conflict error passes the caller-supplied skipTeardown through unchanged. Since the dirty-worktree conflict fires in phase 0 (before teardown runs in phase 1), the retry should always run teardown regardless of the original flag's value. Today this is masked because the only caller passing skipTeardown: true also passes force: true, which the !force guard already excludes from this branch — but that coupling is incidental, not enforced, and a future call site combining force: false with skipTeardown: true would silently skip teardown on retry even though it never ran.

🔧 Proposed fix
 					if (e.kind === "conflict" && !force) {
-						result = await destroy({ deleteBranch, force: true, skipTeardown });
+						result = await destroy({ deleteBranch, force: true, skipTeardown: false });
 					} else {

Based on the PR plan's documented requirement that this retry "must pass skipTeardown: false semantics... teardown has not run yet at that point".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarDeleteDialog/hooks/useDestroyDialogState/useDestroyDialogState.ts`
around lines 118 - 136, The conflict-retry path in useDestroyDialogState should
always force teardown on retry instead of propagating the caller’s skipTeardown
value. Update the retry call inside the catch block around destroy(...) so the
second invocation hard-codes skipTeardown to false while still setting force to
true, since this branch is only for the dirty-worktree conflict before teardown
runs. Keep the change localized to useDestroyDialogState and the destroy(...)
retry logic.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@plans/done/20260707-1351-v2-delete-teardown-resolution.md`:
- Around line 168-170: The teardown validation example uses the wrong config
shape, so update the manual end-to-end check to match the documented teardown
array contract. In the teardown verification snippet, replace the nested object
form with the same plain command array shape used by the implementation, and
keep the example centered on making the teardown observable with a command like
appending to a log. Refer to the teardown example in this plan section so the
manual test exercises the same contract as the parser and execution path.

---

Outside diff comments:
In
`@apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarDeleteDialog/hooks/useDestroyDialogState/useDestroyDialogState.ts`:
- Around line 118-136: The conflict-retry path in useDestroyDialogState should
always force teardown on retry instead of propagating the caller’s skipTeardown
value. Update the retry call inside the catch block around destroy(...) so the
second invocation hard-codes skipTeardown to false while still setting force to
true, since this branch is only for the dirty-worktree conflict before teardown
runs. Keep the change localized to useDestroyDialogState and the destroy(...)
retry logic.

In
`@packages/host-service/src/trpc/router/workspace-cleanup/workspace-cleanup.ts`:
- Around line 137-159: Update the phase-list doc in workspace-cleanup so it
matches the current force and teardown behavior. In the comment near the cleanup
flow summary, change the “Teardown” bullet to reflect that force does not skip
teardown and that teardown is controlled by `skipTeardown`, not the force flag;
also avoid hard-coding `.superset/teardown.sh` if the implementation uses
config-aware teardown resolution. Keep the wording consistent with the Force
semantics block and the `skipTeardown` description in the same comment.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 4f98530d-2ad3-47c4-8d8f-8ac870c3e608

📥 Commits

Reviewing files that changed from the base of the PR and between 931b6b2 and 28f90aa.

📒 Files selected for processing (9)
  • apps/desktop/src/renderer/hooks/host-service/useDestroyWorkspace/useDestroyWorkspace.ts
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarDeleteDialog/DashboardSidebarDeleteDialog.tsx
  • apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/DashboardSidebar/components/DashboardSidebarDeleteDialog/hooks/useDestroyDialogState/useDestroyDialogState.ts
  • packages/host-service/src/runtime/setup/config.ts
  • packages/host-service/src/runtime/teardown/teardown.test.ts
  • packages/host-service/src/runtime/teardown/teardown.ts
  • packages/host-service/src/trpc/router/workspace-cleanup/workspace-cleanup.ts
  • packages/host-service/test/integration/teardown.integration.test.ts
  • plans/done/20260707-1351-v2-delete-teardown-resolution.md

Comment on lines +168 to +170
Manual end-to-end check, using any project whose teardown is declared in config.json (K3 is ideal). Make the teardown observable, e.g. append to the project's teardown script (or temporarily set in the main repo's `.superset/config.local.json`):

{ "teardown": { "after": ["date >> /tmp/superset-teardown-ran.log"] } }

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

Fix the teardown config example.

This validation snippet uses { "teardown": { "after": [...] } }, which doesn't match the teardown array shape documented earlier in the plan. It should show a plain command array so the manual test exercises the same contract as the implementation.

♻️ Proposed fix
-    { "teardown": { "after": ["date >> /tmp/superset-teardown-ran.log"] } }
+    { "teardown": ["date >> /tmp/superset-teardown-ran.log"] }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
Manual end-to-end check, using any project whose teardown is declared in config.json (K3 is ideal). Make the teardown observable, e.g. append to the project's teardown script (or temporarily set in the main repo's `.superset/config.local.json`):
{ "teardown": { "after": ["date >> /tmp/superset-teardown-ran.log"] } }
Manual end-to-end check, using any project whose teardown is declared in config.json (K3 is ideal). Make the teardown observable, e.g. append to the project's teardown script (or temporarily set in the main repo's `.superset/config.local.json`):
{ "teardown": ["date >> /tmp/superset-teardown-ran.log"] }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@plans/done/20260707-1351-v2-delete-teardown-resolution.md` around lines 168 -
170, The teardown validation example uses the wrong config shape, so update the
manual end-to-end check to match the documented teardown array contract. In the
teardown verification snippet, replace the nested object form with the same
plain command array shape used by the implementation, and keep the example
centered on making the teardown observable with a command like appending to a
log. Refer to the teardown example in this plan section so the manual test
exercises the same contract as the parser and execution path.

@cubic-dev-ai cubic-dev-ai 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.

2 issues found across 9 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="plans/done/20260707-1351-v2-delete-teardown-resolution.md">

<violation number="1" location="plans/done/20260707-1351-v2-delete-teardown-resolution.md:25">
P3: The ExecPlan in `plans/done/` contains two Open Questions that are already answered by Decisions D3 and D4 later in the same document. In a completed plan, these should be marked resolved or moved out of the Open Questions section so future readers don't re-escalate already-made product decisions.

Additionally, the Progress checklist leaves the "Manual marker-file scenario" item unchecked even though all other milestones are checked and the Outcomes section describes it as intentionally outstanding. For a living document that states its sections must be kept up to date, leaving this ambiguously unchecked in a `done/` plan can suggest it was forgotten rather than deferred. Consider marking it `[~]` or `[x] (deferred — automated coverage equivalent)` to make intent explicit.</violation>
</file>

<file name="packages/host-service/src/trpc/router/workspace-cleanup/workspace-cleanup.ts">

<violation number="1" location="packages/host-service/src/trpc/router/workspace-cleanup/workspace-cleanup.ts:147">
P2: The destroy-phase JSDoc list still says teardown is `run .superset/teardown.sh` and is `skip if force`, but both claims are now obsolete. The newly added `Force semantics` section below correctly says the opposite (`"delete despite dirty files" — NOT "skip teardown"`), and the PR description confirms teardown now resolves from overlaid `config.json` files (not just `.superset/teardown.sh`). Please update the phase list so it no longer contradicts the detailed semantics or the actual implementation: change the teardown line to reflect config-based resolution and replace `skip if force` with `skip if skipTeardown`.</violation>
</file>
Architecture diagram
sequenceDiagram
    participant UI as Renderer (Dialog)
    participant Dialog as useDestroyDialogState
    participant DestroySvc as useDestroyWorkspace
    participant TRPC as TRPC Client
    participant Backend as workspaceCleanup.destroy
    participant Resolve as resolveTeardownCommand
    participant Teardown as runTeardown
    participant Terminal as PTY Session

    Note over UI,Terminal: Workspace deletion v2 – teardown resolution (this PR)

    UI->>Dialog: onConfirm({ force, skipTeardown: false })

    Dialog->>DestroySvc: destroy({ workspaceId, deleteBranch, force, skipTeardown })

    DestroySvc->>TRPC: mutate destroy with input

    TRPC->>Backend: destroyWorkspace(ctx, input)

    Backend->>Backend: skip preflight if force

    alt skipTeardown === false
        Backend->>Resolve: resolveTeardownCommand(repoPath, worktreePath, projectId)
        Resolve->>Resolve: loadSetupConfig → getResolvedTeardownCommands
        alt commands in config.json exist
            Resolve->>Resolve: buildTeardownCommandString(commands.join(' && '))
            Note over Resolve: exec bash -c '…' (same fish-safe trick as setup)
        else worktree has .superset/teardown.sh
            Resolve->>Resolve: buildTeardownInitialCommand(worktree script)
        else main repo has .superset/teardown.sh
            Resolve->>Resolve: buildTeardownInitialCommand(mainRepo script)
        else nothing configured
            Resolve->>Resolve: log skip, return null
        end
        Resolve-->>Backend: initialCommand or null

        alt initialCommand exists
            Backend->>Teardown: runTeardown(initialCommand, timeoutMs)
            Teardown->>Terminal: createSession + exec bash -c '…'
            Terminal-->>Teardown: exit status / timedOut
            Teardown-->>Backend: TeardownResult { status }

            alt status === "failed"
                alt force === false
                    Backend->>Backend: throw TRPCError (TEARDOWN_FAILED)
                    Backend-->>TRPC: error
                    TRPC-->>DestroySvc: error
                    DestroySvc-->>Dialog: error
                    Dialog-->>UI: show TeardownFailedPane
                    UI->>Dialog: onForceDelete() → run({ force: true, skipTeardown: true })
                else force === true
                    Backend->>Backend: log warning, add to warnings[]
                end
            else status === "ok"
                Backend->>Backend: teardownStatus = "ok"
            end
        else initialCommand null
            Backend->>Backend: log, teardownStatus = "skipped"
        end
    else skipTeardown === true
        Backend->>Backend: teardownStatus = "skipped"
        Note over Backend: Used only on retry after teardown failure
    end

    Backend->>Backend: continue local/cloud cleanup (unchanged)
    Backend-->>TRPC: result { teardownStatus, warnings, … }
    TRPC-->>DestroySvc: result
    DestroySvc-->>Dialog: result
    Dialog-->>UI: close dialog with teardownStatus
Loading

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

* still visible and delete can be retried instead of orphaning disk state.
*
* Force semantics:
* Force semantics ("delete despite dirty files" — NOT "skip teardown"):

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.

P2: The destroy-phase JSDoc list still says teardown is run .superset/teardown.sh and is skip if force, but both claims are now obsolete. The newly added Force semantics section below correctly says the opposite ("delete despite dirty files" — NOT "skip teardown"), and the PR description confirms teardown now resolves from overlaid config.json files (not just .superset/teardown.sh). Please update the phase list so it no longer contradicts the detailed semantics or the actual implementation: change the teardown line to reflect config-based resolution and replace skip if force with skip if skipTeardown.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/host-service/src/trpc/router/workspace-cleanup/workspace-cleanup.ts, line 147:

<comment>The destroy-phase JSDoc list still says teardown is `run .superset/teardown.sh` and is `skip if force`, but both claims are now obsolete. The newly added `Force semantics` section below correctly says the opposite (`"delete despite dirty files" — NOT "skip teardown"`), and the PR description confirms teardown now resolves from overlaid `config.json` files (not just `.superset/teardown.sh`). Please update the phase list so it no longer contradicts the detailed semantics or the actual implementation: change the teardown line to reflect config-based resolution and replace `skip if force` with `skip if skipTeardown`.</comment>

<file context>
@@ -142,14 +144,19 @@ export const workspaceCleanupRouter = router({
 	 * still visible and delete can be retried instead of orphaning disk state.
 	 *
-	 * Force semantics:
+	 * Force semantics ("delete despite dirty files" — NOT "skip teardown"):
 	 *   - skips preflight (step 0)
-	 *   - skips teardown  (step 1)
</file context>

@@ -0,0 +1,231 @@
# Run project teardown scripts on the v2 workspace delete path

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.

P3: The ExecPlan in plans/done/ contains two Open Questions that are already answered by Decisions D3 and D4 later in the same document. In a completed plan, these should be marked resolved or moved out of the Open Questions section so future readers don't re-escalate already-made product decisions.

Additionally, the Progress checklist leaves the "Manual marker-file scenario" item unchecked even though all other milestones are checked and the Outcomes section describes it as intentionally outstanding. For a living document that states its sections must be kept up to date, leaving this ambiguously unchecked in a done/ plan can suggest it was forgotten rather than deferred. Consider marking it [~] or [x] (deferred — automated coverage equivalent) to make intent explicit.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At plans/done/20260707-1351-v2-delete-teardown-resolution.md, line 25:

<comment>The ExecPlan in `plans/done/` contains two Open Questions that are already answered by Decisions D3 and D4 later in the same document. In a completed plan, these should be marked resolved or moved out of the Open Questions section so future readers don't re-escalate already-made product decisions.

Additionally, the Progress checklist leaves the "Manual marker-file scenario" item unchecked even though all other milestones are checked and the Outcomes section describes it as intentionally outstanding. For a living document that states its sections must be kept up to date, leaving this ambiguously unchecked in a `done/` plan can suggest it was forgotten rather than deferred. Consider marking it `[~]` or `[x] (deferred — automated coverage equivalent)` to make intent explicit.</comment>

<file context>
@@ -0,0 +1,231 @@
+- The 60-second teardown timeout (`TEARDOWN_TIMEOUT_MS` in `packages/shared/src/constants.ts:57`) stays as-is.
+- Backwards compatibility of the `destroy` input is required: existing callers pass only `{ workspaceId, deleteBranch, force }`, so the new `skipTeardown` field must default to `false`.
+
+## Open Questions
+
+- Should the legacy external `workspace.delete` procedure (CLI/SDK/MCP surface, `packages/host-service/src/trpc/router/workspace/workspace.ts:71-81`, which hard-codes `force: true`) now run teardown best-effort? This plan says yes (see Decision Log D3) — it makes SDK deletes take up to 60s longer if a teardown hangs, but skipping lifecycle scripts silently is the exact bug being fixed. If the product decision is "no", pass `skipTeardown: true` there instead and note it in the Decision Log. Impacts: Plan of Work step 4, Validation.
</file context>

…matching setup

Review feedback: config-array commands were wrapped in exec bash -c, so
commands authored for the user's shell (the contract setup uses) could
fail at delete when re-parsed by non-interactive bash. Join with ' && '
and type into the login shell like setup does; a trailing argless 'exit'
closes the hidden PTY and propagates the last status in bash/zsh/fish.
@ivanvan93 ivanvan93 closed this Jul 7, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
packages/host-service/src/runtime/teardown/teardown.test.ts (1)

68-76: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Silent skip hides fish-propagation coverage when fish is absent.

if (!isFishAvailable()) return; makes the test report as passed without ever exercising the assertion when fish isn't installed (e.g., in some CI images). Since this specifically verifies the exit-status-propagation contract highlighted in the PR's commit message, a silent pass could mask a real regression on machines lacking fish.

Consider using an explicit skip so it's visible in test output:

♻️ Proposed refactor using explicit skip
-	test("config command exit propagates the last status under fish", () => {
-		if (!isFishAvailable()) return;
-
-		const result = spawnSync("fish", [
+	test.skipIf(!isFishAvailable())("config command exit propagates the last status under fish", () => {
+		const result = spawnSync("fish", [
 			"-c",
 			buildTeardownCommandString(["sh -c 'exit 7'"]),
 		]);
 
 		expect(result.status).toBe(7);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/host-service/src/runtime/teardown/teardown.test.ts` around lines 68
- 76, The fish exit-status propagation test is silently passing when fish is
unavailable, which hides missing coverage. Update the test in teardown.test.ts
around the isFishAvailable check to use an explicit skip or equivalent visible
test skip mechanism instead of an early return, so the absence of fish is
reported clearly while preserving the existing spawnSync and
expect(result.status).toBe(7) assertion when fish is present.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@packages/host-service/src/runtime/teardown/teardown.test.ts`:
- Around line 68-76: The fish exit-status propagation test is silently passing
when fish is unavailable, which hides missing coverage. Update the test in
teardown.test.ts around the isFishAvailable check to use an explicit skip or
equivalent visible test skip mechanism instead of an early return, so the
absence of fish is reported clearly while preserving the existing spawnSync and
expect(result.status).toBe(7) assertion when fish is present.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 4c6404bb-ed64-499e-b1be-7030058c98aa

📥 Commits

Reviewing files that changed from the base of the PR and between 28f90aa and de1edcd.

📒 Files selected for processing (2)
  • packages/host-service/src/runtime/teardown/teardown.test.ts
  • packages/host-service/src/runtime/teardown/teardown.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant