Skip to content

feat: worktree auto cleanup - #94

Merged
fum4 merged 12 commits into
masterfrom
feat/worktree-auto-cleanup
Mar 22, 2026
Merged

fum4 merged 12 commits into
masterfrom
feat/worktree-auto-cleanup

Conversation

@fum4

@fum4 fum4 commented Mar 22, 2026 •

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features

    • Automatic worktree cleanup on PR merge or close (configurable per project)
    • PR state callback support to detect terminal transitions
  • Configuration

    • Local config file renamed to .openkit/config.local.json
    • New toggles: "Auto-delete on PR merge" and "Auto-delete on PR close"
  • Safety

    • Deletion skipped when worktree has uncommitted changes, unpushed commits, or no upstream
  • Activity & Notifications

    • Activity events and toasts for AUTO_CLEANUP and AUTO_CLEANUP_SKIPPED
  • Tests

    • Added coverage for PR transitions, auto-cleanup flows, and local-config handling

@fum4 fum4 self-assigned this Mar 22, 2026
@vercel

vercel Bot commented Mar 22, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
openkit Ignored Ignored Preview Mar 22, 2026 9:37pm

@coderabbitai

coderabbitai Bot commented Mar 22, 2026 •

Copy link
Copy Markdown

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds configurable automatic worktree cleanup on PR terminal transitions (merged/closed) with safety checks against cached git status, renames local config to config.local.json, wires GitHub polling to emit PR-state callbacks, adds activity event types, frontend toggles, and tests.

Changes

