Merge branch 'main' into feature-dependency-improvements

This commit is contained in:
Cody Seibert
2025-12-17 00:23:59 -05:00
98 changed files with 13081 additions and 767 deletions

View File

@@ -0,0 +1,84 @@
/**
* Automaker Paths - Utilities for managing automaker data storage
*
* Stores project data inside the project directory at {projectPath}/.automaker/
*/
import fs from "fs/promises";
import path from "path";
/**
* Get the automaker data directory for a project
* This is stored inside the project at .automaker/
*/
export function getAutomakerDir(projectPath: string): string {
return path.join(projectPath, ".automaker");
}
/**
* Get the features directory for a project
*/
export function getFeaturesDir(projectPath: string): string {
return path.join(getAutomakerDir(projectPath), "features");
}
/**
* Get the directory for a specific feature
*/
export function getFeatureDir(projectPath: string, featureId: string): string {
return path.join(getFeaturesDir(projectPath), featureId);
}
/**
* Get the images directory for a feature
*/
export function getFeatureImagesDir(
projectPath: string,
featureId: string
): string {
return path.join(getFeatureDir(projectPath, featureId), "images");
}
/**
* Get the board directory for a project (board backgrounds, etc.)
*/
export function getBoardDir(projectPath: string): string {
return path.join(getAutomakerDir(projectPath), "board");
}
/**
* Get the images directory for a project (general images)
*/
export function getImagesDir(projectPath: string): string {
return path.join(getAutomakerDir(projectPath), "images");
}
/**
* Get the worktrees metadata directory for a project
*/
export function getWorktreesDir(projectPath: string): string {
return path.join(getAutomakerDir(projectPath), "worktrees");
}
/**
* Get the app spec file path for a project
*/
export function getAppSpecPath(projectPath: string): string {
return path.join(getAutomakerDir(projectPath), "app_spec.txt");
}
/**
* Get the branch tracking file path for a project
*/
export function getBranchTrackingPath(projectPath: string): string {
return path.join(getAutomakerDir(projectPath), "active-branches.json");
}
/**
* Ensure the automaker directory structure exists for a project
*/
export async function ensureAutomakerDir(projectPath: string): Promise<string> {
const automakerDir = getAutomakerDir(projectPath);
await fs.mkdir(automakerDir, { recursive: true });
return automakerDir;
}

View File

@@ -0,0 +1,67 @@
/**
* File system utilities that handle symlinks safely
*/
import fs from "fs/promises";
import path from "path";
/**
* Create a directory, handling symlinks safely to avoid ELOOP errors.
* If the path already exists as a directory or symlink, returns success.
*/
export async function mkdirSafe(dirPath: string): Promise<void> {
const resolvedPath = path.resolve(dirPath);
// Check if path already exists using lstat (doesn't follow symlinks)
try {
const stats = await fs.lstat(resolvedPath);
// Path exists - if it's a directory or symlink, consider it success
if (stats.isDirectory() || stats.isSymbolicLink()) {
return;
}
// It's a file - can't create directory
throw new Error(`Path exists and is not a directory: ${resolvedPath}`);
} catch (error: any) {
// ENOENT means path doesn't exist - we should create it
if (error.code !== "ENOENT") {
// Some other error (could be ELOOP in parent path)
// If it's ELOOP, the path involves symlinks - don't try to create
if (error.code === "ELOOP") {
console.warn(`[fs-utils] Symlink loop detected at ${resolvedPath}, skipping mkdir`);
return;
}
throw error;
}
}
// Path doesn't exist, create it
try {
await fs.mkdir(resolvedPath, { recursive: true });
} catch (error: any) {
// Handle race conditions and symlink issues
if (error.code === "EEXIST" || error.code === "ELOOP") {
return;
}
throw error;
}
}
/**
* Check if a path exists, handling symlinks safely.
* Returns true if the path exists as a file, directory, or symlink.
*/
export async function existsSafe(filePath: string): Promise<boolean> {
try {
await fs.lstat(filePath);
return true;
} catch (error: any) {
if (error.code === "ENOENT") {
return false;
}
// ELOOP or other errors - path exists but is problematic
if (error.code === "ELOOP") {
return true; // Symlink exists, even if looping
}
throw error;
}
}

View File

