-
-
Notifications
You must be signed in to change notification settings - Fork 253
fix(hooks): create real git worktrees and clean them up in worktree hooks #74
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
gepenniman
wants to merge
2
commits into
rohitg00:main
Choose a base branch
from
gepenniman:fix/worktree-hooks
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,29 +1,100 @@ | ||
| #!/usr/bin/env node | ||
| // WorktreeRemove hook: cleanup counterpart to worktree-create.js. | ||
| // Input (stdin JSON): { session_id, transcript_path, cwd, hook_event_name, | ||
| // worktree_path } where worktree_path is the path worktree-create.js echoed. | ||
| // Best-effort: remove the git worktree, delete the matching agents/* branch, | ||
| // prune stale admin entries, drop the ledger row. Never blocks the harness: | ||
| // always exits 0 and echoes stdin, matching the original script's contract. | ||
| const fs = require('fs'); | ||
| const path = require('path'); | ||
| const os = require('os'); | ||
| const { execFileSync } = require('child_process'); | ||
|
|
||
| const tempDir = path.join(os.tmpdir(), 'pro-workflow'); | ||
| const baseDir = path.join(tempDir, 'worktrees'); | ||
| const worktreeLog = path.join(tempDir, 'worktrees.json'); | ||
|
|
||
| const git = (args, cwd) => execFileSync('git', args, { | ||
| cwd: cwd || process.cwd(), | ||
| stdio: ['ignore', 'pipe', 'ignore'], | ||
| timeout: 8000 | ||
| }).toString().trim(); | ||
|
|
||
| const tryGit = (args, cwd) => { try { return git(args, cwd); } catch (e) { return null; } }; | ||
|
|
||
| function cleanup(input, raw) { | ||
| const wt = input.worktree_path || input.worktreePath || input.path || ''; | ||
|
|
||
| // Capture the raw payload so future harness schema changes are diagnosable. | ||
| try { | ||
| fs.mkdirSync(tempDir, { recursive: true }); | ||
| fs.appendFileSync(path.join(tempDir, 'worktree-remove.log'), | ||
| `${new Date().toISOString()} ${String(raw).replace(/\s+/g, ' ').slice(0, 2000)}\n`); | ||
| } catch (e) { /* ignore */ } | ||
|
|
||
| let ledger = []; | ||
| try { ledger = JSON.parse(fs.readFileSync(worktreeLog, 'utf8')); } catch (e) { ledger = []; } | ||
| if (!Array.isArray(ledger)) ledger = []; | ||
| const entry = ledger.find(w => w && w.worktree_path === wt) || null; | ||
|
|
||
| const resolved = wt ? path.resolve(wt) : ''; | ||
| // Only paths under our own baseDir are ever deleted from disk. | ||
| const ours = !!resolved && resolved.startsWith(baseDir + path.sep); | ||
|
|
||
| // Identify the branch before the directory disappears. Fallbacks cover the | ||
| // case where the harness (or a previous attempt) already removed the dir: | ||
| // the ledger row, then the create hook's own naming scheme. | ||
| let branch = null; | ||
| if (wt && fs.existsSync(wt)) branch = tryGit(['branch', '--show-current'], wt); | ||
| if (!branch && entry && typeof entry.branch === 'string') branch = entry.branch; | ||
| if (!branch && ours) branch = 'agents/' + path.basename(resolved); | ||
|
|
||
| // Locate the main repo: from the worktree's git-common-dir, the ledger, | ||
| // or the session cwd the payload carries. | ||
| let repo = null; | ||
| if (wt && fs.existsSync(wt)) { | ||
| const common = tryGit(['rev-parse', '--git-common-dir'], wt); | ||
| if (common) repo = path.dirname(path.resolve(wt, common)); | ||
| } | ||
| if (!repo && entry && typeof entry.repo === 'string' && fs.existsSync(entry.repo)) repo = entry.repo; | ||
| if (!repo && input.cwd && fs.existsSync(input.cwd)) repo = input.cwd; | ||
|
|
||
| // Only touch git state when we've confirmed ownership: either the path | ||
| // resolves under our own baseDir, or the ledger has a matching row for it. | ||
| // `repo` alone isn't enough to gate on — it can resolve via input.cwd (the | ||
| // session's cwd), which may be the user's main repo, not a worktree we made. | ||
| const owned = ours || !!entry; | ||
|
|
||
| if (owned) { | ||
| if (repo) tryGit(['worktree', 'remove', '--force', resolved], repo); | ||
| try { | ||
| if (fs.existsSync(resolved)) fs.rmSync(resolved, { recursive: true, force: true }); | ||
| } catch (e) { /* ignore */ } | ||
| } | ||
| if (owned && repo) { | ||
| tryGit(['worktree', 'prune'], repo); | ||
| // agents/* is the namespace worktree-create.js owns; never touch others. | ||
| if (branch && /^agents\//.test(branch)) tryGit(['branch', '-D', branch], repo); | ||
| } | ||
|
|
||
| try { | ||
| if (entry) { | ||
| fs.writeFileSync(worktreeLog, JSON.stringify(ledger.filter(w => w !== entry), null, 2)); | ||
| } | ||
| } catch (e) { /* ignore */ } | ||
|
|
||
| console.error(`[ProWorkflow] Worktree removed: ${wt || 'unknown'}${branch ? ` (branch ${branch})` : ''}`); | ||
| } | ||
|
|
||
| process.stdin.setEncoding('utf8'); | ||
| let data = ''; | ||
| process.stdin.on('data', chunk => { data += chunk; }); | ||
| process.stdin.on('end', () => { | ||
| try { | ||
| const input = JSON.parse(data); | ||
|
|
||
| console.error(`[ProWorkflow] Worktree removed: ${input.worktree_path || 'unknown'}`); | ||
|
|
||
| const tempDir = path.join(os.tmpdir(), 'pro-workflow'); | ||
| const worktreeLog = path.join(tempDir, 'worktrees.json'); | ||
| if (fs.existsSync(worktreeLog)) { | ||
| try { | ||
| let worktrees = JSON.parse(fs.readFileSync(worktreeLog, 'utf8')); | ||
| worktrees = worktrees.filter(w => w.worktree_path !== input.worktree_path); | ||
| fs.writeFileSync(worktreeLog, JSON.stringify(worktrees, null, 2)); | ||
| } catch (e) { /* ignore */ } | ||
| } | ||
|
|
||
| console.log(data); | ||
| } catch (err) { | ||
| console.log(data || '{}'); | ||
| } | ||
| let input = {}; | ||
| try { input = JSON.parse(data); } catch (e) { input = {}; } | ||
| try { cleanup(input, data); } catch (e) { /* cleanup is best-effort, never block */ } | ||
| // No process.exit() here: stdout to a pipe is written asynchronously by | ||
| // Node, and exit() doesn't wait for the flush. Letting the event loop drain | ||
| // naturally (no open handles remain) guarantees the payload isn't truncated. | ||
| console.log(data || '{}'); | ||
| }); | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.