Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
135 changes: 27 additions & 108 deletions src/commands/merge.ts
Original file line number Diff line number Diff line change
@@ -1,138 +1,57 @@
import { execa } from 'execa';
import { requireManifest, updateManifest, resolveWorktree } from '../core/manifest.js';
import { refreshAllAgentStatuses } from '../core/agent.js';
import { getRepoRoot, getCurrentBranch } from '../core/worktree.js';
import { cleanupWorktree } from '../core/cleanup.js';
import { getCurrentPaneId } from '../core/self.js';
import { listSessionPanes, type PaneInfo } from '../core/tmux.js';
import { PpgError, WorktreeNotFoundError, MergeFailedError } from '../lib/errors.js';
import { performMerge } from '../core/operations/merge.js';
import { getRepoRoot } from '../core/worktree.js';
import { output, success, info, warn } from '../lib/output.js';
import { execaEnv } from '../lib/env.js';

export interface MergeOptions {
export interface MergeCommandOptions {
strategy?: 'squash' | 'no-ff';
cleanup?: boolean;
dryRun?: boolean;
force?: boolean;
json?: boolean;
}

export async function mergeCommand(worktreeId: string, options: MergeOptions): Promise<void> {
export async function mergeCommand(worktreeId: string, options: MergeCommandOptions): Promise<void> {
const projectRoot = await getRepoRoot();

await requireManifest(projectRoot);
const manifest = await updateManifest(projectRoot, async (m) => {
return refreshAllAgentStatuses(m, projectRoot);
});

const wt = resolveWorktree(manifest, worktreeId);

if (!wt) throw new WorktreeNotFoundError(worktreeId);

// Check all agents finished
const agents = Object.values(wt.agents);
const incomplete = agents.filter((a) => a.status === 'running');

if (incomplete.length > 0 && !options.force) {
const ids = incomplete.map((a) => a.id).join(', ');
throw new PpgError(
`${incomplete.length} agent(s) still running: ${ids}. Use --force to merge anyway.`,
'AGENTS_RUNNING',
);
}

if (options.dryRun) {
info('Dry run — no changes will be made');
info(`Would merge branch ${wt.branch} into ${wt.baseBranch} using ${options.strategy ?? 'squash'} strategy`);
if (options.cleanup !== false) {
info(`Would remove worktree ${wt.id} and delete branch ${wt.branch}`);
}
return;
}

// Set worktree status to merging
await updateManifest(projectRoot, (m) => {
if (m.worktrees[wt.id]) {
m.worktrees[wt.id].status = 'merging';
}
return m;
const result = await performMerge({
projectRoot,
worktreeRef: worktreeId,
strategy: options.strategy,
cleanup: options.cleanup,
dryRun: options.dryRun,
force: options.force,
});

const strategy = options.strategy ?? 'squash';

try {
const currentBranch = await getCurrentBranch(projectRoot);
if (currentBranch !== wt.baseBranch) {
info(`Switching to base branch ${wt.baseBranch}`);
await execa('git', ['checkout', wt.baseBranch], { ...execaEnv, cwd: projectRoot });
}

info(`Merging ${wt.branch} into ${wt.baseBranch} (${strategy})`);

if (strategy === 'squash') {
await execa('git', ['merge', '--squash', wt.branch], { ...execaEnv, cwd: projectRoot });
await execa('git', ['commit', '-m', `ppg: merge ${wt.name} (${wt.branch})`], {
...execaEnv,
cwd: projectRoot,
});
} else {
await execa('git', ['merge', '--no-ff', wt.branch, '-m', `ppg: merge ${wt.name} (${wt.branch})`], {
...execaEnv,
cwd: projectRoot,
});
if (result.dryRun) {
info(`Would merge branch ${result.branch} into ${result.baseBranch} using ${result.strategy} strategy`);
if (options.cleanup !== false) {
info(`Would remove worktree ${result.worktreeId} and delete branch ${result.branch}`);
}

success(`Merged ${wt.branch} into ${wt.baseBranch}`);
} catch (err) {
await updateManifest(projectRoot, (m) => {
if (m.worktrees[wt.id]) {
m.worktrees[wt.id].status = 'failed';
}
return m;
});
throw new MergeFailedError(
`Merge failed: ${err instanceof Error ? err.message : err}`,
);
return;
}

// Mark as merged
await updateManifest(projectRoot, (m) => {
if (m.worktrees[wt.id]) {
m.worktrees[wt.id].status = 'merged';
m.worktrees[wt.id].mergedAt = new Date().toISOString();
}
return m;
});

// Cleanup with self-protection
let selfProtected = false;
if (options.cleanup !== false) {
info('Cleaning up...');

const selfPaneId = getCurrentPaneId();
let paneMap: Map<string, PaneInfo> | undefined;
if (selfPaneId) {
paneMap = await listSessionPanes(manifest.sessionName);
}

const cleanupResult = await cleanupWorktree(projectRoot, wt, { selfPaneId, paneMap });
selfProtected = cleanupResult.selfProtected;
success(`Merged ${result.branch} into ${result.baseBranch}`);

if (selfProtected) {
warn(`Some tmux targets skipped during cleanup — contains current ppg process`);
if (result.cleaned) {
if (result.selfProtected) {
warn('Some tmux targets skipped during cleanup — contains current ppg process');
}
success(`Cleaned up worktree ${wt.id}`);
success(`Cleaned up worktree ${result.worktreeId}`);
}

if (options.json) {
output({
success: true,
worktreeId: wt.id,
branch: wt.branch,
baseBranch: wt.baseBranch,
strategy,
cleaned: options.cleanup !== false,
selfProtected: selfProtected || undefined,
worktreeId: result.worktreeId,
branch: result.branch,
baseBranch: result.baseBranch,
strategy: result.strategy,
cleaned: result.cleaned,
selfProtected: result.selfProtected || undefined,
}, true);
}
Comment on lines 16 to 56

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

--json mode currently emits human logs and skips dry-run JSON output.

info/success/warn are emitted even when options.json is true, and the dry-run branch returns before the JSON payload is written. This breaks machine-readable command output.

✅ Suggested flow fix
 export async function mergeCommand(worktreeId: string, options: MergeCommandOptions): Promise<void> {
   const projectRoot = await getRepoRoot();
-  const strategy = options.strategy ?? 'squash';

-  if (options.dryRun) {
+  if (options.dryRun && !options.json) {
     info('Dry run — no changes will be made');
   }

   const result = await performMerge({
     projectRoot,
     worktreeRef: worktreeId,
     strategy: options.strategy,
     cleanup: options.cleanup,
     dryRun: options.dryRun,
     force: options.force,
   });

+  if (options.json) {
+    output({
+      success: true,
+      worktreeId: result.worktreeId,
+      branch: result.branch,
+      baseBranch: result.baseBranch,
+      strategy: result.strategy,
+      dryRun: result.dryRun,
+      merged: result.merged,
+      cleaned: result.cleaned,
+      selfProtected: result.selfProtected || undefined,
+    }, true);
+    return;
+  }
+
   if (result.dryRun) {
     info(`Would merge branch ${result.branch} into ${result.baseBranch} using ${result.strategy} strategy`);
     if (options.cleanup !== false) {
       info(`Would remove worktree ${result.worktreeId} and delete branch ${result.branch}`);
     }
     return;
   }

   success(`Merged ${result.branch} into ${result.baseBranch}`);

   if (result.cleaned) {
     if (result.selfProtected) {
       warn('Some tmux targets skipped during cleanup — contains current ppg process');
     }
     success(`Cleaned up worktree ${result.worktreeId}`);
   }
-
-  if (options.json) {
-    output({
-      success: true,
-      worktreeId: result.worktreeId,
-      branch: result.branch,
-      baseBranch: result.baseBranch,
-      strategy: result.strategy,
-      cleaned: result.cleaned,
-      selfProtected: result.selfProtected || undefined,
-    }, true);
-  }
 }

As per coding guidelines src/commands/**/*.ts: "Support --json flag on every command and use output(data, json) and outputError(error, json) for dual output".

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

In `@src/commands/merge.ts` around lines 17 - 57, The command currently always
emits human logs (info/success/warn) and returns early on dry-run before writing
JSON; update the post-merge flow to honor options.json: stop calling
info/success/warn when options.json is true and instead call output(...) with
the same payloads; specifically, for the dry-run branch (check result.dryRun)
write a JSON payload via output({ success: true, dryRun: true, worktreeId:
result.worktreeId, branch: result.branch, baseBranch: result.baseBranch,
strategy: result.strategy, cleaned: result.cleaned, selfProtected:
result.selfProtected || undefined }, true) and return, and for the non-dry-run
path replace the human success/cleanup messages with a single output(...) call
matching the schema already used (include success, worktreeId, branch,
baseBranch, strategy, cleaned, selfProtected) when options.json is true; leave
info/success/warn calls in place only when options.json is falsy.

}
5 changes: 3 additions & 2 deletions src/commands/spawn.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { spawnAgent } from '../core/agent.js';
import { getRepoRoot } from '../core/worktree.js';
import { agentId, sessionId } from '../lib/id.js';
import * as tmux from '../core/tmux.js';
import type { Manifest } from '../types/manifest.js';

vi.mock('node:fs/promises', async () => {
const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');
Expand Down Expand Up @@ -79,7 +80,7 @@ const mockedEnsureSession = vi.mocked(tmux.ensureSession);
const mockedCreateWindow = vi.mocked(tmux.createWindow);
const mockedSplitPane = vi.mocked(tmux.splitPane);

function createManifest(tmuxWindow = '') {
function createManifest(tmuxWindow = ''): Manifest {
return {
version: 1 as const,
projectRoot: '/tmp/repo',
Expand All @@ -103,7 +104,7 @@ function createManifest(tmuxWindow = '') {
}

describe('spawnCommand', () => {
let manifestState = createManifest();
let manifestState: Manifest = createManifest();
let nextAgent = 1;
let nextSession = 1;

Expand Down
Loading