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
112 changes: 13 additions & 99 deletions src/commands/restart.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,6 @@
import fs from 'node:fs/promises';
import { requireManifest, updateManifest, findAgent } from '../core/manifest.js';
import { loadConfig, resolveAgentConfig } from '../core/config.js';
import { spawnAgent, killAgent } from '../core/agent.js';
import { getRepoRoot } from '../core/worktree.js';
import * as tmux from '../core/tmux.js';
import { performRestart } from '../core/operations/restart.js';
import { openTerminalWindow } from '../core/terminal.js';
import { agentId as genAgentId, sessionId as genSessionId } from '../lib/id.js';
import { agentPromptFile } from '../lib/paths.js';
import { PpgError, AgentNotFoundError } from '../lib/errors.js';
import { output, success, info } from '../lib/output.js';
import { renderTemplate, type TemplateContext } from '../core/template.js';

export interface RestartOptions {
prompt?: string;
Expand All @@ -19,105 +10,28 @@ export interface RestartOptions {
}

export async function restartCommand(agentRef: string, options: RestartOptions): Promise<void> {
const projectRoot = await getRepoRoot();
const config = await loadConfig(projectRoot);

const manifest = await requireManifest(projectRoot);

const found = findAgent(manifest, agentRef);
if (!found) throw new AgentNotFoundError(agentRef);

const { worktree: wt, agent: oldAgent } = found;

// Kill old agent if still running
if (oldAgent.status === 'running') {
info(`Killing existing agent ${oldAgent.id}`);
await killAgent(oldAgent);
}

// Read original prompt from prompt file, or use override
let promptText: string;
if (options.prompt) {
promptText = options.prompt;
} else {
const pFile = agentPromptFile(projectRoot, oldAgent.id);
try {
promptText = await fs.readFile(pFile, 'utf-8');
} catch {
throw new PpgError(
`Could not read original prompt for agent ${oldAgent.id}. Use --prompt to provide one.`,
'PROMPT_NOT_FOUND',
);
}
}

// Resolve agent config
const agentConfig = resolveAgentConfig(config, options.agent ?? oldAgent.agentType);

// Ensure tmux session
await tmux.ensureSession(manifest.sessionName);

// Create new tmux window in same worktree
const newAgentId = genAgentId();
const windowTarget = await tmux.createWindow(manifest.sessionName, `${wt.name}-restart`, wt.path);

// Render template vars
const ctx: TemplateContext = {
WORKTREE_PATH: wt.path,
BRANCH: wt.branch,
AGENT_ID: newAgentId,
PROJECT_ROOT: projectRoot,
TASK_NAME: wt.name,
PROMPT: promptText,
};
const renderedPrompt = renderTemplate(promptText, ctx);

const newSessionId = genSessionId();
const agentEntry = await spawnAgent({
agentId: newAgentId,
agentConfig,
prompt: renderedPrompt,
worktreePath: wt.path,
tmuxTarget: windowTarget,
projectRoot,
branch: wt.branch,
sessionId: newSessionId,
});

// Update manifest: mark old agent as gone, add new agent
await updateManifest(projectRoot, (m) => {
const mWt = m.worktrees[wt.id];
if (mWt) {
const mOldAgent = mWt.agents[oldAgent.id];
if (mOldAgent && mOldAgent.status === 'running') {
mOldAgent.status = 'gone';
}
mWt.agents[newAgentId] = agentEntry;
}
return m;
const result = await performRestart({
agentRef,
prompt: options.prompt,
agentType: options.agent,
});

// Only open Terminal window when explicitly requested via --open (fire-and-forget)
if (options.open === true) {
openTerminalWindow(manifest.sessionName, windowTarget, `${wt.name}-restart`).catch(() => {});
openTerminalWindow(result.sessionName, result.newAgent.tmuxTarget, `${result.newAgent.worktreeName}-restart`).catch(() => {});
}

if (options.json) {
output({
success: true,
oldAgentId: oldAgent.id,
newAgent: {
id: newAgentId,
tmuxTarget: windowTarget,
sessionId: newSessionId,
worktreeId: wt.id,
worktreeName: wt.name,
branch: wt.branch,
path: wt.path,
},
oldAgentId: result.oldAgentId,
newAgent: result.newAgent,
}, true);
} else {
success(`Restarted agent ${oldAgent.id} → ${newAgentId} in worktree ${wt.name}`);
info(` New agent ${newAgentId} → ${windowTarget}`);
if (result.killedOldAgent) {
info(`Killed existing agent ${result.oldAgentId}`);
}
success(`Restarted agent ${result.oldAgentId} → ${result.newAgent.id} in worktree ${result.newAgent.worktreeName}`);
info(` New agent ${result.newAgent.id} → ${result.newAgent.tmuxTarget}`);
}
}
7 changes: 4 additions & 3 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 @@ -93,7 +94,7 @@ function createManifest(tmuxWindow = '') {
baseBranch: 'main',
status: 'active' as const,
tmuxWindow,
agents: {} as Record<string, any>,
agents: {},
createdAt: '2026-02-27T00:00:00.000Z',
},
},
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