Cohort / File(s) Summary
Auto-cleanup core & wiring
apps/server/src/manager.ts, libs/integrations/src/github/github-manager.ts, libs/shared/src/activity-event.ts
Implements WorktreeManager.handlePrStateChange, adds onPrStateChange callback to GitHub polling, and introduces AUTO_CLEANUP / AUTO_CLEANUP_SKIPPED activity types and toast defaults.
Local config & schema
apps/server/src/local-config.ts, libs/shared/src/worktree-types.ts, apps/server/src/routes/config.ts
Renames persisted local config to config.local.json, adds autoCleanupOnPrMerge / autoCleanupOnPrClose to types, updates defaults/validation, and improves load error logging.
Manager integration & safety gates
apps/server/src/manager.ts
Merges local/global auto-cleanup flags into runtime and per-worktree configs; checks cached git status (uncommitted/ahead/no-upstream) before invoking removeWorktree; records AUTO_CLEANUP or AUTO_CLEANUP_SKIPPED events and logs warnings on failure.
Frontend UI & types
apps/web-app/src/components/ConfigurationPanel.tsx, apps/web-app/src/hooks/useConfig.ts, apps/web-app/src/hooks/useLocalConfig.ts
Adds UI toggles for auto-cleanup on PR merge/close and extends frontend config interfaces with the two optional boolean flags.
Tests
apps/server/src/__test__/auto-cleanup.test.ts, apps/server/src/__test__/github-manager-pr-callback.test.ts, apps/server/src/__test__/local-config.test.ts
Adds tests covering auto-cleanup decision logic (flags, git-status safety gate, events), GitHubManager PR-state callback behavior (including cold-start), and local-config parsing.
Docs & guides
docs/* (AGENTS.md, API.md, ARCHITECTURE.md, CONFIGURATION.md, DEVELOPMENT.md, FRONTEND.md, NOTIFICATIONS.md)
Updates references from local-config.json → config.local.json, documents new auto-cleanup fields and safety-gate behavior, and documents new activity event types and toast defaults.
Misc / tooling doc
.claude/skills/address-pr-review/SKILL.md
Unrelated doc edits expanding bot comment collection logic (documentation-only).

Sequence Diagram

sequenceDiagram
    participant Polling as GitHubManager (Polling)
    participant Cache as PR Cache
    participant Callback as onPrStateChange
    participant WM as WorktreeManager
    participant Git as Cached Git Status
    participant Remove as removeWorktree
    participant Log as ActivityLog / Logger

    Polling->>Cache: Detect PR transition (open → merged/closed)
    Note over Polling,Cache: ignore cold-start (initial terminal state)
    Polling->>Callback: Invoke onPrStateChange(worktreeId, oldState, newState)
    Callback->>WM: handlePrStateChange(worktreeId, oldState, newState)
    WM->>Git: Check cached git status for worktreeId
    alt Status shows uncommitted/ahead/no-upstream
        WM->>Log: Emit AUTO_CLEANUP_SKIPPED event and warning
    else Status clean or not cached
        WM->>Remove: removeWorktree(worktreeId)
        Remove-->>WM: { success: true/false, message }
        alt success:true
            WM->>Log: Emit AUTO_CLEANUP event
        else success:false
            WM->>Log: Emit warning with failure message and domain "auto-cleanup"
        end
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰 I hop through branches, neat and spry,
When PRs are merged or say goodbye.
I check for changes, ahead or stray —
If clean, I whisk the worktree away.
A tidy rabbit, happy to save the day. 🥕

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: worktree auto cleanup' directly and clearly describes the primary feature being added across the entire changeset—automatic cleanup of worktrees based on pull request state transitions.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/worktree-auto-cleanup

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

@github-actions

github-actions Bot commented Mar 22, 2026 •

Copy link
Copy Markdown
Contributor

Claude Review

🟠 Medium

  1. Race condition: PR cache updated after cleanup deletes the worktree (libs/integrations/src/github/github-manager.ts:188-210). The onPrStateChange callback calls removeWorktree(), which deletes the worktree. Then execution continues to line this.prCache.set(wt.id, pr) — caching PR data for a worktree that no longer exists. This is a minor memory leak (orphaned cache entries) and could cause confusing behavior if a new worktree reuses the same ID. Consider either clearing the cache entry after successful cleanup, or moving the cache update before the callback.

  2. No transition guard for terminal→terminal PR state changes in handlePrStateChange (apps/server/src/manager.ts:444-512). While github-manager.ts guards against non-terminal→terminal only, handlePrStateChange itself has no such guard — it's a public-ish method (accessible via (manager as any) in tests) that could be called with oldState="merged", newState="closed". Consider adding a defensive check, or making the method truly private and trusting the caller.

  3. Config file rename (local-config.json → config.local.json) is a breaking change with no migration (apps/server/src/local-config.ts:12). Existing users who upgrade will silently lose their local config settings (agent git policy, shortcuts, arrow nav). The old file will be orphaned and the new file will be initialized with defaults. Consider adding a one-time migration that renames the old file if it exists.

🟡 Minor

  1. Duplicate autoCleanupOnPrMerge/autoCleanupOnPrClose type definitions — the fields are defined in WorktreeConfig (libs/shared/src/worktree-types.ts), LocalConfig (apps/server/src/local-config.ts), useConfig.ts, and useLocalConfig.ts. The frontend types should ideally derive from the shared types to avoid drift.

  2. handlePrStateChange only checks config flags for merged and closed (apps/server/src/manager.ts:448-449). If newState is anything else (e.g., "draft" or "open"), the method silently proceeds to the safety-gate and cleanup logic. Consider returning early for non-terminal states, or at minimum adding a comment that the caller is expected to filter.

  3. Test uses (manager as any).handlePrStateChange (apps/server/src/__test__/auto-cleanup.test.ts). This couples tests to the private method name. If the method were exposed through a more testable seam (e.g., by triggering it via the PR state change callback path), the tests would be more resilient to refactoring.

  4. auto_cleanup added to default toast events (libs/shared/src/activity-event.ts:83). A successful auto-cleanup is an info-severity event — showing a toast for every merged-PR cleanup could be noisy for users with many worktrees. Consider whether auto_cleanup should default to feed-only, with only auto_cleanup_skipped as a toast.

🟢 Resolved

No previous review issues to track (prior review errored).

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (9)
libs/shared/src/activity-event.ts (1)

1-2: Missing JSDoc file comment.

As per coding guidelines, every source file must have a JSDoc comment at the top explaining what the file is for. This file defines activity event types, categories, severities, and default configuration for the activity logging system.

📝 Proposed JSDoc addition
+/**
+ * Defines activity event types, categories, severities, and default configuration
+ * for the activity logging system used to track worktree lifecycle and agent actions.
+ */
 export type ActivityCategory = "agent" | "worktree" | "system";
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@libs/shared/src/activity-event.ts` around lines 1 - 2, Add a top-of-file
JSDoc comment describing the purpose of this module (it defines activity event
types, categories, severities, and default configuration for the activity
logging system). Place the comment above the existing exports and reference the
module role and the exported types ActivityCategory and ActivitySeverity so
readers and tooling can understand the file intent.
apps/web-app/src/hooks/useConfig.ts (1)

1-5: Missing JSDoc file comment.

As per coding guidelines, every source file must have a JSDoc comment at the top explaining what the file is for.

📝 Proposed JSDoc addition
+/**
+ * React hook for fetching and managing project configuration state,
+ * including SSE-based real-time config change updates.
+ */
 import { useCallback, useEffect, useState } from "react";
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/web-app/src/hooks/useConfig.ts` around lines 1 - 5, Add a JSDoc block
comment at the top of this file (apps/web-app/src/hooks/useConfig.ts) describing
the purpose of the module: that it exports a React hook (useConfig) which
fetches application configuration from the API (uses apiFetchConfig), handles
server URL via useServerUrlOptional, and surfaces errors via
reportPersistentErrorToast; include author/maintainer and a brief description of
main behavior and exports to satisfy the project coding guidelines.
apps/server/src/__test__/github-manager-pr-callback.test.ts (1)