@@ -3,13 +3,13 @@
*/
import { query } from "@anthropic-ai/claude-agent-sdk";
import path from "path";
import fs from "fs/promises";
import type { EventEmitter } from "../../lib/events.js";
import { createLogger } from "../../lib/logger.js";
import { createFeatureGenerationOptions } from "../../lib/sdk-options.js";
import { logAuthStatus } from "./common.js";
import { parseAndCreateFeatures } from "./parse-and-create-features.js";
import { getAppSpecPath } from "../../lib/automaker-paths.js";
const logger = createLogger("SpecRegeneration");
@@ -26,8 +26,8 @@ export async function generateFeaturesFromSpec(
logger.debug("projectPath:", projectPath);
logger.debug("maxFeatures:", featureCount);
// Read existing spec
const specPath = path.join(projectPath, ".automaker", "app_spec.txt");
// Read existing spec from .automaker directory
const specPath = getAppSpecPath(projectPath);
let spec: string;
logger.debug("Reading spec from:", specPath);

View File

@@ -11,6 +11,7 @@ import { createLogger } from "../../lib/logger.js";
import { createSpecGenerationOptions } from "../../lib/sdk-options.js";
import { logAuthStatus } from "./common.js";
import { generateFeaturesFromSpec } from "./generate-features-from-spec.js";
import { ensureAutomakerDir, getAppSpecPath } from "../../lib/automaker-paths.js";
const logger = createLogger("SpecRegeneration");
@@ -209,14 +210,13 @@ ${getAppSpecFormatInstruction()}`;
logger.error("❌ WARNING: responseText is empty! Nothing to save.");
}
// Save spec
const specDir = path.join(projectPath, ".automaker");
const specPath = path.join(specDir, "app_spec.txt");
// Save spec to .automaker directory
const specDir = await ensureAutomakerDir(projectPath);
const specPath = getAppSpecPath(projectPath);
logger.info("Saving spec to:", specPath);
logger.info(`Content to save (${responseText.length} chars)`);
await fs.mkdir(specDir, { recursive: true });
await fs.writeFile(specPath, responseText);
// Verify the file was written

View File

@@ -22,3 +22,4 @@ export function createSpecRegenerationRoutes(events: EventEmitter): Router {
return router;
}

View File

@@ -6,6 +6,7 @@ import path from "path";
import fs from "fs/promises";
import type { EventEmitter } from "../../lib/events.js";
import { createLogger } from "../../lib/logger.js";
import { getFeaturesDir } from "../../lib/automaker-paths.js";
const logger = createLogger("SpecRegeneration");
@@ -41,7 +42,7 @@ export async function parseAndCreateFeatures(
logger.info(`Parsed ${parsed.features?.length || 0} features`);
logger.info("Parsed features:", JSON.stringify(parsed.features, null, 2));
const featuresDir = path.join(projectPath, ".automaker", "features");
const featuresDir = getFeaturesDir(projectPath);
await fs.mkdir(featuresDir, { recursive: true });
const createdFeatures: Array<{ id: string; title: string }> = [];

View File

@@ -9,9 +9,10 @@ import { getErrorMessage, logError } from "../common.js";
export function createCommitFeatureHandler(autoModeService: AutoModeService) {
return async (req: Request, res: Response): Promise<void> => {
try {
const { projectPath, featureId } = req.body as {
const { projectPath, featureId, worktreePath } = req.body as {
projectPath: string;
featureId: string;
worktreePath?: string;
};
if (!projectPath || !featureId) {
@@ -26,7 +27,8 @@ export function createCommitFeatureHandler(autoModeService: AutoModeService) {
const commitHash = await autoModeService.commitFeature(
projectPath,
featureId
featureId,
worktreePath
);
res.json({ success: true, commitHash });
} catch (error) {

View File

@@ -12,11 +12,12 @@ const logger = createLogger("AutoMode");
export function createFollowUpFeatureHandler(autoModeService: AutoModeService) {
return async (req: Request, res: Response): Promise<void> => {
try {
const { projectPath, featureId, prompt, imagePaths } = req.body as {
const { projectPath, featureId, prompt, imagePaths, worktreePath } = req.body as {
projectPath: string;
featureId: string;
prompt: string;
imagePaths?: string[];
worktreePath?: string;
};
if (!projectPath || !featureId || !prompt) {
@@ -27,9 +28,9 @@ export function createFollowUpFeatureHandler(autoModeService: AutoModeService) {
return;
}
// Start follow-up in background
// Start follow-up in background, using the feature's worktreePath for correct branch
autoModeService
.followUpFeature(projectPath, featureId, prompt, imagePaths)
.followUpFeature(projectPath, featureId, prompt, imagePaths, worktreePath)
.catch((error) => {
logger.error(
`[AutoMode] Follow up feature ${featureId} error:`,

View File

@@ -29,8 +29,9 @@ export function createResumeFeatureHandler(autoModeService: AutoModeService) {
}
// Start resume in background
// Default to false - worktrees should only be used when explicitly enabled
autoModeService
.resumeFeature(projectPath, featureId, useWorktrees ?? true)
.resumeFeature(projectPath, featureId, useWorktrees ?? false)
.catch((error) => {
logger.error(`[AutoMode] Resume feature ${featureId} error:`, error);
});

View File

@@ -12,10 +12,11 @@ const logger = createLogger("AutoMode");
export function createRunFeatureHandler(autoModeService: AutoModeService) {
return async (req: Request, res: Response): Promise<void> => {
try {
const { projectPath, featureId, useWorktrees } = req.body as {
const { projectPath, featureId, useWorktrees, worktreePath } = req.body as {
projectPath: string;
featureId: string;
useWorktrees?: boolean;
worktreePath?: string;
};
if (!projectPath || !featureId) {
@@ -29,8 +30,10 @@ export function createRunFeatureHandler(autoModeService: AutoModeService) {
}
// Start execution in background
// If worktreePath is provided, use it directly; otherwise let the service decide
// Default to false - worktrees should only be used when explicitly enabled
autoModeService
.executeFeature(projectPath, featureId, useWorktrees ?? true, false)
.executeFeature(projectPath, featureId, useWorktrees ?? false, false, worktreePath)
.catch((error) => {
logger.error(`[AutoMode] Feature ${featureId} error:`, error);
});

View File

@@ -6,6 +6,7 @@ import type { Request, Response } from "express";
import fs from "fs/promises";
import path from "path";
import { getErrorMessage, logError } from "../common.js";
import { getBoardDir } from "../../../lib/automaker-paths.js";
export function createDeleteBoardBackgroundHandler() {
return async (req: Request, res: Response): Promise<void> => {
@@ -20,10 +21,11 @@ export function createDeleteBoardBackgroundHandler() {
return;
}
const boardDir = path.join(projectPath, ".automaker", "board");
// Get board directory
const boardDir = getBoardDir(projectPath);
try {
// Try to remove all files in the board directory
// Try to remove all background files in the board directory
const files = await fs.readdir(boardDir);
for (const file of files) {
if (file.startsWith("background")) {

View File

@@ -1,5 +1,6 @@
/**
* POST /mkdir endpoint - Create directory
* Handles symlinks safely to avoid ELOOP errors
*/
import type { Request, Response } from "express";
@@ -20,13 +21,46 @@ export function createMkdirHandler() {
const resolvedPath = path.resolve(dirPath);
// Check if path already exists using lstat (doesn't follow symlinks)
try {
const stats = await fs.lstat(resolvedPath);
// Path exists - if it's a directory or symlink, consider it success
if (stats.isDirectory() || stats.isSymbolicLink()) {
addAllowedPath(resolvedPath);
res.json({ success: true });
return;
}
// It's a file - can't create directory
res.status(400).json({
success: false,
error: "Path exists and is not a directory",
});
return;
} catch (statError: any) {
// ENOENT means path doesn't exist - we should create it
if (statError.code !== "ENOENT") {
// Some other error (could be ELOOP in parent path)
throw statError;
}
}
// Path doesn't exist, create it
await fs.mkdir(resolvedPath, { recursive: true });
// Add the new directory to allowed paths for tracking
addAllowedPath(resolvedPath);
res.json({ success: true });
} catch (error) {
} catch (error: any) {
// Handle ELOOP specifically
if (error.code === "ELOOP") {
logError(error, "Create directory failed - symlink loop detected");
res.status(400).json({
success: false,
error: "Cannot create directory: symlink loop detected in path",
});
return;
}
logError(error, "Create directory failed");
res.status(500).json({ success: false, error: getErrorMessage(error) });
}

View File

@@ -7,6 +7,23 @@ import fs from "fs/promises";
import { validatePath } from "../../../lib/security.js";
import { getErrorMessage, logError } from "../common.js";
// Optional files that are expected to not exist in new projects
// Don't log ENOENT errors for these to reduce noise
const OPTIONAL_FILES = ["categories.json"];
function isOptionalFile(filePath: string): boolean {
return OPTIONAL_FILES.some((optionalFile) => filePath.endsWith(optionalFile));
}
function isENOENT(error: unknown): boolean {
return (
error !== null &&
typeof error === "object" &&
"code" in error &&
error.code === "ENOENT"
);
}
export function createReadHandler() {
return async (req: Request, res: Response): Promise<void> => {
try {
@@ -22,7 +39,11 @@ export function createReadHandler() {
res.json({ success: true, content });
} catch (error) {
logError(error, "Read file failed");
// Don't log ENOENT errors for optional files (expected to be missing in new projects)
const shouldLog = !(isENOENT(error) && isOptionalFile(req.body?.filePath || ""));
if (shouldLog) {
logError(error, "Read file failed");
}
res.status(500).json({ success: false, error: getErrorMessage(error) });
}
};

View File

@@ -7,6 +7,7 @@ import fs from "fs/promises";
import path from "path";
import { addAllowedPath } from "../../../lib/security.js";
import { getErrorMessage, logError } from "../common.js";
import { getBoardDir } from "../../../lib/automaker-paths.js";
export function createSaveBoardBackgroundHandler() {
return async (req: Request, res: Response): Promise<void> => {
@@ -26,8 +27,8 @@ export function createSaveBoardBackgroundHandler() {
return;
}
// Create .automaker/board directory if it doesn't exist
const boardDir = path.join(projectPath, ".automaker", "board");
// Get board directory
const boardDir = getBoardDir(projectPath);
await fs.mkdir(boardDir, { recursive: true });
// Decode base64 data (remove data URL prefix if present)
@@ -42,12 +43,11 @@ export function createSaveBoardBackgroundHandler() {
// Write file
await fs.writeFile(filePath, buffer);
// Add project path to allowed paths if not already
addAllowedPath(projectPath);
// Add board directory to allowed paths
addAllowedPath(boardDir);
// Return the relative path for storage
const relativePath = `.automaker/board/${uniqueFilename}`;
res.json({ success: true, path: relativePath });
// Return the absolute path
res.json({ success: true, path: filePath });
} catch (error) {
logError(error, "Save board background failed");
res.status(500).json({ success: false, error: getErrorMessage(error) });

View File

@@ -1,5 +1,5 @@
/**
* POST /save-image endpoint - Save image to .automaker/images directory
* POST /save-image endpoint - Save image to .automaker images directory
*/
import type { Request, Response } from "express";
@@ -7,6 +7,7 @@ import fs from "fs/promises";
import path from "path";
import { addAllowedPath } from "../../../lib/security.js";
import { getErrorMessage, logError } from "../common.js";
import { getImagesDir } from "../../../lib/automaker-paths.js";
export function createSaveImageHandler() {
return async (req: Request, res: Response): Promise<void> => {
@@ -26,8 +27,8 @@ export function createSaveImageHandler() {
return;
}
// Create .automaker/images directory if it doesn't exist
const imagesDir = path.join(projectPath, ".automaker", "images");
// Get images directory
const imagesDir = getImagesDir(projectPath);
await fs.mkdir(imagesDir, { recursive: true });
// Decode base64 data (remove data URL prefix if present)
@@ -44,9 +45,10 @@ export function createSaveImageHandler() {
// Write file
await fs.writeFile(filePath, buffer);
// Add project path to allowed paths if not already
addAllowedPath(projectPath);
// Add automaker directory to allowed paths
addAllowedPath(imagesDir);
// Return the absolute path
res.json({ success: true, path: filePath });
} catch (error) {
logError(error, "Save image failed");

View File

@@ -7,6 +7,7 @@ import fs from "fs/promises";
import path from "path";
import { validatePath } from "../../../lib/security.js";
import { getErrorMessage, logError } from "../common.js";
import { mkdirSafe } from "../../../lib/fs-utils.js";
export function createWriteHandler() {
return async (req: Request, res: Response): Promise<void> => {
@@ -23,8 +24,8 @@ export function createWriteHandler() {
const resolvedPath = validatePath(filePath);
// Ensure parent directory exists
await fs.mkdir(path.dirname(resolvedPath), { recursive: true });
// Ensure parent directory exists (symlink-safe)
await mkdirSafe(path.dirname(resolvedPath));
await fs.writeFile(resolvedPath, content, "utf-8");
res.json({ success: true });

View File

@@ -11,6 +11,7 @@ import { createDeleteApiKeyHandler } from "./routes/delete-api-key.js";
import { createApiKeysHandler } from "./routes/api-keys.js";
import { createPlatformHandler } from "./routes/platform.js";
import { createVerifyClaudeAuthHandler } from "./routes/verify-claude-auth.js";
import { createGhStatusHandler } from "./routes/gh-status.js";
export function createSetupRoutes(): Router {
const router = Router();
@@ -23,6 +24,7 @@ export function createSetupRoutes(): Router {
router.get("/api-keys", createApiKeysHandler());
router.get("/platform", createPlatformHandler());
router.post("/verify-claude-auth", createVerifyClaudeAuthHandler());
router.get("/gh-status", createGhStatusHandler());
return router;
}

View File

@@ -102,3 +102,4 @@ export function createDeleteApiKeyHandler() {
};
}

View File

@@ -0,0 +1,131 @@
/**
* GET /gh-status endpoint - Get GitHub CLI status
*/
import type { Request, Response } from "express";
import { exec } from "child_process";
import { promisify } from "util";
import os from "os";
import path from "path";
import fs from "fs/promises";
import { getErrorMessage, logError } from "../common.js";
const execAsync = promisify(exec);
// Extended PATH to include common tool installation locations
const extendedPath = [
process.env.PATH,
"/opt/homebrew/bin",
"/usr/local/bin",
"/home/linuxbrew/.linuxbrew/bin",
`${process.env.HOME}/.local/bin`,
].filter(Boolean).join(":");
const execEnv = {
...process.env,
PATH: extendedPath,
};
export interface GhStatus {
installed: boolean;
authenticated: boolean;
version: string | null;
path: string | null;
user: string | null;
error?: string;
}
async function getGhStatus(): Promise<GhStatus> {
const status: GhStatus = {
installed: false,
authenticated: false,
version: null,
path: null,
user: null,
};
const isWindows = process.platform === "win32";
// Check if gh CLI is installed
try {
const findCommand = isWindows ? "where gh" : "command -v gh";
const { stdout } = await execAsync(findCommand, { env: execEnv });
status.path = stdout.trim().split(/\r?\n/)[0];
status.installed = true;
} catch {
// gh not in PATH, try common locations
const commonPaths = isWindows
? [
path.join(process.env.LOCALAPPDATA || "", "Programs", "gh", "bin", "gh.exe"),
path.join(process.env.ProgramFiles || "", "GitHub CLI", "gh.exe"),
]
: [
"/opt/homebrew/bin/gh",
"/usr/local/bin/gh",
path.join(os.homedir(), ".local", "bin", "gh"),
"/home/linuxbrew/.linuxbrew/bin/gh",
];
for (const p of commonPaths) {
try {
await fs.access(p);
status.path = p;
status.installed = true;
break;
} catch {
// Not found at this path
}
}
}
if (!status.installed) {
return status;
}
// Get version
try {
const { stdout } = await execAsync("gh --version", { env: execEnv });
// Extract version from output like "gh version 2.40.1 (2024-01-09)"
const versionMatch = stdout.match(/gh version ([\d.]+)/);
status.version = versionMatch ? versionMatch[1] : stdout.trim().split("\n")[0];
} catch {
// Version command failed
}
// Check authentication status
try {
const { stdout } = await execAsync("gh auth status", { env: execEnv });
// If this succeeds without error, we're authenticated
status.authenticated = true;
// Try to extract username from output
const userMatch = stdout.match(/Logged in to [^\s]+ account ([^\s]+)/i) ||
stdout.match(/Logged in to [^\s]+ as ([^\s]+)/i);
if (userMatch) {
status.user = userMatch[1];
}
} catch (error: unknown) {
// Auth status returns non-zero if not authenticated
const err = error as { stderr?: string };
if (err.stderr?.includes("not logged in")) {
status.authenticated = false;
}
}
return status;
}
export function createGhStatusHandler() {
return async (_req: Request, res: Response): Promise<void> => {
try {
const status = await getGhStatus();
res.json({
success: true,
...status,
});
} catch (error) {
logError(error, "Get GitHub CLI status failed");
res.status(500).json({ success: false, error: getErrorMessage(error) });
}
};
}

View File

@@ -13,6 +13,15 @@ import {
const logger = createLogger("Worktree");
const execAsync = promisify(exec);
/**
* Normalize path separators to forward slashes for cross-platform consistency.
* This ensures paths from `path.join()` (backslashes on Windows) match paths
* from git commands (which may use forward slashes).
*/
export function normalizePath(p: string): string {
return p.replace(/\\/g, "/");
}
/**
* Check if a path is a git repo
*/
@@ -25,6 +34,42 @@ export async function isGitRepo(repoPath: string): Promise<boolean> {
}
}
/**
* Check if an error is ENOENT (file/path not found or spawn failed)
* These are expected in test environments with mock paths
*/
export function isENOENT(error: unknown): boolean {
return (
error !== null &&
typeof error === "object" &&
"code" in error &&
error.code === "ENOENT"
);
}
/**
* Check if a path is a mock/test path that doesn't exist
*/
export function isMockPath(worktreePath: string): boolean {
return worktreePath.startsWith("/mock/") || worktreePath.includes("/mock/");
}
/**
* Conditionally log worktree errors - suppress ENOENT for mock paths
* to reduce noise in test output
*/
export function logWorktreeError(
error: unknown,
message: string,
worktreePath?: string
): void {
// Don't log ENOENT errors for mock paths (expected in tests)
if (isENOENT(error) && worktreePath && isMockPath(worktreePath)) {
return;
}
logError(error, message);
}
// Re-export shared utilities
export { getErrorMessageShared as getErrorMessage };
export const logError = createLogError(logger);

View File

@@ -8,8 +8,25 @@ import { createStatusHandler } from "./routes/status.js";
import { createListHandler } from "./routes/list.js";
import { createDiffsHandler } from "./routes/diffs.js";
import { createFileDiffHandler } from "./routes/file-diff.js";
import { createRevertHandler } from "./routes/revert.js";
import { createMergeHandler } from "./routes/merge.js";
import { createCreateHandler } from "./routes/create.js";
import { createDeleteHandler } from "./routes/delete.js";
import { createCreatePRHandler } from "./routes/create-pr.js";
import { createCommitHandler } from "./routes/commit.js";
import { createPushHandler } from "./routes/push.js";
import { createPullHandler } from "./routes/pull.js";
import { createCheckoutBranchHandler } from "./routes/checkout-branch.js";
import { createListBranchesHandler } from "./routes/list-branches.js";
import { createSwitchBranchHandler } from "./routes/switch-branch.js";
import {
createOpenInEditorHandler,
createGetDefaultEditorHandler,
} from "./routes/open-in-editor.js";
import { createInitGitHandler } from "./routes/init-git.js";
import { createMigrateHandler } from "./routes/migrate.js";
import { createStartDevHandler } from "./routes/start-dev.js";
import { createStopDevHandler } from "./routes/stop-dev.js";
import { createListDevServersHandler } from "./routes/list-dev-servers.js";
export function createWorktreeRoutes(): Router {
const router = Router();
@@ -19,8 +36,23 @@ export function createWorktreeRoutes(): Router {
router.post("/list", createListHandler());
router.post("/diffs", createDiffsHandler());
router.post("/file-diff", createFileDiffHandler());
router.post("/revert", createRevertHandler());
router.post("/merge", createMergeHandler());
router.post("/create", createCreateHandler());
router.post("/delete", createDeleteHandler());
router.post("/create-pr", createCreatePRHandler());
router.post("/commit", createCommitHandler());
router.post("/push", createPushHandler());
router.post("/pull", createPullHandler());
router.post("/checkout-branch", createCheckoutBranchHandler());
router.post("/list-branches", createListBranchesHandler());
router.post("/switch-branch", createSwitchBranchHandler());
router.post("/open-in-editor", createOpenInEditorHandler());
router.get("/default-editor", createGetDefaultEditorHandler());
router.post("/init-git", createInitGitHandler());
router.post("/migrate", createMigrateHandler());
router.post("/start-dev", createStartDevHandler());
router.post("/stop-dev", createStopDevHandler());
router.post("/list-dev-servers", createListDevServersHandler());
return router;
}

View File

@@ -0,0 +1,123 @@
/**
* Branch tracking utilities
*
* Tracks active branches in .automaker so users
* can switch between branches even after worktrees are removed.
*/
import { readFile, writeFile } from "fs/promises";
import path from "path";
import {
getBranchTrackingPath,
ensureAutomakerDir,
} from "../../../lib/automaker-paths.js";
export interface TrackedBranch {
name: string;
createdAt: string;
lastActivatedAt?: string;
}
interface BranchTrackingData {
branches: TrackedBranch[];
}
/**
* Read tracked branches from file
*/
export async function getTrackedBranches(
projectPath: string
): Promise<TrackedBranch[]> {
try {
const filePath = getBranchTrackingPath(projectPath);
const content = await readFile(filePath, "utf-8");
const data: BranchTrackingData = JSON.parse(content);
return data.branches || [];
} catch (error: any) {
if (error.code === "ENOENT") {
return [];
}
console.warn("[branch-tracking] Failed to read tracked branches:", error);
return [];
}
}
/**
* Save tracked branches to file
*/
async function saveTrackedBranches(
projectPath: string,
branches: TrackedBranch[]
): Promise<void> {
const automakerDir = await ensureAutomakerDir(projectPath);
const filePath = path.join(automakerDir, "active-branches.json");
const data: BranchTrackingData = { branches };
await writeFile(filePath, JSON.stringify(data, null, 2), "utf-8");
}
/**
* Add a branch to tracking
*/
export async function trackBranch(
projectPath: string,
branchName: string
): Promise<void> {
const branches = await getTrackedBranches(projectPath);
// Check if already tracked
const existing = branches.find((b) => b.name === branchName);
if (existing) {
return; // Already tracked
}
branches.push({
name: branchName,
createdAt: new Date().toISOString(),
});
await saveTrackedBranches(projectPath, branches);
console.log(`[branch-tracking] Now tracking branch: ${branchName}`);
}
/**
* Remove a branch from tracking
*/
export async function untrackBranch(
projectPath: string,
branchName: string
): Promise<void> {
const branches = await getTrackedBranches(projectPath);
const filtered = branches.filter((b) => b.name !== branchName);
if (filtered.length !== branches.length) {
await saveTrackedBranches(projectPath, filtered);
console.log(`[branch-tracking] Stopped tracking branch: ${branchName}`);
}
}
/**
* Update last activated timestamp for a branch
*/
export async function updateBranchActivation(
projectPath: string,
branchName: string
): Promise<void> {
const branches = await getTrackedBranches(projectPath);
const branch = branches.find((b) => b.name === branchName);
if (branch) {
branch.lastActivatedAt = new Date().toISOString();
await saveTrackedBranches(projectPath, branches);
}
}
/**
* Check if a branch is tracked
*/
export async function isBranchTracked(
projectPath: string,
branchName: string
): Promise<boolean> {
const branches = await getTrackedBranches(projectPath);
return branches.some((b) => b.name === branchName);
}

View File

@@ -0,0 +1,86 @@
/**
* POST /checkout-branch endpoint - Create and checkout a new branch
*/
import type { Request, Response } from "express";
import { exec } from "child_process";
import { promisify } from "util";
import { getErrorMessage, logError } from "../common.js";
const execAsync = promisify(exec);
export function createCheckoutBranchHandler() {
return async (req: Request, res: Response): Promise<void> => {
try {
const { worktreePath, branchName } = req.body as {
worktreePath: string;
branchName: string;
};
if (!worktreePath) {
res.status(400).json({
success: false,
error: "worktreePath required",
});
return;
}
if (!branchName) {
res.status(400).json({
success: false,
error: "branchName required",
});
return;
}
// Validate branch name (basic validation)
const invalidChars = /[\s~^:?*\[\\]/;
if (invalidChars.test(branchName)) {
res.status(400).json({
success: false,
error: "Branch name contains invalid characters",
});
return;
}
// Get current branch for reference
const { stdout: currentBranchOutput } = await execAsync(
"git rev-parse --abbrev-ref HEAD",
{ cwd: worktreePath }
);
const currentBranch = currentBranchOutput.trim();
// Check if branch already exists
try {
await execAsync(`git rev-parse --verify ${branchName}`, {
cwd: worktreePath,
});
// Branch exists
res.status(400).json({
success: false,
error: `Branch '${branchName}' already exists`,
});
return;
} catch {
// Branch doesn't exist, good to create
}
// Create and checkout the new branch
await execAsync(`git checkout -b ${branchName}`, {
cwd: worktreePath,
});
res.json({
success: true,
result: {
previousBranch: currentBranch,
newBranch: branchName,
message: `Created and checked out branch '${branchName}'`,
},
});
} catch (error) {
logError(error, "Checkout branch failed");
res.status(500).json({ success: false, error: getErrorMessage(error) });
}
};
}

View File

@@ -0,0 +1,79 @@
/**
* POST /commit endpoint - Commit changes in a worktree
*/
import type { Request, Response } from "express";
import { exec } from "child_process";
import { promisify } from "util";
import { getErrorMessage, logError } from "../common.js";
const execAsync = promisify(exec);
export function createCommitHandler() {
return async (req: Request, res: Response): Promise<void> => {
try {
const { worktreePath, message } = req.body as {
worktreePath: string;
message: string;
};
if (!worktreePath || !message) {
res.status(400).json({
success: false,
error: "worktreePath and message required",
});
return;
}
// Check for uncommitted changes
const { stdout: status } = await execAsync("git status --porcelain", {
cwd: worktreePath,
});
if (!status.trim()) {
res.json({
success: true,
result: {
committed: false,
message: "No changes to commit",
},
});
return;
}
// Stage all changes
await execAsync("git add -A", { cwd: worktreePath });
// Create commit
await execAsync(`git commit -m "${message.replace(/"/g, '\\"')}"`, {
cwd: worktreePath,
});
// Get commit hash
const { stdout: hashOutput } = await execAsync("git rev-parse HEAD", {
cwd: worktreePath,
});
const commitHash = hashOutput.trim().substring(0, 8);
// Get branch name
const { stdout: branchOutput } = await execAsync(
"git rev-parse --abbrev-ref HEAD",
{ cwd: worktreePath }
);
const branchName = branchOutput.trim();
res.json({
success: true,
result: {
committed: true,
commitHash,
branch: branchName,
message,
},
});
} catch (error) {
logError(error, "Commit worktree failed");
res.status(500).json({ success: false, error: getErrorMessage(error) });
}
};
}

