feat: enhance project initialization and improve logging in auto mode service

- Added a default categories.json file to the project initialization structure.
- Improved code formatting and readability in the auto-mode-service.ts file by restructuring console log statements and method calls.
- Updated feature status checks to include "backlog" in addition to "pending" and "ready".
This commit is contained in:
Cody Seibert
2025-12-14 00:43:52 -05:00
parent 58f466b443
commit b52b9ba236
8 changed files with 311 additions and 112 deletions

View File

@@ -26,6 +26,12 @@ export function initAllowedPaths(): void {
if (dataDir) {
allowedPaths.add(path.resolve(dataDir));
}
// Always allow the workspace directory (where projects are created)
const workspaceDir = process.env.WORKSPACE_DIR;
if (workspaceDir) {
allowedPaths.add(path.resolve(workspaceDir));
}
}
/**
@@ -58,7 +64,9 @@ export function validatePath(filePath: string): string {
const resolved = path.resolve(filePath);
if (!isPathAllowed(resolved)) {
throw new Error(`Access denied: ${filePath} is not in an allowed directory`);
throw new Error(
`Access denied: ${filePath} is not in an allowed directory`
);
}
return resolved;

View File

@@ -7,7 +7,11 @@ import { Router, type Request, type Response } from "express";
import fs from "fs/promises";
import os from "os";
import path from "path";
import { validatePath, addAllowedPath, isPathAllowed } from "../lib/security.js";
import {
validatePath,
addAllowedPath,
isPathAllowed,
} from "../lib/security.js";
import type { EventEmitter } from "../lib/events.js";
export function createFsRoutes(_events: EventEmitter): Router {
@@ -69,9 +73,41 @@ export function createFsRoutes(_events: EventEmitter): Router {
return;
}
const resolvedPath = validatePath(dirPath);
const resolvedPath = path.resolve(dirPath);
// Security check: allow paths in allowed directories OR within home directory
const isAllowed = (() => {
// Check if path or parent is in allowed paths
if (isPathAllowed(resolvedPath)) return true;
const parentPath = path.dirname(resolvedPath);
if (isPathAllowed(parentPath)) return true;
// Also allow within home directory (like the /browse endpoint)
const homeDir = os.homedir();
const normalizedHome = path.normalize(homeDir);
if (
resolvedPath === normalizedHome ||
resolvedPath.startsWith(normalizedHome + path.sep)
) {
return true;
}
return false;
})();
if (!isAllowed) {
res.status(403).json({
success: false,
error: `Access denied: ${dirPath} is not in an allowed directory`,
});
return;
}
await fs.mkdir(resolvedPath, { recursive: true });
// Add the new directory to allowed paths so subsequent operations work
addAllowedPath(resolvedPath);
res.json({ success: true });
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
@@ -197,7 +233,9 @@ export function createFsRoutes(_events: EventEmitter): Router {
const stats = await fs.stat(resolvedPath);
if (!stats.isDirectory()) {
res.status(400).json({ success: false, error: "Path is not a directory" });
res
.status(400)
.json({ success: false, error: "Path is not a directory" });
return;
}
@@ -229,7 +267,9 @@ export function createFsRoutes(_events: EventEmitter): Router {
};
if (!directoryName) {
res.status(400).json({ success: false, error: "directoryName is required" });
res
.status(400)
.json({ success: false, error: "directoryName is required" });
return;
}
@@ -254,10 +294,16 @@ export function createFsRoutes(_events: EventEmitter): Router {
const searchPaths: string[] = [
process.cwd(), // Current working directory
process.env.HOME || process.env.USERPROFILE || "", // User home
path.join(process.env.HOME || process.env.USERPROFILE || "", "Documents"),
path.join(
process.env.HOME || process.env.USERPROFILE || "",
"Documents"
),
path.join(process.env.HOME || process.env.USERPROFILE || "", "Desktop"),
// Common project locations
path.join(process.env.HOME || process.env.USERPROFILE || "", "Projects"),
path.join(
process.env.HOME || process.env.USERPROFILE || "",
"Projects"
),
].filter(Boolean);
// Also check parent of current working directory
@@ -275,7 +321,7 @@ export function createFsRoutes(_events: EventEmitter): Router {
try {
const candidatePath = path.join(searchPath, directoryName);
const stats = await fs.stat(candidatePath);
if (stats.isDirectory()) {
// Verify it matches by checking for sample files
if (sampleFiles && sampleFiles.length > 0) {
@@ -284,8 +330,10 @@ export function createFsRoutes(_events: EventEmitter): Router {
// Remove directory name prefix from sample file path
const relativeFile = sampleFile.startsWith(directoryName + "/")
? sampleFile.substring(directoryName.length + 1)
: sampleFile.split("/").slice(1).join("/") || sampleFile.split("/").pop() || sampleFile;
: sampleFile.split("/").slice(1).join("/") ||
sampleFile.split("/").pop() ||
sampleFile;
try {
const filePath = path.join(candidatePath, relativeFile);
await fs.access(filePath);
@@ -294,7 +342,7 @@ export function createFsRoutes(_events: EventEmitter): Router {
// File doesn't exist, continue checking
}
}
// If at least one file matches, consider it a match
if (matches === 0 && sampleFiles.length > 0) {
continue; // Try next candidate
@@ -405,7 +453,9 @@ export function createFsRoutes(_events: EventEmitter): Router {
const stats = await fs.stat(targetPath);
if (!stats.isDirectory()) {
res.status(400).json({ success: false, error: "Path is not a directory" });
res
.status(400)
.json({ success: false, error: "Path is not a directory" });
return;
}
@@ -438,7 +488,8 @@ export function createFsRoutes(_events: EventEmitter): Router {
} catch (error) {
res.status(400).json({
success: false,
error: error instanceof Error ? error.message : "Failed to read directory",
error:
error instanceof Error ? error.message : "Failed to read directory",
});
}
} catch (error) {
@@ -464,8 +515,8 @@ export function createFsRoutes(_events: EventEmitter): Router {
const fullPath = path.isAbsolute(imagePath)
? imagePath
: projectPath
? path.join(projectPath, imagePath)
: imagePath;
? path.join(projectPath, imagePath)
: imagePath;
// Check if file exists
try {
@@ -490,7 +541,10 @@ export function createFsRoutes(_events: EventEmitter): Router {
".bmp": "image/bmp",
};
res.setHeader("Content-Type", mimeTypes[ext] || "application/octet-stream");
res.setHeader(
"Content-Type",
mimeTypes[ext] || "application/octet-stream"
);
res.setHeader("Cache-Control", "public, max-age=3600");
res.send(buffer);
} catch (error) {
@@ -546,38 +600,42 @@ export function createFsRoutes(_events: EventEmitter): Router {
});
// Delete board background image
router.post("/delete-board-background", async (req: Request, res: Response) => {
try {
const { projectPath } = req.body as { projectPath: string };
if (!projectPath) {
res.status(400).json({
success: false,
error: "projectPath is required",
});
return;
}
const boardDir = path.join(projectPath, ".automaker", "board");
router.post(
"/delete-board-background",
async (req: Request, res: Response) => {
try {
// Try to remove all files in the board directory
const files = await fs.readdir(boardDir);
for (const file of files) {
if (file.startsWith("background")) {
await fs.unlink(path.join(boardDir, file));
}
}
} catch {
// Directory may not exist, that's fine
}
const { projectPath } = req.body as { projectPath: string };
res.json({ success: true });
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
res.status(500).json({ success: false, error: message });
if (!projectPath) {
res.status(400).json({
success: false,
error: "projectPath is required",
});
return;
}
const boardDir = path.join(projectPath, ".automaker", "board");
try {
// Try to remove all files in the board directory
const files = await fs.readdir(boardDir);
for (const file of files) {
if (file.startsWith("background")) {
await fs.unlink(path.join(boardDir, file));
}
}
} catch {
// Directory may not exist, that's fine
}
res.json({ success: true });
} catch (error) {
const message =
error instanceof Error ? error.message : "Unknown error";
res.status(500).json({ success: false, error: message });
}
}
});
);
// Browse directories for file picker
// SECURITY: Restricted to home directory, allowed paths, and drive roots on Windows
@@ -614,7 +672,10 @@ export function createFsRoutes(_events: EventEmitter): Router {
const normalizedHome = path.resolve(homeDir);
// Allow browsing within home directory
if (resolved === normalizedHome || resolved.startsWith(normalizedHome + path.sep)) {
if (
resolved === normalizedHome ||
resolved.startsWith(normalizedHome + path.sep)
) {
return true;
}
@@ -646,7 +707,8 @@ export function createFsRoutes(_events: EventEmitter): Router {
if (!isSafePath(targetPath)) {
res.status(403).json({
success: false,
error: "Access denied: browsing is restricted to your home directory and allowed project paths",
error:
"Access denied: browsing is restricted to your home directory and allowed project paths",
});
return;
}
@@ -655,7 +717,9 @@ export function createFsRoutes(_events: EventEmitter): Router {
const stats = await fs.stat(targetPath);
if (!stats.isDirectory()) {
res.status(400).json({ success: false, error: "Path is not a directory" });
res
.status(400)
.json({ success: false, error: "Path is not a directory" });
return;
}
@@ -688,7 +752,8 @@ export function createFsRoutes(_events: EventEmitter): Router {
} catch (error) {
res.status(400).json({
success: false,
error: error instanceof Error ? error.message : "Failed to read directory",
error:
error instanceof Error ? error.message : "Failed to read directory",
});
}
} catch (error) {

View File

@@ -32,7 +32,15 @@ interface Feature {
priority?: number;
spec?: string;
model?: string; // Model to use for this feature
imagePaths?: Array<string | { path: string; filename?: string; mimeType?: string; [key: string]: unknown }>;
imagePaths?: Array<
| string
| {
path: string;
filename?: string;
mimeType?: string;
[key: string]: unknown;
}
>;
}
interface RunningFeature {
@@ -78,7 +86,7 @@ export class AutoModeService {
projectPath,
};
this.emitAutoModeEvent("auto_mode_complete", {
this.emitAutoModeEvent("auto_mode_started", {
message: `Auto mode started with max ${maxConcurrency} concurrent features`,
projectPath,
});
@@ -111,8 +119,9 @@ export class AutoModeService {
);
if (pendingFeatures.length === 0) {
this.emitAutoModeEvent("auto_mode_complete", {
this.emitAutoModeEvent("auto_mode_idle", {
message: "No pending features - auto mode idle",
projectPath: this.config!.projectPath,
});
await this.sleep(10000);
continue;
@@ -143,8 +152,9 @@ export class AutoModeService {
}
this.autoLoopRunning = false;
this.emitAutoModeEvent("auto_mode_complete", {
this.emitAutoModeEvent("auto_mode_stopped", {
message: "Auto mode stopped",
projectPath: this.config?.projectPath,
});
}
@@ -230,10 +240,19 @@ export class AutoModeService {
// Get model from feature
const model = resolveModelString(feature.model, DEFAULT_MODELS.claude);
console.log(`[AutoMode] Executing feature ${featureId} with model: ${model}`);
console.log(
`[AutoMode] Executing feature ${featureId} with model: ${model}`
);
// Run the agent with the feature's model and images
await this.runAgent(workDir, featureId, prompt, abortController, imagePaths, model);
await this.runAgent(
workDir,
featureId,
prompt,
abortController,
imagePaths,
model
);
// Mark as waiting_approval for user review
await this.updateFeatureStatus(
@@ -422,7 +441,9 @@ Address the follow-up instructions above. Review the previous work and make the
try {
// Get model from feature (already loaded above)
const model = resolveModelString(feature?.model, DEFAULT_MODELS.claude);
console.log(`[AutoMode] Follow-up for feature ${featureId} using model: ${model}`);
console.log(
`[AutoMode] Follow-up for feature ${featureId} using model: ${model}`
);
// Update feature status to in_progress
await this.updateFeatureStatus(projectPath, featureId, "in_progress");
@@ -458,9 +479,11 @@ Address the follow-up instructions above. Review the previous work and make the
filename
);
copiedImagePaths.push(relativePath);
} catch (error) {
console.error(`[AutoMode] Failed to copy follow-up image ${imagePath}:`, error);
console.error(
`[AutoMode] Failed to copy follow-up image ${imagePath}:`,
error
);
}
}
}
@@ -506,7 +529,14 @@ Address the follow-up instructions above. Review the previous work and make the
}
// Use fullPrompt (already built above) with model and all images
await this.runAgent(workDir, featureId, fullPrompt, abortController, allImagePaths.length > 0 ? allImagePaths : imagePaths, model);
await this.runAgent(
workDir,
featureId,
fullPrompt,
abortController,
allImagePaths.length > 0 ? allImagePaths : imagePaths,
model
);
// Mark as waiting_approval for user review
await this.updateFeatureStatus(
@@ -717,7 +747,10 @@ Format your response as a structured markdown document.`;
try {
// Use default Claude model for analysis (can be overridden in the future)
const analysisModel = resolveModelString(undefined, DEFAULT_MODELS.claude);
const analysisModel = resolveModelString(
undefined,
DEFAULT_MODELS.claude
);
const provider = ProviderFactory.getProviderForModel(analysisModel);
const options: ExecuteOptions = {
@@ -917,7 +950,11 @@ Format your response as a structured markdown document.`;
try {
const data = await fs.readFile(featurePath, "utf-8");
const feature = JSON.parse(data);
if (feature.status === "pending" || feature.status === "ready") {
if (
feature.status === "pending" ||
feature.status === "ready" ||
feature.status === "backlog"
) {
features.push(feature);
}
} catch {
@@ -998,9 +1035,15 @@ ${feature.spec}
const imagesList = feature.imagePaths
.map((img, idx) => {
const path = typeof img === "string" ? img : img.path;
const filename = typeof img === "string" ? path.split("/").pop() : img.filename || path.split("/").pop();
const mimeType = typeof img === "string" ? "image/*" : img.mimeType || "image/*";
return ` ${idx + 1}. ${filename} (${mimeType})\n Path: ${path}`;
const filename =
typeof img === "string"
? path.split("/").pop()
: img.filename || path.split("/").pop();
const mimeType =
typeof img === "string" ? "image/*" : img.mimeType || "image/*";
return ` ${
idx + 1
}. ${filename} (${mimeType})\n Path: ${path}`;
})
.join("\n");
@@ -1038,7 +1081,9 @@ When done, summarize what you implemented and any notes for the developer.`;
model?: string
): Promise<void> {
const finalModel = resolveModelString(model, DEFAULT_MODELS.claude);
console.log(`[AutoMode] runAgent called for feature ${featureId} with model: ${finalModel}`);
console.log(
`[AutoMode] runAgent called for feature ${featureId} with model: ${finalModel}`
);
// Get provider for this model
const provider = ProviderFactory.getProviderForModel(finalModel);
@@ -1060,14 +1105,7 @@ When done, summarize what you implemented and any notes for the developer.`;
model: finalModel,
maxTurns: 50,
cwd: workDir,
allowedTools: [
"Read",
"Write",
"Edit",
"Glob",
"Grep",
"Bash",
],
allowedTools: ["Read", "Write", "Edit", "Glob", "Grep", "Bash"],
abortController,
};
@@ -1089,12 +1127,15 @@ When done, summarize what you implemented and any notes for the developer.`;
responseText = block.text || "";
// Check for authentication errors in the response
if (block.text && (block.text.includes("Invalid API key") ||
if (
block.text &&
(block.text.includes("Invalid API key") ||
block.text.includes("authentication_failed") ||
block.text.includes("Fix external API key"))) {
block.text.includes("Fix external API key"))
) {
throw new Error(
"Authentication failed: Invalid or expired API key. " +
"Please check your ANTHROPIC_API_KEY or GOOGLE_API_KEY, or run 'claude login' to re-authenticate."
"Please check your ANTHROPIC_API_KEY or GOOGLE_API_KEY, or run 'claude login' to re-authenticate."
);
}