46-78: Consider adding a test for draft→merged transition.

The AI summary mentions that oldState is derived as "draft" when prev.isDraft is true, but there's no test coverage for this path. This would verify the isDraft handling in GitHubManager.startPolling.

💡 Example test case
it("calls onPrStateChange with 'draft' as oldState when previous PR was a draft", async () => {
  const worktree = { id: "feat-3", branch: "feat-3", status: "stopped" };
  mockGetWorktrees.mockReturnValue([worktree]);

  // First poll: PR is draft
  vi.mocked(ghClient.findPRForBranch).mockResolvedValueOnce({
    url: "https://github.com/test/repo/pull/3",
    number: 3,
    state: "open",
    isDraft: true,
    title: "feat",
  });

  manager.startPolling(mockGetWorktrees, mockOnUpdate, mockOnPrStateChange);
  await vi.advanceTimersByTimeAsync(100);

  // Second poll: PR is merged
  vi.mocked(ghClient.findPRForBranch).mockResolvedValueOnce({
    url: "https://github.com/test/repo/pull/3",
    number: 3,
    state: "merged",
    isDraft: false,
    title: "feat",
  });

  await vi.advanceTimersByTimeAsync(60_000);

  expect(mockOnPrStateChange).toHaveBeenCalledWith("feat-3", "draft", "merged");
});
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server/src/__test__/github-manager-pr-callback.test.ts` around lines 46
- 78, Add a unit test to cover the draft→merged transition so
GitHubManager.startPolling correctly maps prev.isDraft to "draft"; create a test
similar to the existing open→merged case that sets up a worktree (e.g., id
"feat-3"), mocks ghClient.findPRForBranch to first return an open PR with
isDraft: true and then a merged PR with isDraft: false, call
manager.startPolling(mockGetWorktrees, mockOnUpdate, mockOnPrStateChange),
advance timers for the initial poll and the subsequent poll, and assert
mockOnPrStateChange was called with ("feat-3", "draft", "merged").
apps/server/src/__test__/auto-cleanup.test.ts (1)

86-97: Consider using vi.spyOn for method mocking.

The current approach of reassigning manager.removeWorktree works, but using vi.spyOn is more idiomatic and preserves type safety:

vi.spyOn(manager, 'removeWorktree').mockResolvedValue({ success: true });

This is a minor stylistic suggestion.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server/src/__test__/auto-cleanup.test.ts` around lines 86 - 97, Replace
the direct reassignment of manager.removeWorktree in the beforeEach with a
vi.spyOn to preserve type safety and idiomatic mocking: use vi.spyOn(manager,
'removeWorktree').mockResolvedValue({ success: true }) instead of assigning
mockRemoveWorktree to manager.removeWorktree; keep mockAddEvent and
mockGetCachedGitStatus setup as-is and remove the standalone mockRemoveWorktree
variable if no longer needed so tests use the spy on the createManager instance.
apps/web-app/src/hooks/useLocalConfig.ts (1)

1-1: Add the required file-level JSDoc block.

Please add a short top-of-file JSDoc describing this hook’s responsibility.

As per coding guidelines: Every source file must have a JSDoc comment at the top explaining what the file is for (1-3 sentences). Update JSDoc when changing a file's responsibility.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/web-app/src/hooks/useLocalConfig.ts` at line 1, Add a top-of-file JSDoc
block (1–3 sentences) to describe this module's responsibility: state that the
file exports the useLocalConfig React hook which manages reading, writing, and
syncing local configuration settings (e.g., reading from localStorage and
providing setters) for the web app; place the JSDoc immediately above the import
statements in apps/web-app/src/hooks/useLocalConfig.ts and update it if the
hook's behavior changes.
apps/web-app/src/components/ConfigurationPanel.tsx (1)

1-1: Add a file-level JSDoc summary.

This TSX source file is missing the required top-level JSDoc description.

As per coding guidelines: Every source file must have a JSDoc comment at the top explaining what the file is for (1-3 sentences). Update JSDoc when changing a file's responsibility.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/web-app/src/components/ConfigurationPanel.tsx` at line 1, Add a
top-of-file JSDoc block (1–3 sentences) describing the purpose of this source
file and its primary exported component (ConfigurationPanel) — place it above
the first import (before the line "import Editor from
\"@monaco-editor/react\""). The JSDoc should succinctly state what the
ConfigurationPanel component does and when to update the comment if the file's
responsibility changes.
libs/integrations/src/github/github-manager.ts (1)

1-1: Add a file-level JSDoc header.