View File

@@ -0,0 +1,288 @@
/**
* POST /create-pr endpoint - Commit changes and create a pull request from a worktree
*/
import type { Request, Response } from "express";
import { exec } from "child_process";
import { promisify } from "util";
import { getErrorMessage, logError } from "../common.js";
const execAsync = promisify(exec);
// Extended PATH to include common tool installation locations
// This is needed because Electron apps don't inherit the user's shell PATH
const pathSeparator = process.platform === "win32" ? ";" : ":";
const additionalPaths: string[] = [];
if (process.platform === "win32") {
// Windows paths
if (process.env.LOCALAPPDATA) {
additionalPaths.push(`${process.env.LOCALAPPDATA}\\Programs\\Git\\cmd`);
}
if (process.env.PROGRAMFILES) {
additionalPaths.push(`${process.env.PROGRAMFILES}\\Git\\cmd`);
}
if (process.env["ProgramFiles(x86)"]) {
additionalPaths.push(`${process.env["ProgramFiles(x86)"]}\\Git\\cmd`);
}
} else {
// Unix/Mac paths
additionalPaths.push(
"/opt/homebrew/bin", // Homebrew on Apple Silicon
"/usr/local/bin", // Homebrew on Intel Mac, common Linux location
"/home/linuxbrew/.linuxbrew/bin", // Linuxbrew
`${process.env.HOME}/.local/bin`, // pipx, other user installs
);
}
const extendedPath = [
process.env.PATH,
...additionalPaths.filter(Boolean),
].filter(Boolean).join(pathSeparator);
const execEnv = {
...process.env,
PATH: extendedPath,
};
export function createCreatePRHandler() {
return async (req: Request, res: Response): Promise<void> => {
try {
const { worktreePath, commitMessage, prTitle, prBody, baseBranch, draft } = req.body as {
worktreePath: string;
commitMessage?: string;
prTitle?: string;
prBody?: string;
baseBranch?: string;
draft?: boolean;
};
if (!worktreePath) {
res.status(400).json({
success: false,
error: "worktreePath required",
});
return;
}
// Get current branch name
const { stdout: branchOutput } = await execAsync(
"git rev-parse --abbrev-ref HEAD",
{ cwd: worktreePath, env: execEnv }
);
const branchName = branchOutput.trim();
// Check for uncommitted changes
const { stdout: status } = await execAsync("git status --porcelain", {
cwd: worktreePath,
env: execEnv,
});
const hasChanges = status.trim().length > 0;
// If there are changes, commit them
let commitHash: string | null = null;
if (hasChanges) {
const message = commitMessage || `Changes from ${branchName}`;
// Stage all changes
await execAsync("git add -A", { cwd: worktreePath, env: execEnv });
// Create commit
await execAsync(`git commit -m "${message.replace(/"/g, '\\"')}"`, {
cwd: worktreePath,
env: execEnv,
});
// Get commit hash
const { stdout: hashOutput } = await execAsync("git rev-parse HEAD", {
cwd: worktreePath,
env: execEnv,
});
commitHash = hashOutput.trim().substring(0, 8);
}
// Push the branch to remote
let pushError: string | null = null;
try {
await execAsync(`git push -u origin ${branchName}`, {
cwd: worktreePath,
env: execEnv,
});
} catch (error: unknown) {
// If push fails, try with --set-upstream
try {
await execAsync(`git push --set-upstream origin ${branchName}`, {
cwd: worktreePath,
env: execEnv,
});
} catch (error2: unknown) {
// Capture push error for reporting
const err = error2 as { stderr?: string; message?: string };
pushError = err.stderr || err.message || "Push failed";
console.error("[CreatePR] Push failed:", pushError);
}
}
// If push failed, return error
if (pushError) {
res.status(500).json({
success: false,
error: `Failed to push branch: ${pushError}`,
});
return;
}
// Create PR using gh CLI or provide browser fallback
const base = baseBranch || "main";
const title = prTitle || branchName;
const body = prBody || `Changes from branch ${branchName}`;
const draftFlag = draft ? "--draft" : "";
let prUrl: string | null = null;
let prError: string | null = null;
let browserUrl: string | null = null;
let ghCliAvailable = false;
// Check if gh CLI is available (cross-platform)
try {
const checkCommand = process.platform === "win32"
? "where gh"
: "command -v gh";
await execAsync(checkCommand, { env: execEnv });
ghCliAvailable = true;
} catch {
ghCliAvailable = false;
}
// Get repository URL for browser fallback
let repoUrl: string | null = null;
let upstreamRepo: string | null = null;
let originOwner: string | null = null;
try {
const { stdout: remotes } = await execAsync("git remote -v", {
cwd: worktreePath,
env: execEnv,
});
// Parse remotes to detect fork workflow and get repo URL
const lines = remotes.split(/\r?\n/); // Handle both Unix and Windows line endings
for (const line of lines) {
// Try multiple patterns to match different remote URL formats
// Pattern 1: git@github.com:owner/repo.git (fetch)
// Pattern 2: https://github.com/owner/repo.git (fetch)
// Pattern 3: https://github.com/owner/repo (fetch)
let match = line.match(/^(\w+)\s+.*[:/]([^/]+)\/([^/\s]+?)(?:\.git)?\s+\(fetch\)/);
if (!match) {
// Try SSH format: git@github.com:owner/repo.git
match = line.match(/^(\w+)\s+git@[^:]+:([^/]+)\/([^\s]+?)(?:\.git)?\s+\(fetch\)/);
}
if (!match) {
// Try HTTPS format: https://github.com/owner/repo.git
match = line.match(/^(\w+)\s+https?:\/\/[^/]+\/([^/]+)\/([^\s]+?)(?:\.git)?\s+\(fetch\)/);
}
if (match) {
const [, remoteName, owner, repo] = match;
if (remoteName === "upstream") {
upstreamRepo = `${owner}/${repo}`;
repoUrl = `https://github.com/${owner}/${repo}`;
} else if (remoteName === "origin") {
originOwner = owner;
if (!repoUrl) {
repoUrl = `https://github.com/${owner}/${repo}`;
}
}
}
}
} catch (error) {
// Couldn't parse remotes - will try fallback
}
// Fallback: Try to get repo URL from git config if remote parsing failed
if (!repoUrl) {
try {
const { stdout: originUrl } = await execAsync("git config --get remote.origin.url", {
cwd: worktreePath,
env: execEnv,
});
const url = originUrl.trim();
// Parse URL to extract owner/repo
// Handle both SSH (git@github.com:owner/repo.git) and HTTPS (https://github.com/owner/repo.git)
let match = url.match(/[:/]([^/]+)\/([^/\s]+?)(?:\.git)?$/);
if (match) {
const [, owner, repo] = match;
originOwner = owner;
repoUrl = `https://github.com/${owner}/${repo}`;
}
} catch (error) {
// Failed to get repo URL from config
}
}
// Construct browser URL for PR creation
if (repoUrl) {
const encodedTitle = encodeURIComponent(title);
const encodedBody = encodeURIComponent(body);
if (upstreamRepo && originOwner) {
// Fork workflow: PR to upstream from origin
browserUrl = `https://github.com/${upstreamRepo}/compare/${base}...${originOwner}:${branchName}?expand=1&title=${encodedTitle}&body=${encodedBody}`;
} else {
// Regular repo
browserUrl = `${repoUrl}/compare/${base}...${branchName}?expand=1&title=${encodedTitle}&body=${encodedBody}`;
}
}
if (ghCliAvailable) {
try {
// Build gh pr create command
let prCmd = `gh pr create --base "${base}"`;
// If this is a fork (has upstream remote), specify the repo and head
if (upstreamRepo && originOwner) {
// For forks: --repo specifies where to create PR, --head specifies source
prCmd += ` --repo "${upstreamRepo}" --head "${originOwner}:${branchName}"`;
} else {
// Not a fork, just specify the head branch
prCmd += ` --head "${branchName}"`;
}
prCmd += ` --title "${title.replace(/"/g, '\\"')}" --body "${body.replace(/"/g, '\\"')}" ${draftFlag}`;
prCmd = prCmd.trim();
const { stdout: prOutput } = await execAsync(prCmd, {
cwd: worktreePath,
env: execEnv,
});
prUrl = prOutput.trim();
} catch (ghError: unknown) {
// gh CLI failed
const err = ghError as { stderr?: string; message?: string };
prError = err.stderr || err.message || "PR creation failed";
}
} else {
prError = "gh_cli_not_available";
}
// Return result with browser fallback URL
res.json({
success: true,
result: {
branch: branchName,
committed: hasChanges,
commitHash,
pushed: true,
prUrl,
prCreated: !!prUrl,
prError: prError || undefined,
browserUrl: browserUrl || undefined,
ghCliAvailable,
},
});
} catch (error) {
logError(error, "Create PR failed");
res.status(500).json({ success: false, error: getErrorMessage(error) });
}
};
}

