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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions apps/server/src/lib/sdk-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,11 @@ export interface CreateSdkOptionsConfig {

/** Extended thinking level for Claude models */
thinkingLevel?: ThinkingLevel;

/** Optional user-configured max turns override (from settings).
* When provided, overrides the preset MAX_TURNS for the use case.
* Range: 1-2000. */
maxTurns?: number;
}

// Re-export MCP types from @automaker/types for convenience
Expand Down Expand Up @@ -403,7 +408,7 @@ export function createSpecGenerationOptions(config: CreateSdkOptionsConfig): Opt
// See: https://github.com/AutoMaker-Org/automaker/issues/149
permissionMode: 'default',
model: getModelForUseCase('spec', config.model),
maxTurns: MAX_TURNS.maximum,
maxTurns: config.maxTurns ?? MAX_TURNS.maximum,
cwd: config.cwd,
allowedTools: [...TOOL_PRESETS.specGeneration],
...claudeMdOptions,
Expand Down Expand Up @@ -437,7 +442,7 @@ export function createFeatureGenerationOptions(config: CreateSdkOptionsConfig):
// Override permissionMode - feature generation only needs read-only tools
permissionMode: 'default',
model: getModelForUseCase('features', config.model),
maxTurns: MAX_TURNS.quick,
maxTurns: config.maxTurns ?? MAX_TURNS.quick,
cwd: config.cwd,
allowedTools: [...TOOL_PRESETS.readOnly],
...claudeMdOptions,
Expand Down Expand Up @@ -468,7 +473,7 @@ export function createSuggestionsOptions(config: CreateSdkOptionsConfig): Option
return {
...getBaseOptions(),
model: getModelForUseCase('suggestions', config.model),
maxTurns: MAX_TURNS.extended,
maxTurns: config.maxTurns ?? MAX_TURNS.extended,
cwd: config.cwd,
allowedTools: [...TOOL_PRESETS.readOnly],
...claudeMdOptions,
Expand Down Expand Up @@ -506,7 +511,7 @@ export function createChatOptions(config: CreateSdkOptionsConfig): Options {
return {
...getBaseOptions(),
model: getModelForUseCase('chat', effectiveModel),
maxTurns: MAX_TURNS.standard,
maxTurns: config.maxTurns ?? MAX_TURNS.standard,
cwd: config.cwd,
allowedTools: [...TOOL_PRESETS.chat],
...claudeMdOptions,
Expand Down Expand Up @@ -541,7 +546,7 @@ export function createAutoModeOptions(config: CreateSdkOptionsConfig): Options {
return {
...getBaseOptions(),
model: getModelForUseCase('auto', config.model),
maxTurns: MAX_TURNS.maximum,
maxTurns: config.maxTurns ?? MAX_TURNS.maximum,
cwd: config.cwd,
allowedTools: [...TOOL_PRESETS.fullAccess],
...claudeMdOptions,
Expand Down
50 changes: 46 additions & 4 deletions apps/server/src/lib/settings-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,16 @@ import {

const logger = createLogger('SettingsHelper');

/** Default number of agent turns used when no value is configured. */
export const DEFAULT_MAX_TURNS = 1000;

/** Upper bound for the max-turns clamp; values above this are capped here. */
export const MAX_ALLOWED_TURNS = 2000;

/**
* Get the autoLoadClaudeMd setting, with project settings taking precedence over global.
* Returns false if settings service is not available.
* Falls back to global settings and defaults to true when unset.
* Returns true if settings service is not available.
*
* @param projectPath - Path to the project
* @param settingsService - Optional settings service instance
Expand All @@ -48,8 +55,8 @@ export async function getAutoLoadClaudeMdSetting(
logPrefix = '[SettingsHelper]'
): Promise<boolean> {
if (!settingsService) {
logger.info(`${logPrefix} SettingsService not available, autoLoadClaudeMd disabled`);
return false;
logger.info(`${logPrefix} SettingsService not available, autoLoadClaudeMd defaulting to true`);
return true;
}

try {
Expand All @@ -64,7 +71,7 @@ export async function getAutoLoadClaudeMdSetting(

// Fall back to global settings
const globalSettings = await settingsService.getGlobalSettings();
const result = globalSettings.autoLoadClaudeMd ?? false;
const result = globalSettings.autoLoadClaudeMd ?? true;
logger.info(`${logPrefix} autoLoadClaudeMd from global settings: ${result}`);
return result;
} catch (error) {
Expand All @@ -73,6 +80,41 @@ export async function getAutoLoadClaudeMdSetting(
}
}

/**
* Get the default max turns setting from global settings.
*
* Reads the user's configured `defaultMaxTurns` setting, which controls the maximum
* number of agent turns (tool-call round-trips) for feature execution.
*
* @param settingsService - Settings service instance (may be null)
* @param logPrefix - Logging prefix for debugging
* @returns The user's configured max turns, or {@link DEFAULT_MAX_TURNS} as default
*/
export async function getDefaultMaxTurnsSetting(
settingsService?: SettingsService | null,
logPrefix = '[SettingsHelper]'
): Promise<number> {
if (!settingsService) {
logger.info(
`${logPrefix} SettingsService not available, using default maxTurns=${DEFAULT_MAX_TURNS}`
);
return DEFAULT_MAX_TURNS;
}

try {
const globalSettings = await settingsService.getGlobalSettings();
const raw = globalSettings.defaultMaxTurns;
const result = Number.isFinite(raw) ? (raw as number) : DEFAULT_MAX_TURNS;
// Clamp to valid range
const clamped = Math.max(1, Math.min(MAX_ALLOWED_TURNS, Math.floor(result)));
logger.debug(`${logPrefix} defaultMaxTurns from global settings: ${clamped}`);
return clamped;
} catch (error) {
logger.error(`${logPrefix} Failed to load defaultMaxTurns setting:`, error);
return DEFAULT_MAX_TURNS;
}
}

/**
* Filters out CLAUDE.md from context files when autoLoadClaudeMd is enabled
* and rebuilds the formatted prompt without it.
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/providers/claude-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ export class ClaudeProvider extends BaseProvider {
model,
cwd,
systemPrompt,
maxTurns = 100,
maxTurns = 1000,
allowedTools,
abortController,
conversationHistory,
Expand Down
10 changes: 10 additions & 0 deletions apps/server/src/providers/codex-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -738,6 +738,16 @@ export class CodexProvider extends BaseProvider {
);
const baseSystemPrompt = resolveSystemPrompt(options.systemPrompt);
const resolvedMaxTurns = resolveMaxTurns(options.maxTurns);
if (resolvedMaxTurns === null && options.maxTurns === undefined) {
logger.warn(
`[executeQuery] maxTurns not provided — Codex CLI will use its internal default. ` +
`This may cause premature completion. Model: ${options.model}`
);
} else {
logger.info(
`[executeQuery] maxTurns: requested=${options.maxTurns}, resolved=${resolvedMaxTurns}, model=${options.model}`
);
}
const resolvedAllowedTools = options.allowedTools ?? Array.from(DEFAULT_ALLOWED_TOOLS);
const restrictTools = !hasMcpServers || options.mcpUnrestrictedTools === false;
const wantsOutputSchema = Boolean(
Expand Down
77 changes: 76 additions & 1 deletion apps/server/src/routes/worktree/routes/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
* 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
* 3. Syncs the base branch from its remote tracking branch (fast-forward only)
* 4. Only creates a new worktree if none exists for the branch
*/

import type { Request, Response } from 'express';
Expand All @@ -27,6 +28,10 @@ import { execGitCommand } from '../../../lib/git.js';
import { trackBranch } from './branch-tracking.js';
import { createLogger } from '@automaker/utils';
import { runInitScript } from '../../../services/init-script-service.js';
import {
syncBaseBranch,
type BaseBranchSyncResult,
} from '../../../services/branch-sync-service.js';

const logger = createLogger('Worktree');

Expand Down Expand Up @@ -193,6 +198,52 @@ export function createCreateHandler(events: EventEmitter, settingsService?: Sett
logger.warn(`Failed to fetch from remotes: ${getErrorMessage(fetchErr)}`);
}

// Sync the base branch with its remote tracking branch (fast-forward only).
// This ensures the new worktree starts from an up-to-date state rather than
// a potentially stale local copy. If the sync fails or the branch has diverged,
// we proceed with the local copy and inform the user.
const effectiveBase = baseBranch || 'HEAD';
let syncResult: BaseBranchSyncResult = { attempted: false, synced: false };

// Only sync if the base is a real branch (not 'HEAD')
// Pass skipFetch=true because we already fetched all remotes above.
if (effectiveBase !== 'HEAD') {
logger.info(`Syncing base branch '${effectiveBase}' before creating worktree`);
syncResult = await syncBaseBranch(projectPath, effectiveBase, true);
if (syncResult.attempted) {
if (syncResult.synced) {
logger.info(`Base branch sync result: ${syncResult.message}`);
} else {
logger.warn(`Base branch sync result: ${syncResult.message}`);
}
}
} else {
// When using HEAD, try to sync the currently checked-out branch
// Pass skipFetch=true because we already fetched all remotes above.
try {
const currentBranch = await execGitCommand(
['rev-parse', '--abbrev-ref', 'HEAD'],
projectPath
);
const trimmedBranch = currentBranch.trim();
if (trimmedBranch && trimmedBranch !== 'HEAD') {
logger.info(
`Syncing current branch '${trimmedBranch}' (HEAD) before creating worktree`
);
syncResult = await syncBaseBranch(projectPath, trimmedBranch, true);
if (syncResult.attempted) {
if (syncResult.synced) {
logger.info(`HEAD branch sync result: ${syncResult.message}`);
} else {
logger.warn(`HEAD branch sync result: ${syncResult.message}`);
}
}
}
} catch {
// Could not determine HEAD branch — skip sync
}
}

// Check if branch exists (using array arguments to prevent injection)
let branchExists = false;
try {
Expand Down Expand Up @@ -226,6 +277,19 @@ export function createCreateHandler(events: EventEmitter, settingsService?: Sett
// normalizePath converts to forward slashes for API consistency
const absoluteWorktreePath = path.resolve(worktreePath);

// Get the commit hash the new worktree is based on for logging
let baseCommitHash: string | undefined;
try {
const hash = await execGitCommand(['rev-parse', '--short', 'HEAD'], absoluteWorktreePath);
baseCommitHash = hash.trim();
} catch {
// Non-critical — just for logging
}

if (baseCommitHash) {
logger.info(`New worktree for '${branchName}' based on commit ${baseCommitHash}`);
}

// Copy configured files into the new worktree before responding
// This runs synchronously to ensure files are in place before any init script
try {
Expand All @@ -247,6 +311,17 @@ export function createCreateHandler(events: EventEmitter, settingsService?: Sett
path: normalizePath(absoluteWorktreePath),
branch: branchName,
isNew: !branchExists,
baseCommitHash,
...(syncResult.attempted
? {
syncResult: {
synced: syncResult.synced,
remote: syncResult.remote,
message: syncResult.message,
diverged: syncResult.diverged,
},
}
: {}),
},
});

Expand Down
44 changes: 35 additions & 9 deletions apps/server/src/services/agent-executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ export type {

const logger = createLogger('AgentExecutor');

const DEFAULT_MAX_TURNS = 1000;

export class AgentExecutor {
private static readonly WRITE_DEBOUNCE_MS = 500;
private static readonly STREAM_HEARTBEAT_MS = 15_000;
Expand Down Expand Up @@ -99,10 +101,22 @@ export class AgentExecutor {
workDir,
false
);
const resolvedMaxTurns = sdkOptions?.maxTurns ?? DEFAULT_MAX_TURNS;
if (sdkOptions?.maxTurns == null) {
logger.info(
`[execute] Feature ${featureId}: sdkOptions.maxTurns is not set, defaulting to ${resolvedMaxTurns}. ` +
`Model: ${effectiveBareModel}`
);
} else {
logger.info(
`[execute] Feature ${featureId}: maxTurns=${resolvedMaxTurns}, model=${effectiveBareModel}`
);
}

const executeOptions: ExecuteOptions = {
prompt: promptContent,
model: effectiveBareModel,
maxTurns: sdkOptions?.maxTurns,
maxTurns: resolvedMaxTurns,
cwd: workDir,
allowedTools: sdkOptions?.allowedTools as string[] | undefined,
abortController,
Expand Down Expand Up @@ -279,6 +293,17 @@ export class AgentExecutor {
throw new Error(AgentExecutor.sanitizeProviderError(msg.error));
} else if (msg.type === 'result' && msg.subtype === 'success') scheduleWrite();
}
} finally {
clearInterval(streamHeartbeat);
if (writeTimeout) clearTimeout(writeTimeout);
if (rawWriteTimeout) clearTimeout(rawWriteTimeout);

const streamElapsedMs = Date.now() - streamStartTime;
logger.info(
`[execute] Stream ended for feature ${featureId} after ${Math.round(streamElapsedMs / 1000)}s. ` +
`aborted=${aborted}, specDetected=${specDetected}, responseLength=${responseText.length}`
);

await writeToFile();
if (enableRawOutput && rawOutputLines.length > 0) {
try {
Expand All @@ -288,10 +313,6 @@ export class AgentExecutor {
/* ignore */
}
}
} finally {
clearInterval(streamHeartbeat);
if (writeTimeout) clearTimeout(writeTimeout);
if (rawWriteTimeout) clearTimeout(rawWriteTimeout);
}
return { responseText, specDetected, tasksCompleted, aborted };
}
Expand Down Expand Up @@ -351,8 +372,13 @@ export class AgentExecutor {
taskPrompts.taskExecution.taskPromptTemplate,
userFeedback
);
const taskMaxTurns = sdkOptions?.maxTurns ?? DEFAULT_MAX_TURNS;
logger.info(
`[executeTasksLoop] Feature ${featureId}, task ${task.id} (${taskIndex + 1}/${tasks.length}): ` +
`maxTurns=${taskMaxTurns} (sdkOptions.maxTurns=${sdkOptions?.maxTurns ?? 'undefined'})`
);
const taskStream = provider.executeQuery(
this.buildExecOpts(options, taskPrompt, Math.min(sdkOptions?.maxTurns ?? 100, 100))
this.buildExecOpts(options, taskPrompt, taskMaxTurns)
);
let taskOutput = '',
taskStartDetected = false,
Expand Down Expand Up @@ -571,7 +597,7 @@ export class AgentExecutor {
});
let revText = '';
for await (const msg of provider.executeQuery(
this.buildExecOpts(options, revPrompt, sdkOptions?.maxTurns ?? 100)
this.buildExecOpts(options, revPrompt, sdkOptions?.maxTurns ?? DEFAULT_MAX_TURNS)
)) {
if (msg.type === 'assistant' && msg.message?.content)
for (const b of msg.message.content)
Expand Down Expand Up @@ -657,7 +683,7 @@ export class AgentExecutor {
return { responseText, tasksCompleted };
}

private buildExecOpts(o: AgentExecutionOptions, prompt: string, maxTurns?: number) {
private buildExecOpts(o: AgentExecutionOptions, prompt: string, maxTurns: number) {
return {
prompt,
model: o.effectiveBareModel,
Expand Down Expand Up @@ -689,7 +715,7 @@ export class AgentExecutor {
.replace(/\{\{approvedPlan\}\}/g, planContent);
let responseText = initialResponseText;
for await (const msg of provider.executeQuery(
this.buildExecOpts(options, contPrompt, options.sdkOptions?.maxTurns)
this.buildExecOpts(options, contPrompt, options.sdkOptions?.maxTurns ?? DEFAULT_MAX_TURNS)
)) {
if (msg.type === 'assistant' && msg.message?.content)
for (const b of msg.message.content) {
Expand Down
Loading