This source file is missing the required top-level JSDoc summary.

As per coding guidelines: Every source file must have a JSDoc comment at the top explaining what the file is for (1-3 sentences). Update JSDoc when changing a file's responsibility.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@libs/integrations/src/github/github-manager.ts` at line 1, Add a top-of-file
JSDoc block (1–3 sentences) describing the purpose and responsibilities of this
module (e.g., managing GitHub integrations/clients, operations provided) and
place it above the first import statement in github-manager.ts; keep it concise,
update it when the file’s responsibilities change, and ensure it follows the
project JSDoc style used elsewhere.
libs/shared/src/worktree-types.ts (1)

1-1: Add a file-level JSDoc header.

This file is missing the required top-of-file JSDoc summary (1–3 sentences).

As per coding guidelines: Every source file must have a JSDoc comment at the top explaining what the file is for (1-3 sentences). Update JSDoc when changing a file's responsibility.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@libs/shared/src/worktree-types.ts` at line 1, Add a top-of-file JSDoc comment
(1–3 sentences) describing the purpose of this module and its exported types;
place it above the existing exports (e.g., above the OpenProjectTarget type) and
ensure it briefly summarizes the file responsibility and when to update it.
apps/server/src/local-config.ts (1)

1-1: Add the required top-level JSDoc comment.

Please add a short file header explaining this module’s local-config responsibilities.

As per coding guidelines: Every source file must have a JSDoc comment at the top explaining what the file is for (1-3 sentences). Update JSDoc when changing a file's responsibility.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server/src/local-config.ts` at line 1, Add a top-level JSDoc header to
the local-config.ts module (the file that manages reading/writing local
configuration using fs functions like existsSync, mkdirSync, readFileSync,
writeFileSync). The JSDoc should be 1–3 sentences placed at the very top of the
file and briefly describe the module’s responsibilities (e.g., managing local
config storage, ensuring config directory exists, and reading/writing config
files), and update it whenever the file's responsibility changes.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/server/src/local-config.ts`:
- Line 8: Add a backward-compat migration that checks for the legacy filename
"local-config.json" and preserves its contents into the new
LOCAL_CONFIG_FILE_NAME ("config.local.json") before any code reads or writes
config; specifically, in the startup/load path that uses LOCAL_CONFIG_FILE_NAME,
detect if "local-config.json" exists and if "config.local.json" does not, read
the legacy file, validate/parse its JSON, write it to LOCAL_CONFIG_FILE_NAME
(atomic rename or write+fsync), and delete or back up the legacy file; ensure
you do not overwrite an existing config.local.json, handle JSON/IO errors with
proper logging, and reference the constant LOCAL_CONFIG_FILE_NAME and the legacy
string "local-config.json" so the migration is easy to find and test.

In `@docs/NOTIFICATIONS.md`:
- Around line 127-128: The doc change introduced an oxfmt formatting violation
in the Markdown table rows containing the entries `AUTO_CLEANUP` and
`AUTO_CLEANUP_SKIPPED`; run the repository's oxfmt formatter (or the project's
documented Markdown formatter) to reformat the modified documentation file so
the table complies with oxfmt rules, then recommit the formatted file.

In `@libs/integrations/src/github/github-manager.ts`:
- Around line 179-191: The catch block swallowing errors when invoking
onPrStateChange must log the failure with context; update the try/catch around
the onPrStateChange(wt.id, oldState, pr.state) call to catch (err) and call the
module logger (e.g., logger.error or log.error) including wt.id, oldState,
pr.state and the error object so callback failures aren’t silent—use the
existing logger used elsewhere in github-manager.ts to report the error and
retain the empty catch’s original intent of not breaking polling.

---

Nitpick comments:
In `@apps/server/src/__test__/auto-cleanup.test.ts`:
- Around line 86-97: Replace the direct reassignment of manager.removeWorktree
in the beforeEach with a vi.spyOn to preserve type safety and idiomatic mocking:
use vi.spyOn(manager, 'removeWorktree').mockResolvedValue({ success: true })
instead of assigning mockRemoveWorktree to manager.removeWorktree; keep
mockAddEvent and mockGetCachedGitStatus setup as-is and remove the standalone
mockRemoveWorktree variable if no longer needed so tests use the spy on the
createManager instance.

In `@apps/server/src/__test__/github-manager-pr-callback.test.ts`:
- Around line 46-78: Add a unit test to cover the draft→merged transition so
GitHubManager.startPolling correctly maps prev.isDraft to "draft"; create a test
similar to the existing open→merged case that sets up a worktree (e.g., id
"feat-3"), mocks ghClient.findPRForBranch to first return an open PR with
isDraft: true and then a merged PR with isDraft: false, call
manager.startPolling(mockGetWorktrees, mockOnUpdate, mockOnPrStateChange),
advance timers for the initial poll and the subsequent poll, and assert
mockOnPrStateChange was called with ("feat-3", "draft", "merged").