View File

@@ -0,0 +1,172 @@
/**
* POST /create endpoint - Create a new git worktree
*
* This endpoint handles worktree creation with proper checks:
* 1. First checks if git already has a worktree for the branch (anywhere)
* 2. If found, returns the existing worktree (no error)
* 3. Only creates a new worktree if none exists for the branch
*/
import type { Request, Response } from "express";
import { exec } from "child_process";
import { promisify } from "util";
import path from "path";
import { mkdir } from "fs/promises";
import { isGitRepo, getErrorMessage, logError, normalizePath } from "../common.js";
import { trackBranch } from "./branch-tracking.js";
const execAsync = promisify(exec);
/**
* Find an existing worktree for a given branch by checking git worktree list
*/
async function findExistingWorktreeForBranch(
projectPath: string,
branchName: string
): Promise<{ path: string; branch: string } | null> {
try {
const { stdout } = await execAsync("git worktree list --porcelain", {
cwd: projectPath,
});
const lines = stdout.split("\n");
let currentPath: string | null = null;
let currentBranch: string | null = null;
for (const line of lines) {
if (line.startsWith("worktree ")) {
currentPath = line.slice(9);
} else if (line.startsWith("branch ")) {
currentBranch = line.slice(7).replace("refs/heads/", "");
} else if (line === "" && currentPath && currentBranch) {
// End of a worktree entry
if (currentBranch === branchName) {
// Resolve to absolute path - git may return relative paths
// Critical for cross-platform compatibility (Windows, macOS, Linux)
const resolvedPath = path.isAbsolute(currentPath)
? path.resolve(currentPath)
: path.resolve(projectPath, currentPath);
return { path: resolvedPath, branch: currentBranch };
}
currentPath = null;
currentBranch = null;
}
}
// Check the last entry (if file doesn't end with newline)
if (currentPath && currentBranch && currentBranch === branchName) {
// Resolve to absolute path for cross-platform compatibility
const resolvedPath = path.isAbsolute(currentPath)
? path.resolve(currentPath)
: path.resolve(projectPath, currentPath);
return { path: resolvedPath, branch: currentBranch };
}
return null;
} catch {
return null;
}
}
export function createCreateHandler() {
return async (req: Request, res: Response): Promise<void> => {
try {
const { projectPath, branchName, baseBranch } = req.body as {
projectPath: string;
branchName: string;
baseBranch?: string; // Optional base branch to create from (defaults to current HEAD)
};
if (!projectPath || !branchName) {
res.status(400).json({
success: false,
error: "projectPath and branchName required",
});
return;
}
if (!(await isGitRepo(projectPath))) {
res.status(400).json({
success: false,
error: "Not a git repository",
});
return;
}
// First, check if git already has a worktree for this branch (anywhere)
const existingWorktree = await findExistingWorktreeForBranch(projectPath, branchName);
if (existingWorktree) {
// Worktree already exists, return it as success (not an error)
// This handles manually created worktrees or worktrees from previous runs
console.log(`[Worktree] Found existing worktree for branch "${branchName}" at: ${existingWorktree.path}`);
// Track the branch so it persists in the UI
await trackBranch(projectPath, branchName);
res.json({
success: true,
worktree: {
path: normalizePath(existingWorktree.path),
branch: branchName,
isNew: false, // Not newly created
},
});
return;
}
// Sanitize branch name for directory usage
const sanitizedName = branchName.replace(/[^a-zA-Z0-9_-]/g, "-");
const worktreesDir = path.join(projectPath, ".worktrees");
const worktreePath = path.join(worktreesDir, sanitizedName);
// Create worktrees directory if it doesn't exist
await mkdir(worktreesDir, { recursive: true });
// Check if branch exists
let branchExists = false;
try {
await execAsync(`git rev-parse --verify ${branchName}`, {
cwd: projectPath,
});
branchExists = true;
} catch {
// Branch doesn't exist
}
// Create worktree
let createCmd: string;
if (branchExists) {
// Use existing branch
createCmd = `git worktree add "${worktreePath}" ${branchName}`;
} else {
// Create new branch from base or HEAD
const base = baseBranch || "HEAD";
createCmd = `git worktree add -b ${branchName} "${worktreePath}" ${base}`;
}
await execAsync(createCmd, { cwd: projectPath });
// Note: We intentionally do NOT symlink .automaker to worktrees
// Features and config are always accessed from the main project path
// This avoids symlink loop issues when activating worktrees
// Track the branch so it persists in the UI even after worktree is removed
await trackBranch(projectPath, branchName);
// Resolve to absolute path for cross-platform compatibility
// normalizePath converts to forward slashes for API consistency
const absoluteWorktreePath = path.resolve(worktreePath);
res.json({
success: true,
worktree: {
path: normalizePath(absoluteWorktreePath),
branch: branchName,
isNew: !branchExists,
},
});
} catch (error) {
logError(error, "Create worktree failed");
res.status(500).json({ success: false, error: getErrorMessage(error) });
}
};
}

View File

@@ -0,0 +1,79 @@
/**
* POST /delete endpoint - Delete a git worktree
*/
import type { Request, Response } from "express";
import { exec } from "child_process";
import { promisify } from "util";
import { isGitRepo, getErrorMessage, logError } from "../common.js";
const execAsync = promisify(exec);
export function createDeleteHandler() {
return async (req: Request, res: Response): Promise<void> => {
try {
const { projectPath, worktreePath, deleteBranch } = req.body as {
projectPath: string;
worktreePath: string;
deleteBranch?: boolean; // Whether to also delete the branch
};
if (!projectPath || !worktreePath) {
res.status(400).json({
success: false,
error: "projectPath and worktreePath required",
});
return;
}
if (!(await isGitRepo(projectPath))) {
res.status(400).json({
success: false,
error: "Not a git repository",
});
return;
}
// Get branch name before removing worktree
let branchName: string | null = null;
try {
const { stdout } = await execAsync("git rev-parse --abbrev-ref HEAD", {
cwd: worktreePath,
});
branchName = stdout.trim();
} catch {
// Could not get branch name
}
// Remove the worktree
try {
await execAsync(`git worktree remove "${worktreePath}" --force`, {
cwd: projectPath,
});
} catch (error) {
// Try with prune if remove fails
await execAsync("git worktree prune", { cwd: projectPath });
}
// Optionally delete the branch
if (deleteBranch && branchName && branchName !== "main" && branchName !== "master") {
try {
await execAsync(`git branch -D ${branchName}`, { cwd: projectPath });
} catch {
// Branch deletion failed, not critical
}
}
res.json({
success: true,
deleted: {
worktreePath,
branch: deleteBranch ? branchName : null,
},
});
} catch (error) {
logError(error, "Delete worktree failed");
res.status(500).json({ success: false, error: getErrorMessage(error) });
}
};
}

View File

@@ -26,12 +26,8 @@ export function createDiffsHandler() {
return;
}
const worktreePath = path.join(
projectPath,
".automaker",
"worktrees",
featureId
);
// Git worktrees are stored in project directory
const worktreePath = path.join(projectPath, ".worktrees", featureId);
try {
// Check if worktree exists

View File

@@ -29,12 +29,8 @@ export function createFileDiffHandler() {
return;
}
const worktreePath = path.join(
projectPath,
".automaker",
"worktrees",
featureId
);
// Git worktrees are stored in project directory
const worktreePath = path.join(projectPath, ".worktrees", featureId);
try {
await fs.access(worktreePath);

View File

@@ -7,7 +7,7 @@ import { exec } from "child_process";
import { promisify } from "util";
import path from "path";
import fs from "fs/promises";
import { getErrorMessage, logError } from "../common.js";
import { getErrorMessage, logError, normalizePath } from "../common.js";
const execAsync = promisify(exec);
@@ -29,13 +29,8 @@ export function createInfoHandler() {
return;
}
// Check if worktree exists
const worktreePath = path.join(
projectPath,
".automaker",
"worktrees",
featureId
);
// Check if worktree exists (git worktrees are stored in project directory)
const worktreePath = path.join(projectPath, ".worktrees", featureId);
try {
await fs.access(worktreePath);
const { stdout } = await execAsync("git rev-parse --abbrev-ref HEAD", {
@@ -43,7 +38,7 @@ export function createInfoHandler() {
});
res.json({
success: true,
worktreePath,
worktreePath: normalizePath(worktreePath),
branchName: stdout.trim(),
});
} catch {

View File

@@ -0,0 +1,60 @@
/**
* POST /init-git endpoint - Initialize a git repository in a directory
*/
import type { Request, Response } from "express";
import { exec } from "child_process";
import { promisify } from "util";
import { existsSync } from "fs";
import { join } from "path";
import { getErrorMessage, logError } from "../common.js";
const execAsync = promisify(exec);
export function createInitGitHandler() {
return async (req: Request, res: Response): Promise<void> => {
try {
const { projectPath } = req.body as {
projectPath: string;
};
if (!projectPath) {
res.status(400).json({
success: false,
error: "projectPath required",
});
return;
}
// Check if .git already exists
const gitDirPath = join(projectPath, ".git");
if (existsSync(gitDirPath)) {
res.json({
success: true,
result: {
initialized: false,
message: "Git repository already exists",
},
});
return;
}
// Initialize git and create an initial empty commit
await execAsync(
`git init && git commit --allow-empty -m "Initial commit"`,
{ cwd: projectPath }
);
res.json({
success: true,
result: {
initialized: true,
message: "Git repository initialized with initial commit",
},
});
} catch (error) {
logError(error, "Init git failed");
res.status(500).json({ success: false, error: getErrorMessage(error) });
}
};
}

View File

@@ -0,0 +1,94 @@
/**
* POST /list-branches endpoint - List all local branches
*/
import type { Request, Response } from "express";
import { exec } from "child_process";
import { promisify } from "util";
import { getErrorMessage, logWorktreeError } from "../common.js";
const execAsync = promisify(exec);
interface BranchInfo {
name: string;
isCurrent: boolean;
isRemote: boolean;
}
export function createListBranchesHandler() {
return async (req: Request, res: Response): Promise<void> => {
try {
const { worktreePath } = req.body as {
worktreePath: string;
};
if (!worktreePath) {
res.status(400).json({
success: false,
error: "worktreePath required",
});
return;
}
// Get current branch
const { stdout: currentBranchOutput } = await execAsync(
"git rev-parse --abbrev-ref HEAD",
{ cwd: worktreePath }
);
const currentBranch = currentBranchOutput.trim();
// List all local branches
const { stdout: branchesOutput } = await execAsync(
"git branch --format='%(refname:short)'",
{ cwd: worktreePath }
);
const branches: BranchInfo[] = branchesOutput
.trim()
.split("\n")
.filter((b) => b.trim())
.map((name) => ({
name: name.trim(),
isCurrent: name.trim() === currentBranch,
isRemote: false,
}));
// Get ahead/behind count for current branch
let aheadCount = 0;
let behindCount = 0;
try {
// First check if there's a remote tracking branch
const { stdout: upstreamOutput } = await execAsync(
`git rev-parse --abbrev-ref ${currentBranch}@{upstream}`,
{ cwd: worktreePath }
);
if (upstreamOutput.trim()) {
const { stdout: aheadBehindOutput } = await execAsync(
`git rev-list --left-right --count ${currentBranch}@{upstream}...HEAD`,
{ cwd: worktreePath }
);
const [behind, ahead] = aheadBehindOutput.trim().split(/\s+/).map(Number);
aheadCount = ahead || 0;
behindCount = behind || 0;
}
} catch {
// No upstream branch set, that's okay
}
res.json({
success: true,
result: {
currentBranch,
branches,
aheadCount,
behindCount,
},
});
} catch (error) {
const worktreePath = req.body?.worktreePath;
logWorktreeError(error, "List branches failed", worktreePath);
res.status(500).json({ success: false, error: getErrorMessage(error) });
}
};
}

View File

@@ -0,0 +1,29 @@
/**
* POST /list-dev-servers endpoint - List all running dev servers
*
* Returns information about all worktree dev servers currently running,
* including their ports and URLs.
*/
import type { Request, Response } from "express";
import { getDevServerService } from "../../../services/dev-server-service.js";
import { getErrorMessage, logError } from "../common.js";
export function createListDevServersHandler() {
return async (_req: Request, res: Response): Promise<void> => {
try {
const devServerService = getDevServerService();
const result = devServerService.listDevServers();
res.json({
success: true,
result: {
servers: result.result.servers,
},
});
} catch (error) {
logError(error, "List dev servers failed");
res.status(500).json({ success: false, error: getErrorMessage(error) });
}
};
}

View File

@@ -1,18 +1,43 @@
/**
* POST /list endpoint - List all worktrees
* POST /list endpoint - List all git worktrees
*
* Returns actual git worktrees from `git worktree list`.
* Does NOT include tracked branches - only real worktrees with separate directories.
*/
import type { Request, Response } from "express";
import { exec } from "child_process";
import { promisify } from "util";
import { isGitRepo, getErrorMessage, logError } from "../common.js";
import { isGitRepo, getErrorMessage, logError, normalizePath } from "../common.js";
const execAsync = promisify(exec);
interface WorktreeInfo {
path: string;
branch: string;
isMain: boolean;
isCurrent: boolean; // Is this the currently checked out branch in main?
hasWorktree: boolean; // Always true for items in this list
hasChanges?: boolean;
changedFilesCount?: number;
}
async function getCurrentBranch(cwd: string): Promise<string> {
try {
const { stdout } = await execAsync("git branch --show-current", { cwd });
return stdout.trim();
} catch {
return "";
}
}
export function createListHandler() {
return async (req: Request, res: Response): Promise<void> => {
try {
const { projectPath } = req.body as { projectPath: string };
const { projectPath, includeDetails } = req.body as {
projectPath: string;
includeDetails?: boolean;
};
if (!projectPath) {
res.status(400).json({ success: false, error: "projectPath required" });
@@ -24,27 +49,60 @@ export function createListHandler() {
return;
}
// Get current branch in main directory
const currentBranch = await getCurrentBranch(projectPath);
// Get actual worktrees from git
const { stdout } = await execAsync("git worktree list --porcelain", {
cwd: projectPath,
});
const worktrees: Array<{ path: string; branch: string }> = [];
const worktrees: WorktreeInfo[] = [];
const lines = stdout.split("\n");
let current: { path?: string; branch?: string } = {};
let isFirst = true;
for (const line of lines) {
if (line.startsWith("worktree ")) {
current.path = line.slice(9);
current.path = normalizePath(line.slice(9));
} else if (line.startsWith("branch ")) {
current.branch = line.slice(7).replace("refs/heads/", "");
} else if (line === "") {
if (current.path && current.branch) {
worktrees.push({ path: current.path, branch: current.branch });
worktrees.push({
path: current.path,
branch: current.branch,
isMain: isFirst,
isCurrent: current.branch === currentBranch,
hasWorktree: true,
});
isFirst = false;
}
current = {};
}
}
// If includeDetails is requested, fetch change status for each worktree
if (includeDetails) {
for (const worktree of worktrees) {
try {
const { stdout: statusOutput } = await execAsync(
"git status --porcelain",
{ cwd: worktree.path }
);
const changedFiles = statusOutput
.trim()
.split("\n")
.filter((line) => line.trim());
worktree.hasChanges = changedFiles.length > 0;
worktree.changedFilesCount = changedFiles.length;
} catch {
worktree.hasChanges = false;
worktree.changedFilesCount = 0;
}
}
}
res.json({ success: true, worktrees });
} catch (error) {
logError(error, "List worktrees failed");

View File

@@ -30,12 +30,8 @@ export function createMergeHandler() {
}
const branchName = `feature/${featureId}`;
const worktreePath = path.join(
projectPath,
".automaker",
"worktrees",
featureId
);
// Git worktrees are stored in project directory
const worktreePath = path.join(projectPath, ".worktrees", featureId);
// Get current branch
const { stdout: currentBranch } = await execAsync(

View File

@@ -0,0 +1,32 @@
/**
* POST /migrate endpoint - Migration endpoint (no longer needed)
*
* This endpoint is kept for backwards compatibility but no longer performs
* any migration since .automaker is now stored in the project directory.
*/
import type { Request, Response } from "express";
import { getAutomakerDir } from "../../../lib/automaker-paths.js";
export function createMigrateHandler() {
return async (req: Request, res: Response): Promise<void> => {
const { projectPath } = req.body as { projectPath: string };
if (!projectPath) {
res.status(400).json({
success: false,
error: "projectPath is required",
});
return;
}
// Migration is no longer needed - .automaker is stored in project directory
const automakerDir = getAutomakerDir(projectPath);
res.json({
success: true,
migrated: false,
message: "No migration needed - .automaker is stored in project directory",
path: automakerDir,
});
};
}

View File

@@ -0,0 +1,153 @@
/**
* POST /open-in-editor endpoint - Open a worktree directory in the default code editor
* GET /default-editor endpoint - Get the name of the default code editor
*/
import type { Request, Response } from "express";
import { exec } from "child_process";
import { promisify } from "util";
import { getErrorMessage, logError } from "../common.js";
const execAsync = promisify(exec);
// Editor detection with caching
interface EditorInfo {
name: string;
command: string;
}
let cachedEditor: EditorInfo | null = null;
/**
* Detect which code editor is available on the system
*/
async function detectDefaultEditor(): Promise<EditorInfo> {
// Return cached result if available
if (cachedEditor) {
return cachedEditor;
}
// Try Cursor first (if user has Cursor, they probably prefer it)
try {
await execAsync("which cursor || where cursor");
cachedEditor = { name: "Cursor", command: "cursor" };
return cachedEditor;
} catch {
// Cursor not found
}
// Try VS Code
try {
await execAsync("which code || where code");
cachedEditor = { name: "VS Code", command: "code" };
return cachedEditor;
} catch {
// VS Code not found
}
// Try Zed
try {
await execAsync("which zed || where zed");
cachedEditor = { name: "Zed", command: "zed" };
return cachedEditor;
} catch {
// Zed not found
}
// Try Sublime Text
try {
await execAsync("which subl || where subl");
cachedEditor = { name: "Sublime Text", command: "subl" };
return cachedEditor;
} catch {
// Sublime not found
}
// Fallback to file manager
const platform = process.platform;
if (platform === "darwin") {
cachedEditor = { name: "Finder", command: "open" };
} else if (platform === "win32") {
cachedEditor = { name: "Explorer", command: "explorer" };
} else {
cachedEditor = { name: "File Manager", command: "xdg-open" };
}
return cachedEditor;
}
export function createGetDefaultEditorHandler() {
return async (_req: Request, res: Response): Promise<void> => {
try {
const editor = await detectDefaultEditor();
res.json({
success: true,
result: {
editorName: editor.name,
editorCommand: editor.command,
},
});
} catch (error) {
logError(error, "Get default editor failed");
res.status(500).json({ success: false, error: getErrorMessage(error) });
}
};
}
export function createOpenInEditorHandler() {
return async (req: Request, res: Response): Promise<void> => {
try {
const { worktreePath } = req.body as {
worktreePath: string;
};
if (!worktreePath) {
res.status(400).json({
success: false,
error: "worktreePath required",
});
return;
}
const editor = await detectDefaultEditor();
try {
await execAsync(`${editor.command} "${worktreePath}"`);
res.json({
success: true,
result: {
message: `Opened ${worktreePath} in ${editor.name}`,
editorName: editor.name,
},
});
} catch (editorError) {
// If the detected editor fails, try opening in default file manager as fallback
const platform = process.platform;
let openCommand: string;
let fallbackName: string;
if (platform === "darwin") {
openCommand = `open "${worktreePath}"`;
fallbackName = "Finder";
} else if (platform === "win32") {
openCommand = `explorer "${worktreePath}"`;
fallbackName = "Explorer";
} else {
openCommand = `xdg-open "${worktreePath}"`;
fallbackName = "File Manager";
}
await execAsync(openCommand);
res.json({
success: true,
result: {
message: `Opened ${worktreePath} in ${fallbackName}`,
editorName: fallbackName,
},
});
}
} catch (error) {
logError(error, "Open in editor failed");
res.status(500).json({ success: false, error: getErrorMessage(error) });
}
};
}

View File

@@ -0,0 +1,92 @@
/**
* POST /pull endpoint - Pull latest changes for a worktree/branch
*/
import type { Request, Response } from "express";
import { exec } from "child_process";
import { promisify } from "util";
import { getErrorMessage, logError } from "../common.js";
const execAsync = promisify(exec);
export function createPullHandler() {
return async (req: Request, res: Response): Promise<void> => {
try {
const { worktreePath } = req.body as {
worktreePath: string;
};
if (!worktreePath) {
res.status(400).json({
success: false,
error: "worktreePath required",
});
return;
}
// Get current branch name
const { stdout: branchOutput } = await execAsync(
"git rev-parse --abbrev-ref HEAD",
{ cwd: worktreePath }
);
const branchName = branchOutput.trim();
// Fetch latest from remote
await execAsync("git fetch origin", { cwd: worktreePath });
// Check if there are local changes that would be overwritten
const { stdout: status } = await execAsync("git status --porcelain", {
cwd: worktreePath,
});
const hasLocalChanges = status.trim().length > 0;
if (hasLocalChanges) {
res.status(400).json({
success: false,
error: "You have local changes. Please commit them before pulling.",
});
return;
}
// Pull latest changes
try {
const { stdout: pullOutput } = await execAsync(
`git pull origin ${branchName}`,
{ cwd: worktreePath }
);
// Check if we pulled any changes
const alreadyUpToDate = pullOutput.includes("Already up to date");
res.json({
success: true,
result: {
branch: branchName,
pulled: !alreadyUpToDate,
message: alreadyUpToDate ? "Already up to date" : "Pulled latest changes",
},
});
} catch (pullError: unknown) {
const err = pullError as { stderr?: string; message?: string };
const errorMsg = err.stderr || err.message || "Pull failed";
// Check for common errors
if (errorMsg.includes("no tracking information")) {
res.status(400).json({
success: false,
error: `Branch '${branchName}' has no upstream branch. Push it first or set upstream with: git branch --set-upstream-to=origin/${branchName}`,
});
return;
}
res.status(500).json({
success: false,
error: errorMsg,
});
}
} catch (error) {
logError(error, "Pull failed");
res.status(500).json({ success: false, error: getErrorMessage(error) });
}
};
}

View File

@@ -0,0 +1,61 @@
/**
* POST /push endpoint - Push a worktree branch to remote
*/
import type { Request, Response } from "express";
import { exec } from "child_process";
import { promisify } from "util";
import { getErrorMessage, logError } from "../common.js";
const execAsync = promisify(exec);
export function createPushHandler() {
return async (req: Request, res: Response): Promise<void> => {
try {
const { worktreePath, force } = req.body as {
worktreePath: string;
force?: boolean;
};
if (!worktreePath) {
res.status(400).json({
success: false,
error: "worktreePath required",
});
return;
}
// Get branch name
const { stdout: branchOutput } = await execAsync(
"git rev-parse --abbrev-ref HEAD",
{ cwd: worktreePath }
);
const branchName = branchOutput.trim();
// Push the branch
const forceFlag = force ? "--force" : "";
try {
await execAsync(`git push -u origin ${branchName} ${forceFlag}`, {
cwd: worktreePath,
});
} catch {
// Try setting upstream
await execAsync(`git push --set-upstream origin ${branchName} ${forceFlag}`, {
cwd: worktreePath,
});
}
res.json({
success: true,
result: {
branch: branchName,
pushed: true,
message: `Successfully pushed ${branchName} to origin`,
},
});
} catch (error) {
logError(error, "Push worktree failed");
res.status(500).json({ success: false, error: getErrorMessage(error) });
}
};
}

View File

@@ -1,58 +0,0 @@
/**
* POST /revert endpoint - Revert feature (remove worktree)
*/
import type { Request, Response } from "express";
import { exec } from "child_process";
import { promisify } from "util";
import path from "path";
import { getErrorMessage, logError } from "../common.js";
const execAsync = promisify(exec);
export function createRevertHandler() {
return async (req: Request, res: Response): Promise<void> => {
try {
const { projectPath, featureId } = req.body as {
projectPath: string;
featureId: string;
};
if (!projectPath || !featureId) {
res
.status(400)
.json({
success: false,
error: "projectPath and featureId required",
});
return;
}
const worktreePath = path.join(
projectPath,
".automaker",
"worktrees",
featureId
);
try {
// Remove worktree
await execAsync(`git worktree remove "${worktreePath}" --force`, {
cwd: projectPath,
});
// Delete branch
await execAsync(`git branch -D feature/${featureId}`, {
cwd: projectPath,
});
res.json({ success: true, removedPath: worktreePath });
} catch (error) {
// Worktree might not exist
res.json({ success: true, removedPath: null });
}
} catch (error) {
logError(error, "Revert worktree failed");
res.status(500).json({ success: false, error: getErrorMessage(error) });
}
};
}

View File

@@ -0,0 +1,61 @@
/**
* POST /start-dev endpoint - Start a dev server for a worktree
*
* Spins up a development server (npm run dev) in the worktree directory
* on a unique port, allowing preview of the worktree's changes without
* affecting the main dev server.
*/
import type { Request, Response } from "express";
import { getDevServerService } from "../../../services/dev-server-service.js";
import { getErrorMessage, logError } from "../common.js";
export function createStartDevHandler() {
return async (req: Request, res: Response): Promise<void> => {
try {
const { projectPath, worktreePath } = req.body as {
projectPath: string;
worktreePath: string;
};
if (!projectPath) {
res.status(400).json({
success: false,
error: "projectPath is required",
});
return;
}
if (!worktreePath) {
res.status(400).json({
success: false,
error: "worktreePath is required",
});
return;
}
const devServerService = getDevServerService();
const result = await devServerService.startDevServer(projectPath, worktreePath);
if (result.success && result.result) {
res.json({
success: true,
result: {
worktreePath: result.result.worktreePath,
port: result.result.port,
url: result.result.url,
message: result.result.message,
},
});
} else {
res.status(400).json({
success: false,
error: result.error || "Failed to start dev server",
});
}
} catch (error) {
logError(error, "Start dev server failed");
res.status(500).json({ success: false, error: getErrorMessage(error) });
}
};
}

View File

@@ -29,12 +29,8 @@ export function createStatusHandler() {
return;
}
const worktreePath = path.join(
projectPath,
".automaker",
"worktrees",
featureId
);
// Git worktrees are stored in project directory
const worktreePath = path.join(projectPath, ".worktrees", featureId);
try {
await fs.access(worktreePath);

View File

@@ -0,0 +1,49 @@
/**
* POST /stop-dev endpoint - Stop a dev server for a worktree
*
* Stops the development server running for a specific worktree,
* freeing up the ports for reuse.
*/
import type { Request, Response } from "express";
import { getDevServerService } from "../../../services/dev-server-service.js";
import { getErrorMessage, logError } from "../common.js";
export function createStopDevHandler() {
return async (req: Request, res: Response): Promise<void> => {
try {
const { worktreePath } = req.body as {
worktreePath: string;
};
if (!worktreePath) {
res.status(400).json({
success: false,
error: "worktreePath is required",
});
return;
}
const devServerService = getDevServerService();
const result = await devServerService.stopDevServer(worktreePath);
if (result.success && result.result) {
res.json({
success: true,
result: {
worktreePath: result.result.worktreePath,
message: result.result.message,
},
});
} else {
res.status(400).json({
success: false,
error: result.error || "Failed to stop dev server",
});
}
} catch (error) {
logError(error, "Stop dev server failed");
res.status(500).json({ success: false, error: getErrorMessage(error) });
}
};
}

View File

@@ -0,0 +1,139 @@
/**
* POST /switch-branch endpoint - Switch to an existing branch
*
* Simple branch switching.
* If there are uncommitted changes, the switch will fail and
* the user should commit first.
*/
import type { Request, Response } from "express";
import { exec } from "child_process";
import { promisify } from "util";
import { getErrorMessage, logError } from "../common.js";
const execAsync = promisify(exec);
/**
* Check if there are uncommitted changes in the working directory
* Excludes .worktrees/ directory which is created by automaker
*/
async function hasUncommittedChanges(cwd: string): Promise<boolean> {
try {
const { stdout } = await execAsync("git status --porcelain", { cwd });
const lines = stdout.trim().split("\n").filter((line) => {
if (!line.trim()) return false;
// Exclude .worktrees/ directory (created by automaker)
if (line.includes(".worktrees/") || line.endsWith(".worktrees")) return false;
return true;
});
return lines.length > 0;
} catch {
return false;
}
}
/**
* Get a summary of uncommitted changes for user feedback
* Excludes .worktrees/ directory
*/
async function getChangesSummary(cwd: string): Promise<string> {
try {
const { stdout } = await execAsync("git status --short", { cwd });
const lines = stdout.trim().split("\n").filter((line) => {
if (!line.trim()) return false;
// Exclude .worktrees/ directory
if (line.includes(".worktrees/") || line.endsWith(".worktrees")) return false;
return true;
});
if (lines.length === 0) return "";
if (lines.length <= 5) return lines.join(", ");
return `${lines.slice(0, 5).join(", ")} and ${lines.length - 5} more files`;
} catch {
return "unknown changes";
}
}
export function createSwitchBranchHandler() {
return async (req: Request, res: Response): Promise<void> => {
try {
const { worktreePath, branchName } = req.body as {
worktreePath: string;
branchName: string;
};
if (!worktreePath) {
res.status(400).json({
success: false,
error: "worktreePath required",
});
return;
}
if (!branchName) {
res.status(400).json({
success: false,
error: "branchName required",
});
return;
}
// Get current branch
const { stdout: currentBranchOutput } = await execAsync(
"git rev-parse --abbrev-ref HEAD",
{ cwd: worktreePath }
);
const previousBranch = currentBranchOutput.trim();
if (previousBranch === branchName) {
res.json({
success: true,
result: {
previousBranch,
currentBranch: branchName,
message: `Already on branch '${branchName}'`,
},
});
return;
}
// Check if branch exists
try {
await execAsync(`git rev-parse --verify ${branchName}`, {
cwd: worktreePath,
});
} catch {
res.status(400).json({
success: false,
error: `Branch '${branchName}' does not exist`,
});
return;
}
// Check for uncommitted changes
if (await hasUncommittedChanges(worktreePath)) {
const summary = await getChangesSummary(worktreePath);
res.status(400).json({
success: false,
error: `Cannot switch branches: you have uncommitted changes (${summary}). Please commit your changes first.`,
code: "UNCOMMITTED_CHANGES",
});
return;
}
// Switch to the target branch
await execAsync(`git checkout "${branchName}"`, { cwd: worktreePath });
res.json({
success: true,
result: {
previousBranch,
currentBranch: branchName,
message: `Switched to branch '${branchName}'`,
},
});
} catch (error) {
logError(error, "Switch branch failed");
res.status(500).json({ success: false, error: getErrorMessage(error) });
}
};
}

View File

@@ -22,6 +22,12 @@ import { createAutoModeOptions } from "../lib/sdk-options.js";
import { isAbortError, classifyError } from "../lib/error-handler.js";
import { resolveDependencies, areDependenciesSatisfied } from "../lib/dependency-resolver.js";
import type { Feature } from "./feature-loader.js";
import {
getFeatureDir,
getFeaturesDir,
getAutomakerDir,
getWorktreesDir,
} from "../lib/automaker-paths.js";
const execAsync = promisify(exec);
@@ -160,12 +166,18 @@ export class AutoModeService {
/**
* Execute a single feature
* @param projectPath - The main project path
* @param featureId - The feature ID to execute
* @param useWorktrees - Whether to use worktrees for isolation
* @param isAutoMode - Whether this is running in auto mode
* @param providedWorktreePath - Optional: use this worktree path instead of creating a new one
*/
async executeFeature(
projectPath: string,
featureId: string,
useWorktrees = true,
isAutoMode = false
useWorktrees = false,
isAutoMode = false,
providedWorktreePath?: string
): Promise<void> {
if (this.runningFeatures.has(featureId)) {
throw new Error(`Feature ${featureId} is already running`);
@@ -175,8 +187,29 @@ export class AutoModeService {
const branchName = `feature/${featureId}`;
let worktreePath: string | null = null;
// Setup worktree if enabled
if (useWorktrees) {
// Use provided worktree path if given, otherwise setup new worktree if enabled
if (providedWorktreePath) {
// Resolve to absolute path - critical for cross-platform compatibility
// On Windows, relative paths or paths with forward slashes may not work correctly with cwd
// On all platforms, absolute paths ensure commands execute in the correct directory
try {
// Resolve relative paths relative to projectPath, absolute paths as-is
const resolvedPath = path.isAbsolute(providedWorktreePath)
? path.resolve(providedWorktreePath)
: path.resolve(projectPath, providedWorktreePath);
// Verify the path exists before using it
await fs.access(resolvedPath);
worktreePath = resolvedPath;
console.log(`[AutoMode] Using provided worktree path (resolved): ${worktreePath}`);
} catch (error) {
console.error(`[AutoMode] Provided worktree path invalid or doesn't exist: ${providedWorktreePath}`, error);
// Fall through to create new worktree or use project path
}
}
if (!worktreePath && useWorktrees) {
// No specific worktree provided, create a new one for this feature
worktreePath = await this.setupWorktree(
projectPath,
featureId,
@@ -184,7 +217,8 @@ export class AutoModeService {
);
}
const workDir = worktreePath || projectPath;
// Ensure workDir is always an absolute path for cross-platform compatibility
const workDir = worktreePath ? path.resolve(worktreePath) : path.resolve(projectPath);
this.runningFeatures.set(featureId, {
featureId,
@@ -300,16 +334,11 @@ export class AutoModeService {
async resumeFeature(
projectPath: string,
featureId: string,
useWorktrees = true
useWorktrees = false
): Promise<void> {
// Check if context exists
const contextPath = path.join(
projectPath,
".automaker",
"features",
featureId,
"agent-output.md"
);
// Check if context exists in .automaker directory
const featureDir = getFeatureDir(projectPath, featureId);
const contextPath = path.join(featureDir, "agent-output.md");
let hasContext = false;
try {
@@ -341,7 +370,8 @@ export class AutoModeService {
projectPath: string,
featureId: string,
prompt: string,
imagePaths?: string[]
imagePaths?: string[],
providedWorktreePath?: string
): Promise<void> {
if (this.runningFeatures.has(featureId)) {
throw new Error(`Feature ${featureId} is already running`);
@@ -349,33 +379,35 @@ export class AutoModeService {
const abortController = new AbortController();
// Check if worktree exists
const worktreePath = path.join(
projectPath,
".automaker",
"worktrees",
featureId
);
let workDir = projectPath;
// Use the provided worktreePath (from the feature's assigned branch)
// Fall back to project path if not provided
let workDir = path.resolve(projectPath);
let worktreePath: string | null = null;
try {
await fs.access(worktreePath);
workDir = worktreePath;
} catch {
// No worktree, use project path
if (providedWorktreePath) {
try {
// Resolve to absolute path - critical for cross-platform compatibility
// On Windows, relative paths or paths with forward slashes may not work correctly with cwd
// On all platforms, absolute paths ensure commands execute in the correct directory
const resolvedPath = path.isAbsolute(providedWorktreePath)
? path.resolve(providedWorktreePath)
: path.resolve(projectPath, providedWorktreePath);
await fs.access(resolvedPath);
workDir = resolvedPath;
worktreePath = resolvedPath;
} catch {
// Worktree path provided but doesn't exist, use project path
console.log(`[AutoMode] Provided worktreePath doesn't exist: ${providedWorktreePath}, using project path`);
}
}
// Load feature info for context
const feature = await this.loadFeature(projectPath, featureId);
// Load previous agent output if it exists
const contextPath = path.join(
projectPath,
".automaker",
"features",
featureId,
"agent-output.md"
);
const featureDir = getFeatureDir(projectPath, featureId);
const contextPath = path.join(featureDir, "agent-output.md");
let previousContext = "";
try {
previousContext = await fs.readFile(contextPath, "utf-8");
@@ -408,8 +440,8 @@ Address the follow-up instructions above. Review the previous work and make the
this.runningFeatures.set(featureId, {
featureId,
projectPath,
worktreePath: workDir !== projectPath ? worktreePath : null,
branchName: `feature/${featureId}`,
worktreePath,
branchName: worktreePath ? path.basename(worktreePath) : null,
abortController,
isAutoMode: false,
startTime: Date.now(),
@@ -438,13 +470,8 @@ Address the follow-up instructions above. Review the previous work and make the
// Copy follow-up images to feature folder
const copiedImagePaths: string[] = [];
if (imagePaths && imagePaths.length > 0) {
const featureImagesDir = path.join(
projectPath,
".automaker",
"features",
featureId,
"images"
);
const featureDirForImages = getFeatureDir(projectPath, featureId);
const featureImagesDir = path.join(featureDirForImages, "images");
await fs.mkdir(featureImagesDir, { recursive: true });
@@ -457,15 +484,8 @@ Address the follow-up instructions above. Review the previous work and make the
// Copy the image
await fs.copyFile(imagePath, destPath);
// Store the relative path (like FeatureLoader does)
const relativePath = path.join(
".automaker",
"features",
featureId,
"images",
filename
);
copiedImagePaths.push(relativePath);
// Store the absolute path (external storage uses absolute paths)
copiedImagePaths.push(destPath);
} catch (error) {
console.error(
`[AutoMode] Failed to copy follow-up image ${imagePath}:`,
@@ -500,13 +520,8 @@ Address the follow-up instructions above. Review the previous work and make the
// Save updated feature.json with new images
if (copiedImagePaths.length > 0 && feature) {
const featurePath = path.join(
projectPath,
".automaker",
"features",
featureId,
"feature.json"
);
const featureDirForSave = getFeatureDir(projectPath, featureId);
const featurePath = path.join(featureDirForSave, "feature.json");
try {
await fs.writeFile(featurePath, JSON.stringify(feature, null, 2));
@@ -558,12 +573,8 @@ Address the follow-up instructions above. Review the previous work and make the
projectPath: string,
featureId: string
): Promise<boolean> {
const worktreePath = path.join(
projectPath,
".automaker",
"worktrees",
featureId
);
// Worktrees are in project dir
const worktreePath = path.join(projectPath, ".worktrees", featureId);
let workDir = projectPath;
try {
@@ -622,24 +633,36 @@ Address the follow-up instructions above. Review the previous work and make the
/**
* Commit feature changes
* @param projectPath - The main project path
* @param featureId - The feature ID to commit
* @param providedWorktreePath - Optional: the worktree path where the feature's changes are located
*/
async commitFeature(
projectPath: string,
featureId: string
featureId: string,
providedWorktreePath?: string
): Promise<string | null> {
const worktreePath = path.join(
projectPath,
".automaker",
"worktrees",
featureId
);
let workDir = projectPath;
try {
await fs.access(worktreePath);
workDir = worktreePath;
} catch {
// No worktree
// Use the provided worktree path if given
if (providedWorktreePath) {
try {
await fs.access(providedWorktreePath);
workDir = providedWorktreePath;
console.log(`[AutoMode] Committing in provided worktree: ${workDir}`);
} catch {
console.log(`[AutoMode] Provided worktree path doesn't exist: ${providedWorktreePath}, using project path`);
}
} else {
// Fallback: try to find worktree at legacy location
const legacyWorktreePath = path.join(projectPath, ".worktrees", featureId);
try {
await fs.access(legacyWorktreePath);
workDir = legacyWorktreePath;
console.log(`[AutoMode] Committing in legacy worktree: ${workDir}`);
} catch {
console.log(`[AutoMode] No worktree found, committing in project path: ${workDir}`);
}
}
try {
@@ -690,13 +713,9 @@ Address the follow-up instructions above. Review the previous work and make the
projectPath: string,
featureId: string
): Promise<boolean> {
const contextPath = path.join(
projectPath,
".automaker",
"features",
featureId,
"agent-output.md"
);
// Context is stored in .automaker directory
const featureDir = getFeatureDir(projectPath, featureId);
const contextPath = path.join(featureDir, "agent-output.md");
try {
await fs.access(contextPath);
@@ -769,13 +788,10 @@ Format your response as a structured markdown document.`;
}
}
// Save analysis
const analysisPath = path.join(
projectPath,
".automaker",
"project-analysis.md"
);
await fs.mkdir(path.dirname(analysisPath), { recursive: true });
// Save analysis to .automaker directory
const automakerDir = getAutomakerDir(projectPath);
const analysisPath = path.join(automakerDir, "project-analysis.md");
await fs.mkdir(automakerDir, { recursive: true });
await fs.writeFile(analysisPath, analysisResult);
this.emitAutoModeEvent("auto_mode_feature_complete", {
@@ -829,20 +845,82 @@ Format your response as a structured markdown document.`;
// Private helpers
/**
* Find an existing worktree for a given branch by checking git worktree list
*/
private async findExistingWorktreeForBranch(
projectPath: string,
branchName: string
): Promise<string | null> {
try {
const { stdout } = await execAsync("git worktree list --porcelain", {
cwd: projectPath,
});
const lines = stdout.split("\n");
let currentPath: string | null = null;
let currentBranch: string | null = null;
for (const line of lines) {
if (line.startsWith("worktree ")) {
currentPath = line.slice(9);
} else if (line.startsWith("branch ")) {
currentBranch = line.slice(7).replace("refs/heads/", "");
} else if (line === "" && currentPath && currentBranch) {
// End of a worktree entry
if (currentBranch === branchName) {
// Resolve to absolute path - git may return relative paths
// On Windows, this is critical for cwd to work correctly
// On all platforms, absolute paths ensure consistent behavior
const resolvedPath = path.isAbsolute(currentPath)
? path.resolve(currentPath)
: path.resolve(projectPath, currentPath);
return resolvedPath;
}
currentPath = null;
currentBranch = null;
}
}
// Check the last entry (if file doesn't end with newline)
if (currentPath && currentBranch && currentBranch === branchName) {
// Resolve to absolute path for cross-platform compatibility
const resolvedPath = path.isAbsolute(currentPath)
? path.resolve(currentPath)
: path.resolve(projectPath, currentPath);
return resolvedPath;
}
return null;
} catch {
return null;
}
}
private async setupWorktree(
projectPath: string,
featureId: string,
branchName: string
): Promise<string> {
const worktreesDir = path.join(projectPath, ".automaker", "worktrees");
// First, check if git already has a worktree for this branch (anywhere)
const existingWorktree = await this.findExistingWorktreeForBranch(projectPath, branchName);
if (existingWorktree) {
// Path is already resolved to absolute in findExistingWorktreeForBranch
console.log(`[AutoMode] Found existing worktree for branch "${branchName}" at: ${existingWorktree}`);
return existingWorktree;
}
// Git worktrees stay in project directory
const worktreesDir = path.join(projectPath, ".worktrees");
const worktreePath = path.join(worktreesDir, featureId);
await fs.mkdir(worktreesDir, { recursive: true });
// Check if worktree already exists
// Check if worktree directory already exists (might not be linked to branch)
try {
await fs.access(worktreePath);
return worktreePath;
// Return absolute path for cross-platform compatibility
return path.resolve(worktreePath);
} catch {
// Create new worktree
}
@@ -859,26 +937,22 @@ Format your response as a structured markdown document.`;
await execAsync(`git worktree add "${worktreePath}" ${branchName}`, {
cwd: projectPath,
});
// Return absolute path for cross-platform compatibility
return path.resolve(worktreePath);
} catch (error) {
// Worktree creation failed, fall back to direct execution
console.error(`[AutoMode] Worktree creation failed:`, error);
return projectPath;
return path.resolve(projectPath);
}
return worktreePath;
}
private async loadFeature(
projectPath: string,
featureId: string
): Promise<Feature | null> {
const featurePath = path.join(
projectPath,
".automaker",
"features",
featureId,
"feature.json"
);
// Features are stored in .automaker directory
const featureDir = getFeatureDir(projectPath, featureId);
const featurePath = path.join(featureDir, "feature.json");
try {
const data = await fs.readFile(featurePath, "utf-8");
@@ -893,13 +967,9 @@ Format your response as a structured markdown document.`;
featureId: string,
status: string
): Promise<void> {
const featurePath = path.join(
projectPath,
".automaker",
"features",
featureId,
"feature.json"
);
// Features are stored in .automaker directory
const featureDir = getFeatureDir(projectPath, featureId);
const featurePath = path.join(featureDir, "feature.json");
try {
const data = await fs.readFile(featurePath, "utf-8");
@@ -921,7 +991,8 @@ Format your response as a structured markdown document.`;
}
private async loadPendingFeatures(projectPath: string): Promise<Feature[]> {
const featuresDir = path.join(projectPath, ".automaker", "features");
// Features are stored in .automaker directory
const featuresDir = getFeaturesDir(projectPath);
try {
const entries = await fs.readdir(featuresDir, { withFileTypes: true });
@@ -1079,6 +1150,64 @@ When done, summarize what you implemented and any notes for the developer.`;
imagePaths?: string[],
model?: string
): Promise<void> {
// CI/CD Mock Mode: Return early with mock response when AUTOMAKER_MOCK_AGENT is set
// This prevents actual API calls during automated testing
if (process.env.AUTOMAKER_MOCK_AGENT === "true") {
console.log(`[AutoMode] MOCK MODE: Skipping real agent execution for feature ${featureId}`);
// Simulate some work being done
await this.sleep(500);
// Emit mock progress events to simulate agent activity
this.emitAutoModeEvent("auto_mode_progress", {
featureId,
content: "Mock agent: Analyzing the codebase...",
});
await this.sleep(300);
this.emitAutoModeEvent("auto_mode_progress", {
featureId,
content: "Mock agent: Implementing the feature...",
});
await this.sleep(300);
// Create a mock file with "yellow" content as requested in the test
const mockFilePath = path.join(workDir, "yellow.txt");
await fs.writeFile(mockFilePath, "yellow");
this.emitAutoModeEvent("auto_mode_progress", {
featureId,
content: "Mock agent: Created yellow.txt file with content 'yellow'",
});
await this.sleep(200);
// Save mock agent output
const configProjectPath = this.config?.projectPath || workDir;
const featureDirForOutput = getFeatureDir(configProjectPath, featureId);
const outputPath = path.join(featureDirForOutput, "agent-output.md");
const mockOutput = `# Mock Agent Output
## Summary
This is a mock agent response for CI/CD testing.
## Changes Made
- Created \`yellow.txt\` with content "yellow"
## Notes
This mock response was generated because AUTOMAKER_MOCK_AGENT=true was set.
`;
await fs.mkdir(path.dirname(outputPath), { recursive: true });
await fs.writeFile(outputPath, mockOutput);
console.log(`[AutoMode] MOCK MODE: Completed mock execution for feature ${featureId}`);
return;
}
// Build SDK options using centralized configuration for feature implementation
const sdkOptions = createAutoModeOptions({
cwd: workDir,
@@ -1122,13 +1251,12 @@ When done, summarize what you implemented and any notes for the developer.`;
// Execute via provider
const stream = provider.executeQuery(options);
let responseText = "";
const outputPath = path.join(
workDir,
".automaker",
"features",
featureId,
"agent-output.md"
);
// Agent output goes to .automaker directory
// Note: We use the original projectPath here (from config), not workDir
// because workDir might be a worktree path
const configProjectPath = this.config?.projectPath || workDir;
const featureDirForOutput = getFeatureDir(configProjectPath, featureId);
const outputPath = path.join(featureDirForOutput, "agent-output.md");
for await (const msg of stream) {
if (msg.type === "assistant" && msg.message?.content) {

View File

@@ -0,0 +1,460 @@
/**
* Dev Server Service
*
* Manages multiple development server processes for git worktrees.
* Each worktree can have its own dev server running on a unique port.
*
* Developers should configure their projects to use the PORT environment variable.
*/
import { spawn, execSync, type ChildProcess } from "child_process";
import { existsSync } from "fs";
import path from "path";
import net from "net";
export interface DevServerInfo {
worktreePath: string;
port: number;
url: string;
process: ChildProcess | null;
startedAt: Date;
}
// Port allocation starts at 3001 to avoid conflicts with common dev ports
const BASE_PORT = 3001;
const MAX_PORT = 3099; // Safety limit
class DevServerService {
private runningServers: Map<string, DevServerInfo> = new Map();
private allocatedPorts: Set<number> = new Set();
/**
* Check if a port is available (not in use by system or by us)
*/
private async isPortAvailable(port: number): Promise<boolean> {
// First check if we've already allocated it
if (this.allocatedPorts.has(port)) {
return false;
}
// Then check if the system has it in use
return new Promise((resolve) => {
const server = net.createServer();
server.once("error", () => resolve(false));
server.once("listening", () => {
server.close();
resolve(true);
});
server.listen(port, "127.0.0.1");
});
}
/**
* Kill any process running on the given port
*/
private killProcessOnPort(port: number): void {
try {
if (process.platform === "win32") {
// Windows: find and kill process on port
const result = execSync(`netstat -ano | findstr :${port}`, { encoding: "utf-8" });
const lines = result.trim().split("\n");
const pids = new Set<string>();
for (const line of lines) {
const parts = line.trim().split(/\s+/);
const pid = parts[parts.length - 1];
if (pid && pid !== "0") {
pids.add(pid);
}
}
for (const pid of pids) {
try {
execSync(`taskkill /F /PID ${pid}`, { stdio: "ignore" });
console.log(`[DevServerService] Killed process ${pid} on port ${port}`);
} catch {
// Process may have already exited
}
}
} else {
// macOS/Linux: use lsof to find and kill process
try {
const result = execSync(`lsof -ti:${port}`, { encoding: "utf-8" });
const pids = result.trim().split("\n").filter(Boolean);
for (const pid of pids) {
try {
execSync(`kill -9 ${pid}`, { stdio: "ignore" });
console.log(`[DevServerService] Killed process ${pid} on port ${port}`);
} catch {
// Process may have already exited
}
}
} catch {
// No process found on port, which is fine
}
}
} catch (error) {
// Ignore errors - port might not have any process
console.log(`[DevServerService] No process to kill on port ${port}`);
}
}
/**
* Find the next available port, killing any process on it first
*/
private async findAvailablePort(): Promise<number> {
let port = BASE_PORT;
while (port <= MAX_PORT) {
// Skip ports we've already allocated internally
if (this.allocatedPorts.has(port)) {
port++;
continue;
}
// Force kill any process on this port before checking availability
// This ensures we can claim the port even if something stale is holding it
this.killProcessOnPort(port);
// Small delay to let the port be released
await new Promise((resolve) => setTimeout(resolve, 100));
// Now check if it's available
if (await this.isPortAvailable(port)) {
return port;
}
port++;
}
throw new Error(`No available ports found between ${BASE_PORT} and ${MAX_PORT}`);
}
/**
* Detect the package manager used in a directory
*/
private detectPackageManager(
dir: string
): "npm" | "yarn" | "pnpm" | "bun" | null {
if (existsSync(path.join(dir, "bun.lockb"))) return "bun";
if (existsSync(path.join(dir, "pnpm-lock.yaml"))) return "pnpm";
if (existsSync(path.join(dir, "yarn.lock"))) return "yarn";
if (existsSync(path.join(dir, "package-lock.json"))) return "npm";
if (existsSync(path.join(dir, "package.json"))) return "npm"; // Default
return null;
}
/**
* Get the dev script command for a directory
*/
private getDevCommand(dir: string): { cmd: string; args: string[] } | null {
const pm = this.detectPackageManager(dir);
if (!pm) return null;
switch (pm) {
case "bun":
return { cmd: "bun", args: ["run", "dev"] };
case "pnpm":
return { cmd: "pnpm", args: ["run", "dev"] };
case "yarn":
return { cmd: "yarn", args: ["dev"] };
case "npm":
default:
return { cmd: "npm", args: ["run", "dev"] };
}
}
/**
* Start a dev server for a worktree
*/
async startDevServer(
projectPath: string,
worktreePath: string
): Promise<{
success: boolean;
result?: {
worktreePath: string;
port: number;
url: string;
message: string;
};
error?: string;
}> {
// Check if already running
if (this.runningServers.has(worktreePath)) {
const existing = this.runningServers.get(worktreePath)!;
return {
success: true,
result: {
worktreePath: existing.worktreePath,
port: existing.port,
url: existing.url,
message: `Dev server already running on port ${existing.port}`,
},
};
}
// Verify the worktree exists
if (!existsSync(worktreePath)) {
return {
success: false,
error: `Worktree path does not exist: ${worktreePath}`,
};
}
// Check for package.json
const packageJsonPath = path.join(worktreePath, "package.json");
if (!existsSync(packageJsonPath)) {
return {
success: false,
error: `No package.json found in: ${worktreePath}`,
};
}
// Get dev command
const devCommand = this.getDevCommand(worktreePath);
if (!devCommand) {
return {
success: false,
error: `Could not determine dev command for: ${worktreePath}`,
};
}
// Find available port
let port: number;
try {
port = await this.findAvailablePort();
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : "Port allocation failed",
};
}
// Reserve the port (port was already force-killed in findAvailablePort)
this.allocatedPorts.add(port);
// Also kill common related ports (livereload uses 35729 by default)
// Some dev servers use fixed ports for HMR/livereload regardless of main port
const commonRelatedPorts = [35729, 35730, 35731];
for (const relatedPort of commonRelatedPorts) {
this.killProcessOnPort(relatedPort);
}
// Small delay to ensure related ports are freed
await new Promise((resolve) => setTimeout(resolve, 100));
console.log(
`[DevServerService] Starting dev server on port ${port}`
);
console.log(
`[DevServerService] Working directory (cwd): ${worktreePath}`
);
console.log(
`[DevServerService] Command: ${devCommand.cmd} ${devCommand.args.join(" ")} with PORT=${port}`
);
// Spawn the dev process with PORT environment variable
const env = {
...process.env,
PORT: String(port),
};
const devProcess = spawn(devCommand.cmd, devCommand.args, {
cwd: worktreePath,
env,
stdio: ["ignore", "pipe", "pipe"],
detached: false,
});
// Track if process failed early using object to work around TypeScript narrowing
const status = { error: null as string | null, exited: false };
// Log output for debugging
if (devProcess.stdout) {
devProcess.stdout.on("data", (data: Buffer) => {
console.log(`[DevServer:${port}] ${data.toString().trim()}`);
});
}
if (devProcess.stderr) {
devProcess.stderr.on("data", (data: Buffer) => {
const msg = data.toString().trim();
console.error(`[DevServer:${port}] ${msg}`);
});
}
devProcess.on("error", (error) => {
console.error(`[DevServerService] Process error:`, error);
status.error = error.message;
this.allocatedPorts.delete(port);
this.runningServers.delete(worktreePath);
});
devProcess.on("exit", (code) => {
console.log(
`[DevServerService] Process for ${worktreePath} exited with code ${code}`
);
status.exited = true;
this.allocatedPorts.delete(port);
this.runningServers.delete(worktreePath);
});
// Wait a moment to see if the process fails immediately
await new Promise((resolve) => setTimeout(resolve, 500));
if (status.error) {
return {
success: false,
error: `Failed to start dev server: ${status.error}`,
};
}
if (status.exited) {
return {
success: false,
error: `Dev server process exited immediately. Check server logs for details.`,
};
}
const serverInfo: DevServerInfo = {
worktreePath,
port,
url: `http://localhost:${port}`,
process: devProcess,
startedAt: new Date(),
};
this.runningServers.set(worktreePath, serverInfo);
return {
success: true,
result: {
worktreePath,
port,
url: `http://localhost:${port}`,
message: `Dev server started on port ${port}`,
},
};
}
/**
* Stop a dev server for a worktree
*/
async stopDevServer(worktreePath: string): Promise<{
success: boolean;
result?: { worktreePath: string; message: string };
error?: string;
}> {
const server = this.runningServers.get(worktreePath);
// If we don't have a record of this server, it may have crashed/exited on its own
// Return success so the frontend can clear its state
if (!server) {
console.log(`[DevServerService] No server record for ${worktreePath}, may have already stopped`);
return {
success: true,
result: {
worktreePath,
message: `Dev server already stopped`,
},
};
}
console.log(`[DevServerService] Stopping dev server for ${worktreePath}`);
// Kill the process
if (server.process && !server.process.killed) {
server.process.kill("SIGTERM");
}
// Free the port
this.allocatedPorts.delete(server.port);
this.runningServers.delete(worktreePath);
return {
success: true,
result: {
worktreePath,
message: `Stopped dev server on port ${server.port}`,
},
};
}
/**
* List all running dev servers
*/
listDevServers(): {
success: boolean;
result: {
servers: Array<{
worktreePath: string;
port: number;
url: string;
}>;
};
} {
const servers = Array.from(this.runningServers.values()).map((s) => ({
worktreePath: s.worktreePath,
port: s.port,
url: s.url,
}));
return {
success: true,
result: { servers },
};
}
/**
* Check if a worktree has a running dev server
*/
isRunning(worktreePath: string): boolean {
return this.runningServers.has(worktreePath);
}
/**
* Get info for a specific worktree's dev server
*/
getServerInfo(worktreePath: string): DevServerInfo | undefined {
return this.runningServers.get(worktreePath);
}
/**
* Get all allocated ports
*/
getAllocatedPorts(): number[] {
return Array.from(this.allocatedPorts);
}
/**
* Stop all running dev servers (for cleanup)
*/
async stopAll(): Promise<void> {
console.log(`[DevServerService] Stopping all ${this.runningServers.size} dev servers`);
for (const [worktreePath] of this.runningServers) {
await this.stopDevServer(worktreePath);
}
}
}
// Singleton instance
let devServerServiceInstance: DevServerService | null = null;
export function getDevServerService(): DevServerService {
if (!devServerServiceInstance) {
devServerServiceInstance = new DevServerService();
}
return devServerServiceInstance;
}
// Cleanup on process exit
process.on("SIGTERM", async () => {
if (devServerServiceInstance) {
await devServerServiceInstance.stopAll();
}
});
process.on("SIGINT", async () => {
if (devServerServiceInstance) {
await devServerServiceInstance.stopAll();
}
});

View File

@@ -5,6 +5,12 @@
import path from "path";
import fs from "fs/promises";
import {
getFeaturesDir,
getFeatureDir,
getFeatureImagesDir,
ensureAutomakerDir,
} from "../lib/automaker-paths.js";
export interface Feature {
id: string;
@@ -26,14 +32,14 @@ export class FeatureLoader {
* Get the features directory path
*/
getFeaturesDir(projectPath: string): string {
return path.join(projectPath, ".automaker", "features");
return getFeaturesDir(projectPath);
}
/**
* Get the images directory path for a feature
*/
getFeatureImagesDir(projectPath: string, featureId: string): string {
return path.join(this.getFeatureDir(projectPath, featureId), "images");
return getFeatureImagesDir(projectPath, featureId);
}
/**
@@ -60,15 +66,15 @@ export class FeatureLoader {
for (const oldPath of oldPathSet) {
if (!newPathSet.has(oldPath)) {
try {
const fullPath = path.isAbsolute(oldPath)
? oldPath
: path.join(projectPath, oldPath);
await fs.unlink(fullPath);
// Paths are now absolute
await fs.unlink(oldPath);
console.log(`[FeatureLoader] Deleted orphaned image: ${oldPath}`);
} catch (error) {
// Ignore errors when deleting (file may already be gone)
console.warn(`[FeatureLoader] Failed to delete image: ${oldPath}`, error);
console.warn(
`[FeatureLoader] Failed to delete image: ${oldPath}`,
error
);
}
}
}
@@ -81,7 +87,9 @@ export class FeatureLoader {
projectPath: string,
featureId: string,
imagePaths?: Array<string | { path: string; [key: string]: unknown }>
): Promise<Array<string | { path: string; [key: string]: unknown }> | undefined> {
): Promise<
Array<string | { path: string; [key: string]: unknown }> | undefined
> {
if (!imagePaths || imagePaths.length === 0) {
return imagePaths;
}
@@ -89,13 +97,15 @@ export class FeatureLoader {
const featureImagesDir = this.getFeatureImagesDir(projectPath, featureId);
await fs.mkdir(featureImagesDir, { recursive: true });
const updatedPaths: Array<string | { path: string; [key: string]: unknown }> = [];
const updatedPaths: Array<string | { path: string; [key: string]: unknown }> =
[];
for (const imagePath of imagePaths) {
try {
const originalPath = typeof imagePath === "string" ? imagePath : imagePath.path;
const originalPath =
typeof imagePath === "string" ? imagePath : imagePath.path;
// Skip if already in feature directory
// Skip if already in feature directory (already absolute path in external storage)
if (originalPath.includes(`/features/${featureId}/images/`)) {
updatedPaths.push(imagePath);
continue;
@@ -110,18 +120,21 @@ export class FeatureLoader {
try {
await fs.access(fullOriginalPath);
} catch {
console.warn(`[FeatureLoader] Image not found, skipping: ${fullOriginalPath}`);
console.warn(
`[FeatureLoader] Image not found, skipping: ${fullOriginalPath}`
);
continue;
}
// Get filename and create new path
// Get filename and create new path in external storage
const filename = path.basename(originalPath);
const newPath = path.join(featureImagesDir, filename);
const relativePath = `.automaker/features/${featureId}/images/${filename}`;
// Copy the file
await fs.copyFile(fullOriginalPath, newPath);
console.log(`[FeatureLoader] Copied image: ${originalPath} -> ${relativePath}`);
console.log(
`[FeatureLoader] Copied image: ${originalPath} -> ${newPath}`
);
// Try to delete the original temp file
try {
@@ -130,11 +143,11 @@ export class FeatureLoader {
// Ignore errors when deleting temp file
}
// Update the path in the result
// Update the path in the result (use absolute path)
if (typeof imagePath === "string") {
updatedPaths.push(relativePath);
updatedPaths.push(newPath);
} else {
updatedPaths.push({ ...imagePath, path: relativePath });
updatedPaths.push({ ...imagePath, path: newPath });
}
} catch (error) {
console.error(`[FeatureLoader] Failed to migrate image:`, error);
@@ -150,7 +163,7 @@ export class FeatureLoader {
* Get the path to a specific feature folder
*/
getFeatureDir(projectPath: string, featureId: string): string {
return path.join(this.getFeaturesDir(projectPath), featureId);
return getFeatureDir(projectPath, featureId);
}
/**
@@ -252,7 +265,10 @@ export class FeatureLoader {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
return null;
}
console.error(`[FeatureLoader] Failed to get feature ${featureId}:`, error);
console.error(
`[FeatureLoader] Failed to get feature ${featureId}:`,
error
);
throw error;
}
}
@@ -260,14 +276,16 @@ export class FeatureLoader {
/**
* Create a new feature
*/
async create(projectPath: string, featureData: Partial<Feature>): Promise<Feature> {
async create(
projectPath: string,
featureData: Partial<Feature>
): Promise<Feature> {
const featureId = featureData.id || this.generateFeatureId();
const featureDir = this.getFeatureDir(projectPath, featureId);
const featureJsonPath = this.getFeatureJsonPath(projectPath, featureId);
// Ensure features directory exists
const featuresDir = this.getFeaturesDir(projectPath);
await fs.mkdir(featuresDir, { recursive: true });
// Ensure automaker directory exists
await ensureAutomakerDir(projectPath);
// Create feature directory
await fs.mkdir(featureDir, { recursive: true });
@@ -289,7 +307,11 @@ export class FeatureLoader {
};
// Write feature.json
await fs.writeFile(featureJsonPath, JSON.stringify(feature, null, 2), "utf-8");
await fs.writeFile(
featureJsonPath,
JSON.stringify(feature, null, 2),
"utf-8"
);
console.log(`[FeatureLoader] Created feature ${featureId}`);
return feature;
@@ -330,7 +352,9 @@ export class FeatureLoader {
const updatedFeature: Feature = {
...feature,
...updates,
...(updatedImagePaths !== undefined ? { imagePaths: updatedImagePaths } : {}),
...(updatedImagePaths !== undefined
? { imagePaths: updatedImagePaths }
: {}),
};
// Write back to file
@@ -355,7 +379,10 @@ export class FeatureLoader {
console.log(`[FeatureLoader] Deleted feature ${featureId}`);
return true;
} catch (error) {
console.error(`[FeatureLoader] Failed to delete feature ${featureId}:`, error);
console.error(
`[FeatureLoader] Failed to delete feature ${featureId}:`,
error
);
return false;
}
}
@@ -401,7 +428,10 @@ export class FeatureLoader {
/**
* Delete agent output for a feature
*/
async deleteAgentOutput(projectPath: string, featureId: string): Promise<void> {
async deleteAgentOutput(
projectPath: string,
featureId: string
): Promise<void> {
try {
const agentOutputPath = this.getAgentOutputPath(projectPath, featureId);
await fs.unlink(agentOutputPath);