In `@apps/server/src/local-config.ts`:
- Line 1: Add a top-level JSDoc header to the local-config.ts module (the file
that manages reading/writing local configuration using fs functions like
existsSync, mkdirSync, readFileSync, writeFileSync). The JSDoc should be 1–3
sentences placed at the very top of the file and briefly describe the module’s
responsibilities (e.g., managing local config storage, ensuring config directory
exists, and reading/writing config files), and update it whenever the file's
responsibility changes.

In `@apps/web-app/src/components/ConfigurationPanel.tsx`:
- Line 1: Add a top-of-file JSDoc block (1–3 sentences) describing the purpose
of this source file and its primary exported component (ConfigurationPanel) —
place it above the first import (before the line "import Editor from
\"@monaco-editor/react\""). The JSDoc should succinctly state what the
ConfigurationPanel component does and when to update the comment if the file's
responsibility changes.

In `@apps/web-app/src/hooks/useConfig.ts`:
- Around line 1-5: Add a JSDoc block comment at the top of this file
(apps/web-app/src/hooks/useConfig.ts) describing the purpose of the module: that
it exports a React hook (useConfig) which fetches application configuration from
the API (uses apiFetchConfig), handles server URL via useServerUrlOptional, and
surfaces errors via reportPersistentErrorToast; include author/maintainer and a
brief description of main behavior and exports to satisfy the project coding
guidelines.

In `@apps/web-app/src/hooks/useLocalConfig.ts`:
- Line 1: Add a top-of-file JSDoc block (1–3 sentences) to describe this
module's responsibility: state that the file exports the useLocalConfig React
hook which manages reading, writing, and syncing local configuration settings
(e.g., reading from localStorage and providing setters) for the web app; place
the JSDoc immediately above the import statements in
apps/web-app/src/hooks/useLocalConfig.ts and update it if the hook's behavior
changes.

In `@libs/integrations/src/github/github-manager.ts`:
- Line 1: Add a top-of-file JSDoc block (1–3 sentences) describing the purpose
and responsibilities of this module (e.g., managing GitHub integrations/clients,
operations provided) and place it above the first import statement in
github-manager.ts; keep it concise, update it when the file’s responsibilities
change, and ensure it follows the project JSDoc style used elsewhere.

In `@libs/shared/src/activity-event.ts`:
- Around line 1-2: Add a top-of-file JSDoc comment describing the purpose of
this module (it defines activity event types, categories, severities, and
default configuration for the activity logging system). Place the comment above
the existing exports and reference the module role and the exported types
ActivityCategory and ActivitySeverity so readers and tooling can understand the
file intent.

In `@libs/shared/src/worktree-types.ts`:
- Line 1: Add a top-of-file JSDoc comment (1–3 sentences) describing the purpose
of this module and its exported types; place it above the existing exports
(e.g., above the OpenProjectTarget type) and ensure it briefly summarizes the
file responsibility and when to update it.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2982bb73-b7f3-43ef-ae05-07524ed3b47f

📥 Commits

Reviewing files that changed from the base of the PR and between 36d7aae and 02d01c1.

📒 Files selected for processing (19)
  • apps/server/src/__test__/auto-cleanup.test.ts
  • apps/server/src/__test__/github-manager-pr-callback.test.ts
  • apps/server/src/__test__/local-config.test.ts
  • apps/server/src/local-config.ts
  • apps/server/src/manager.ts
  • apps/server/src/routes/config.ts
  • apps/web-app/src/components/ConfigurationPanel.tsx
  • apps/web-app/src/hooks/useConfig.ts
  • apps/web-app/src/hooks/useLocalConfig.ts
  • docs/AGENTS.md
  • docs/API.md
  • docs/ARCHITECTURE.md
  • docs/CONFIGURATION.md
  • docs/DEVELOPMENT.md
  • docs/FRONTEND.md
  • docs/NOTIFICATIONS.md
  • libs/integrations/src/github/github-manager.ts
  • libs/shared/src/activity-event.ts
  • libs/shared/src/worktree-types.ts

Comment thread apps/server/src/local-config.ts Resolved
Comment thread docs/NOTIFICATIONS.md Resolved
- log onPrStateChange callback errors instead of silently swallowing them
- add auto-cleanup to toast events so users are notified on worktree deletion
- include PR state transition (old → new) in logs and activity events
- migrate old local-config.json to config.local.json on startup
- add explicit vitest imports in github-manager-pr-callback test

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
libs/integrations/src/github/github-manager.ts (2)

180-197: Error handling improvement looks good — consider adding state values to log context.

The terminal transition logic correctly guards against cold-start invocations and the try/catch now logs meaningful context, addressing the previous review concern about silent failures.

For enhanced debuggability, consider including the state values in the warning:

🔧 Optional: include state values in log context
               try {
                 onPrStateChange(wt.id, oldState, pr.state);
               } catch (err) {
                 log.warn("onPrStateChange callback failed", {
                   domain: "GitHub",
                   worktreeId: wt.id,
+                  oldState,
+                  newState: pr.state,
                   error: err instanceof Error ? err.message : String(err),
                 });
               }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@libs/integrations/src/github/github-manager.ts` around lines 180 - 197,
Include the previous and current PR state in the warning context when the
onPrStateChange callback throws: inside the try/catch around
onPrStateChange(wt.id, oldState, pr.state) add prev/current state values
(oldState and pr.state) to the log.warn metadata so the log entry includes
domain, worktreeId (wt.id), oldState, newState, and the error (err.message or
String(err)) to aid debugging.

1-21: Consider adding a JSDoc header describing the module's purpose.

The file lacks a top-level JSDoc comment. Since this PR extends the module's responsibility with PR state change notifications, this would be a good opportunity to document its purpose.

📝 Suggested JSDoc header
+/**
+ * Manages GitHub integration including PR polling, git status tracking,
+ * and worktree lifecycle callbacks on PR state transitions.
+ */
 import type { WorktreeInfo } from "@openkit/shared/worktree-types";

As per coding guidelines: "Every source file must have a JSDoc comment at the top explaining what the file is for (1-3 sentences). Update JSDoc when changing a file's responsibility."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@libs/integrations/src/github/github-manager.ts` around lines 1 - 21, Add a
top-level JSDoc comment to this module (github-manager) that briefly (1–3
sentences) describes its responsibility: coordinating GitHub integration actions
(using functions like createPR, findPRForBranch, createGitHubRepo, pushBranch,
commitAll, etc.), exposing config/types such as GitHubConfig and PRInfo, and
emitting PR state change notifications; place the JSDoc at the very top of the
file so it documents the module’s purpose and mentions the new PR state change
notification responsibility.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/server/src/local-config.ts`:
- Line 1: Add a 1–3 sentence top-level JSDoc comment at the very start of
local-config.ts describing the file's responsibility (e.g., managing local
configuration files and utilities used in this module). Place it above the
existing import line so it precedes imports like existsSync, mkdirSync,
readFileSync, renameSync, and writeFileSync; keep the comment concise and in
JSDoc format (/** ... */).
- Around line 72-78: Wrap the migration rename (existsSync(oldPath) &&
!existsSync(newPath) { renameSync(oldPath, newPath) }) in a try/catch and log a
clear error if renameSync fails, including operation, oldPath, newPath and the
caught error; likewise, in the JSON read/parse fallback that currently returns
{} (the parse/read failure branch around the getLocalConfig/getLocalConfigPath
logic), log a warn/error with the file path and error before returning the empty
object so failures are visible in logs. Ensure you call the module logger (e.g.,
log.warn/log.error) and reference the same symbols (configDirPath, oldPath,
newPath, renameSync and the read/parse code path) when adding the log calls.

---

Nitpick comments:
In `@libs/integrations/src/github/github-manager.ts`:
- Around line 180-197: Include the previous and current PR state in the warning
context when the onPrStateChange callback throws: inside the try/catch around
onPrStateChange(wt.id, oldState, pr.state) add prev/current state values
(oldState and pr.state) to the log.warn metadata so the log entry includes
domain, worktreeId (wt.id), oldState, newState, and the error (err.message or
String(err)) to aid debugging.
- Around line 1-21: Add a top-level JSDoc comment to this module
(github-manager) that briefly (1–3 sentences) describes its responsibility:
coordinating GitHub integration actions (using functions like createPR,
findPRForBranch, createGitHubRepo, pushBranch, commitAll, etc.), exposing
config/types such as GitHubConfig and PRInfo, and emitting PR state change
notifications; place the JSDoc at the very top of the file so it documents the
module’s purpose and mentions the new PR state change notification
responsibility.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 89410500-8d6c-4d00-8dc5-66ce13f1555b

📥 Commits

Reviewing files that changed from the base of the PR and between 02d01c1 and d545833.

📒 Files selected for processing (6)
  • apps/server/src/__test__/github-manager-pr-callback.test.ts
  • apps/server/src/local-config.ts
  • apps/server/src/manager.ts
  • docs/NOTIFICATIONS.md
  • libs/integrations/src/github/github-manager.ts
  • libs/shared/src/activity-event.ts
✅ Files skipped from review due to trivial changes (1)
  • docs/NOTIFICATIONS.md
🚧 Files skipped from review as they are similar to previous changes (3)
  • libs/shared/src/activity-event.ts
  • apps/server/src/test/github-manager-pr-callback.test.ts
  • apps/server/src/manager.ts

Comment thread apps/server/src/local-config.ts Resolved
Comment thread apps/server/src/local-config.ts Outdated
Comment on lines +72 to +78
// Migrate old local-config.json → config.local.json
const configDirPath = path.join(configDir, CONFIG_DIR_NAME);
const oldPath = path.join(configDirPath, "local-config.json");
const newPath = getLocalConfigPath(configDir);
if (existsSync(oldPath) && !existsSync(newPath)) {
renameSync(oldPath, newPath);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Migration/read failures are silently handled and not logged.

Line 77 can throw during rename, and Lines 134-135 swallow parse/read failures by returning {} with no telemetry. This can silently reset effective local behavior and makes debugging hard. Please handle these paths with log.warn/log.error context (operation + paths + error).

As per coding guidelines **/*.{ts,tsx,js,jsx}: Every catch block, fallback branch, and error callback must do something meaningful: log through logger (log.error()/log.warn()) or surface to user via toast.

Also applies to: 132-135

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server/src/local-config.ts` around lines 72 - 78, Wrap the migration
rename (existsSync(oldPath) && !existsSync(newPath) { renameSync(oldPath,
newPath) }) in a try/catch and log a clear error if renameSync fails, including
operation, oldPath, newPath and the caught error; likewise, in the JSON
read/parse fallback that currently returns {} (the parse/read failure branch
around the getLocalConfig/getLocalConfigPath logic), log a warn/error with the
file path and error before returning the empty object so failures are visible in
logs. Ensure you call the module logger (e.g., log.warn/log.error) and reference
the same symbols (configDirPath, oldPath, newPath, renameSync and the read/parse
code path) when adding the log calls.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In @.claude/skills/address-pr-review/SKILL.md:
- Line 35: The doc uses inconsistent placeholder names: it tells readers to
extract `owner` and `name` but later uses `{repo}` in commands; update the text
so placeholders are consistent—use `{owner}` and `{name}` everywhere (replace
occurrences of `{repo}` with `{name}`) and adjust the earlier sentence to
clearly state "extract `owner` and `name` for API calls" to match the command
examples.
- Around line 42-43: The gh API calls that fetch comments ("gh api
repos/{owner}/{repo}/issues/{number}/comments" and "gh api
repos/{owner}/{repo}/pulls/{number}/comments") need to use pagination so you
don't miss older pages; update both calls to add the --paginate flag and ensure
the code that selects the latest bot review/comment iterates over the combined
paginated results (rather than assuming a single page). Keep the same
parsing/filtering logic but feed it the full --paginate output so the "latest
comment" lookup correctly finds the most recent bot feedback.

In `@libs/integrations/src/github/github-manager.ts`:
- Around line 19-20: Add a module-level JSDoc comment (1–3 sentences) at the
very top of github-manager.ts (above the imports) briefly describing the file's
responsibility — e.g., managing GitHub integration helpers and types used for PR
and status handling — and update that comment whenever the file's responsibility
changes; ensure the JSDoc sits above the existing imports (log, GitHubConfig,
GitStatusInfo, PRInfo) so linters and reviewers recognize the header.
- Around line 184-200: The onPrStateChange callback is currently invoked
whenever the new PR state is terminal, even if the previous cached state was
already terminal; change the guard around the callback (the if block using
onPrStateChange, prev, pr, and pr.state) to only fire for transitions from a
non-terminal previous state to a terminal new state by ensuring prev is not
terminal (i.e., prev.state !== "merged" && prev.state !== "closed") before
calling await onPrStateChange(wt.id, oldState, pr.state); keep the existing
prev.isDraft handling for oldState and the try/catch logging.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 0849abc9-3a50-45f4-915d-f7674fd79ff2

📥 Commits

Reviewing files that changed from the base of the PR and between c2f0ab4 and 058888c.

📒 Files selected for processing (5)
  • .claude/skills/address-pr-review/SKILL.md
  • docs/CONFIGURATION.md
  • docs/NOTIFICATIONS.md
  • libs/integrations/src/github/github-manager.ts
  • libs/shared/src/activity-event.ts
✅ Files skipped from review due to trivial changes (1)
  • libs/shared/src/activity-event.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • docs/NOTIFICATIONS.md
  • docs/CONFIGURATION.md

@@ -34,21 +34,24 @@ gh repo view --json owner,name

Extract `owner` and `name` for API calls.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Use consistent placeholder naming for repository identifier.

Line 35 says extract name, but Lines 42-43 use {repo}. This inconsistency can cause incorrect command templating when someone follows the steps literally.

Proposed doc update
-Extract `owner` and `name` for API calls.
+Extract `owner` and `repo` (repository name) for API calls.

Also applies to: 42-43

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.claude/skills/address-pr-review/SKILL.md at line 35, The doc uses
inconsistent placeholder names: it tells readers to extract `owner` and `name`
but later uses `{repo}` in commands; update the text so placeholders are
consistent—use `{owner}` and `{name}` everywhere (replace occurrences of
`{repo}` with `{name}`) and adjust the earlier sentence to clearly state
"extract `owner` and `name` for API calls" to match the command examples.

- guard onPrStateChange to only fire on non-terminal → terminal state changes
  (metadata-only updates on already-merged PRs could re-trigger cleanup)
- add --paginate to gh api calls in address-pr-review skill
  (PRs with >30 comments would miss the latest review)
- add JSDoc header to github-manager.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@libs/integrations/src/github/github-manager.ts`:
- Around line 188-210: The onPrStateChange callback is awaited before updating
prCache which allows overlapping pollPRs to read the stale cache and fire
duplicate terminal callbacks; move the prCache update to before
invoking/awaiting onPrStateChange. Specifically, in the poll/processing block
that references prev, pr, wt.id, and calls onPrStateChange(wt.id, oldState,
pr.state), call this.prCache.set(wt.id, pr) immediately after computing pr (and
before the isTerminalTransition check or at least before awaiting the callback),
then call await onPrStateChange inside a try/catch as before so the cache
remains current even if the callback throws.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: feaba81c-8214-43a5-9175-22d562b6c37f

📥 Commits

Reviewing files that changed from the base of the PR and between 058888c and 7a5627a.

📒 Files selected for processing (2)
  • .claude/skills/address-pr-review/SKILL.md
  • libs/integrations/src/github/github-manager.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • .claude/skills/address-pr-review/SKILL.md

Comment on lines +188 to 210
// Fire state-change callback for non-terminal → terminal transitions only
if (onPrStateChange && prev && pr) {
const oldState = prev.isDraft ? "draft" : prev.state;
const isTerminalTransition =
(pr.state === "merged" || pr.state === "closed") &&
oldState !== "merged" &&
oldState !== "closed";

if (isTerminalTransition) {
try {
await onPrStateChange(wt.id, oldState, pr.state);
} catch (err) {
log.warn("onPrStateChange callback failed", {
domain: "GitHub",
worktreeId: wt.id,
oldState,
newState: pr.state,
error: err instanceof Error ? err.message : String(err),
});
}
}
}
this.prCache.set(wt.id, pr);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Prevent duplicate terminal callbacks under overlapping PR polls.

At Line 198, await onPrStateChange(...) runs before cache update at Line 210. If a later pollPRs tick starts meanwhile, it can still read the old cached state and fire cleanup again.

🔧 Suggested fix (update cache before awaiting callback)
           if (prChanged) {
             // Fire state-change callback for non-terminal → terminal transitions only
             if (onPrStateChange && prev && pr) {
               const oldState = prev.isDraft ? "draft" : prev.state;
               const isTerminalTransition =
                 (pr.state === "merged" || pr.state === "closed") &&
                 oldState !== "merged" &&
                 oldState !== "closed";

               if (isTerminalTransition) {
+                // Advance cache first to avoid duplicate callback on overlapping polls.
+                this.prCache.set(wt.id, pr);
+                changed = true;
                 try {
                   await onPrStateChange(wt.id, oldState, pr.state);
                 } catch (err) {
                   log.warn("onPrStateChange callback failed", {
                     domain: "GitHub",
                     worktreeId: wt.id,
                     oldState,
                     newState: pr.state,
                     error: err instanceof Error ? err.message : String(err),
                   });
                 }
+                continue;
               }
             }
             this.prCache.set(wt.id, pr);
             changed = true;
           }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@libs/integrations/src/github/github-manager.ts` around lines 188 - 210, The
onPrStateChange callback is awaited before updating prCache which allows
overlapping pollPRs to read the stale cache and fire duplicate terminal
callbacks; move the prCache update to before invoking/awaiting onPrStateChange.
Specifically, in the poll/processing block that references prev, pr, wt.id, and
calls onPrStateChange(wt.id, oldState, pr.state), call this.prCache.set(wt.id,
pr) immediately after computing pr (and before the isTerminalTransition check or
at least before awaiting the callback), then call await onPrStateChange inside a
try/catch as before so the cache remains current even if the callback throws.

@fum4
fum4 merged commit 4add5b4 into master Mar 22, 2026
23 checks passed
@fum4
fum4 deleted the feat/worktree-auto-cleanup branch March 22, 2026 21:43
This was referenced Mar 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant